Reputation: 8247
I have a function where I want to allow passing in an optional sorting function. If no function is passed in, I want to sort with the default function. Is there a better way than one of these options?
def do_the_thing(self, sort_func=None):
if sort_func is None:
for item in sorted(self.items):
....
else:
for item in sorted(self.items, key=sort_func):
....
def do_the_thing(self, sort_func=lambda x: x):
for item in sorted(self.items, key=sort_func):
....
Upvotes: 4
Views: 497
Reputation: 27283
Just use None
, sorted
understands that:
>>> sorted([6,2,5,1], key=None)
[1, 2, 5, 6]
An identity function was proposed, but rejected.
Upvotes: 3