xorsyst
xorsyst

Reputation: 8247

How to specify optional sort key in Python

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?

Use if function to avoid passing a key. Fast but code is ugly.

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):
       ....

Use default sort function - slower?

def do_the_thing(self, sort_func=lambda x: x):
  for item in sorted(self.items, key=sort_func):
    ....

Upvotes: 4

Views: 497

Answers (1)

L3viathan
L3viathan

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

Related Questions