rds rds - 7 months ago 78
Python Question

Is there a builtin identity function in python?

I'd like to point to a function that does nothing:

def identity(*args)
return args


my use case is something like this

try:
gettext.find(...)
...
_ = gettext.gettext
else:
_ = identity


Of course, I could use the
identity
defined above, but a built-in would certainly run faster (and avoid bugs introduced by my own).

Apparently,
map
and
filter
use
None
for the identity, but this is specific to their implementations.

>>> _=None
>>> _("hello")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not callable

rds rds
Answer

Doing some more research, there is none, a feature was asked in issue 1673203 And from Raymond Hettinger said there won't be:

Better to let people write their own trivial pass-throughs and think about the signature and time costs.

So a better way to do it is actually (a lambda avoids naming the function):

_ = lambda *args: args
  • advantage: takes any number of parameters
  • disadvantage: the result is a boxed version of the parameters

OR

_ = lambda x: x
  • advantage: doesn't change the type of the parameter
  • takes exactly 1 positional parameter