Search code examples
python-3.xdeque

How to work with a python collections.deque of custom class instances?


I am trying to utilize python deque from collections module where the element inside the deque is a custom class instances. I want to know how I can erase/delete an object? Can I use the builtin methods like deque.remove(element) if yes, how? How would it find my custom object?

class Buffer(object):

    """ """
    def __init__(self, name, size_total, size_in_cache):
        self.name = name
        self.size_total = size_total

 class Storage(object):
    """
    """
    def __init__(self, capacity):
        self.CAPACITY = capacity
        self.contents = collections.deque()
        self.capacity_used = 0      

    def push_to_contents(self, buffer_name, buffer_size):
        buf = Buffer(buffer_name, buffer_size)
        self.contents.appendleft(buf)

    def delete_from_contents(self, buffer_name)
        """ HOW??
        How can I use self.contents.remove() here>      
        """

Solution

  • The way collections.deque.remove operates is by comparing the argument to each item in the deque. If it finds something which is equal to the argument, it removes it. Otherwise, it raises a ValueError.

    Since a Buffer object, as you've implemented it, doesn't know how to compare itself with other objects, Python defaults (using the object parent class) to comparing the id values.

    However, if you were to implement the __eq__ method for your class, you could accomplish what you're looking for.

    E.g.,

    def __eq__(self, other):
        if isinstance(other, Buffer):
            return self.name == other.name and self.size_total == other.size_total
        elif isinstance(other, str):
            return self.name == other
        else:
            return NotImplemented
    

    EDIT:

    This is all fine and good if you're using Python 3. In Python 2, you have to implement __ne__ ("not equal") as well. It can be as simple as

    def __ne__(self, other):
        return not self == other
    

    Python 3 takes care of this for you automatically.