◐ Shell
clean mode source ↗

Message 273643 - Python tracker

An identity function is sometimes useful in functional-style programming as a dummy or default value.

For example, we can sometimes see a pattern like this (e.g. in itertools.groupby):

def f(params, key=None):
  if key is None:
    key = lambda x: x
  ...


However, if we had a canonical itentity function:

def identity(x):
  return x

we could instead write:

def f(params, key=identity):
  ...

and the intended use of the function f and it's functioning would be more obvious simply from it's signature, while also saving a little code. 

As zen of Python says: Explicit is better than implicit.

Of course, we can now write:

def f(params, key=lambda x: x):
  ...

but the reason why is not used is probably that it feels a bit awkward to more people than just me.