What is the standard way of making a class comparable in Python 3? (For example, by id.)
I just thought of a really hackish way to do it. This is in the same spirit as what you were originally trying to do. It does not require adding any functions to the class object; it works for any class.
max(((f(obj), obj) for obj in obj_list), key=lambda x: x[0])[1]
I really don't like that, so here's something less terse that does the same thing:
def make_pair(f, obj):
return (f(obj), obj)
def gen_pairs(f, obj_list):
return (make_pair(f, obj) for obj in obj_list)
def item0(tup):
return tup[0]
def max_obj(f, obj_list):
pair = max(gen_pairs(f, obj_list), key=item0)
return pair[1]
Or, you could use this one-liner if obj_list
is always an indexable object like a list:
obj_list[max((f(obj), i) for i, obj in enumerate(obj_list))[1]]
This has the advantage that if there are multiple objects such that f(obj)
returns an identical value, you know which one you will get: the one with the highest index, i.e. the latest one in the list. If you wanted the earliest one in the list, you could do that with a key function.