Search code examples
pythonqueueidentityequality

Equality and identity of Queues


Will two queue.Queue instances ever be equal or identical?

I have some code where Queue instances are created, appended to a list and later removed.

l = []

def example():
    q = Queue()
    l.append(q)
    thingy = q.get()    # wait on background worker thread to put something in queue
    # ... do something with thingy ...
    l.remove(q)

For (I think irrelevant) context, other threads in the wider program will be putting their own Queues into the list, and there is also a background worker thread which will be putting objects into the Queues it finds in the list.

I understand that list.remove() first checks for identity and then checks for equality. Therefore I want to know if two Queue instances will ever be evaluated as equal or identical.


Solution

  • Two objects are equal (==) if one of their __eq__ methods evaluate as True.

    Two objects are identical (is) if they are in fact the same object at the same memory address.

    If a class (or its parents) do not implement the __eq__ method, then an equality comparison falls back to being an identity comparison.

    The Queue class does not implement __eq__ so two Queue object will only ever be equal if they are in fact identical.

    This can be demonstrated by the fact that Queue() == Queue() is False.