Damir Damir - 1 year ago 77
Python Question

How to heapify by field from custom objects

I am receiving on server objects from clients ( every object has same structure and have field self.utc_time which contains time of creation of that object). I need to store in some structure so I always have sorted in ascending so when I pop I pop the oldest object by utc_time, not by time when I receive. I thought to use priority queue from heapq but how to say to heaify by utc_time field from custom objects ? Is there better solution ?

Answer Source

Add the magic __cmp__ comparison method to your class to avoid needing to do the tuple-decoration that Maksim describes:

>>> import heapq
>>> class MyObject(object):
...     def __init__(self, val):
...         self.val = val
...     def __cmp__(self, other):
...         return cmp(self.val, other.val)
>>> q = []
>>> heapq.heappush(q, MyObject(50))
>>> heapq.heappush(q, MyObject(40))
>>> heapq.heappush(q, MyObject(30))
>>> heapq.heappush(q, MyObject(20))
>>> heapq.heappush(q, MyObject(200))
>>> obj = heapq.heappop(q)
>>> print obj.val