I have multiple subclasses of a superclass that store something in a instance_of_a_class.value and I override __cmp__() to provide reasonable ==, <, > etc. comparisons.
However, I have multiple places in my code where I do
min(list_of_instances_of_class, key=lambda _: _.value) or max(list_of_instances_of_class, key=lambda _: _.value) and an occasional sorted(...
Is there a function to override in the class so that I don’t have to specify the key function for each call to the said functions or do I need to subclass list and override the max, min and sorted methods?
Just implement
__lt__:__cmp__is deprecated, and all of the functions that you mentioned use only__lt__not the other comparisons.If for some reason you really can’t have them compare this way, you can do something like:
Where you call them just as
maxval(obj_list)instead ofmax(obj_list)etc., andsortval(obj_list)to sort in-place instead ofobj_list.sort()