This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: heapq: A way to change the compare function
Type: Stage:
Components: Library (Lib) Versions: Python 2.3
process
Status: closed Resolution: rejected
Dependencies: Superseder:
Assigned To: rhettinger Nosy List: mcherm, rhettinger, tebeka
Priority: normal Keywords: patch

Created on 2003-12-28 10:06 by tebeka, last changed 2022-04-11 14:56 by admin. This issue is now closed.

Files
File name Uploaded Description Edit
hq.diff tebeka, 2003-12-28 10:06 Diff for heapq.py and test_heapq.py
Messages (4)
msg45073 - (view) Author: Miki Tebeka (tebeka) * Date: 2003-12-28 10:06
It'd be nice if heapq could use a custom compare function.
This way the user won't need to write a class with <=
method.

I've added set_cmp(cmp=None) for setting the
comparision function. Using cmp and not expliclty <=
makes later changes in implementation easier.

Attached are the diffs.

BTW: I know in CVS heapq is a C module now, don't have
the  time to change my patch...

Miki
msg45074 - (view) Author: Michael Chermside (mcherm) (Python triager) Date: 2003-12-29 14:53
Logged In: YES 
user_id=99874

Can you explain better the motivation for adding this? I don't 
find writing __le__() to be a significant problem normally, and 
setting the global _le seems a less-than-perfect design. What 
is a use case?
msg45075 - (view) Author: Raymond Hettinger (rhettinger) * (Python committer) Date: 2003-12-31 22:54
Logged In: YES 
user_id=80475

There is no shortage of use cases -- sometimes top priorities 
have higher numbers -- the use cases are basically the same 
as those for descending sorts.

The proposed solution must be rejected because the global 
variable would be shared among all modules using heapq.  It 
is possible the one module relies on __le__ while other 
modules might prefer __ge__.  Those modules could be used 
at the same time.

If a non-global solution is found, please re-submit.

msg45076 - (view) Author: Miki Tebeka (tebeka) * Date: 2004-01-01 07:49
Logged In: YES 
user_id=358087

Also just giving a "lambda" is much shorter than writing a
class with __cmp__ which only servers for comparison.

I agree that this is a lame patch but in the current design
of heapq (using build-in lists) the only other solution I
see is to add another "compare" parameter to the module's
functions (e.g. def heappop(heap, compare=None): ...). If
this is acceptable I'll submit a patch.

The other way is to create a new heap object which will be a
subclass of list and will have a "compare" property.
History
Date User Action Args
2022-04-11 14:56:01adminsetgithub: 39735
2003-12-28 10:06:46tebekacreate