This code seems to smell:
result = None
for item in list:
if result is None:
result = item.foo(args)
else:
if ClassFred.objects.get(arg1=result) < ClassFred.objects.get(arg1=item.foo(args)):
result = item.foo(args)
The smelliest part is the utility of ‘result’. Would anyone be kind enough sniff it for me?
The min function compares the given items and returns the minimum one (of course :P). What isn’t obvious at first is you can control what value is used to compare them, this is the ‘key’ parameter.
The key function computes the “comparison key”, and that is what is used to compare. The default key function is identity, where the comparison key for an item is the item itself.
Another example:
Your code above is using
item.foo(args)as values, where item comes from your list; but the result of passing that throughClassFred.objects.get(arg1=..)is used to compare. This means that construct is your key function:My code at the top just puts this together in one statement.