I am trying to insert some objects into a PriorityQueue. I have not implemented any methods that compare objects of the class because there are many ways that the objects could be ordered.
One approach that I saw was to insert the objects into the PriorityQueue as a tuple as (obj.property, obj). The problem with this approach for me is that obj.property is often the same for multiple objects and so I then get a TypeError becaue object is an unorderable type.
What I would like to do is tell the PriorityQueue to sort on obj.property and then I don't care what order objects come out if their property is the same.
What is the best way to do this?
According to the docs:
The lowest valued entries are retrieved first (the lowest valued entry is the one returned by sorted(list(entries))[0]). A typical pattern for entries is a tuple in the form: (priority_number, data).
Update:
You can create a triple to avoid duplicates, like this:
>>> import queue
>>> class Foo(object):
... def __init__(self, bar):
... self.bar = bar
...
>>> f1 = Foo('foo')
>>> f2 = Foo('bar')
>>> f3 = Foo('baz')
>>> f4 = Foo('bar')
>>> q = queue.PriorityQueue()
>>> q.put((5,0,f1))
>>> q.put((3,0,f2))
>>> q.put((3,1,f3))
>>> q.put((1,0,f4))
Or alternatively (possibly cleaner), implement the magic methods:
>>> import queue
>>> q = queue.PriorityQueue()
>>> class Foo(object):
... def __init__(self, bar):
... self.bar = bar
... def __eq__(self, other):
... return self.bar == other.bar
... def __ne__(self, other):
... return self.bar != other.bar
... def __lt__(self, other):
... return self.bar < other.bar
... def __gt__(self, other):
... return self.bar > other.bar
... def __le__(self, other):
... return self.bar <= other.bar
... def __ge__(self, other):
... return self.bar >= other.bar
...
>>> f1 = Foo('foo')
>>> f2 = Foo('bar')
>>> f3 = Foo('baz')
>>> f4 = Foo('baa')
>>> f5 = Foo('baz')
>>> q.put(f1)
>>> q.put(f2)
>>> q.put(f3)
>>> q.put(f4)
>>> q.put(f5)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With