Is there a builtin identity function in python? Is there a builtin identity function in python? python-3.x python-3.x

Is there a builtin identity function in python?


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
  • disadvantage: takes exactly 1 positional parameter


An identity function, as defined in https://en.wikipedia.org/wiki/Identity_function, takes a single argument and returns it unchanged:

def identity(x):    return x

What you are asking for when you say you want the signature def identity(*args) is not strictly an identity function, as you want it to take multiple arguments. That's fine, but then you hit a problem as Python functions don't return multiple results, so you have to find a way of cramming all of those arguments into one return value.

The usual way of returning "multiple values" in Python is to return a tuple of the values - technically that's one return value but it can be used in most contexts as if it were multiple values. But doing that here means you get

>>> def mv_identity(*args):...     return args...>>> mv_identity(1,2,3)(1, 2, 3)>>> # So far, so good. But what happens now with single arguments?>>> mv_identity(1)(1,)

And fixing that problem quickly gives other issues, as the various answers here have shown.

So, in summary, there's no identity function defined in Python because:

  1. The formal definition (a single argument function) isn't that useful, and is trivial to write.
  2. Extending the definition to multiple arguments is not well-defined in general, and you're far better off defining your own version that works the way you need it to for your particular situation.

For your precise case,

def dummy_gettext(message):    return message

is almost certainly what you want - a function that has the same calling convention and return as gettext.gettext, which returns its argument unchanged, and is clearly named to describe what it does and where it's intended to be used. I'd be pretty shocked if performance were a crucial consideration here.


yours will work fine. When the number of parameters is fix you can use an anonymous function like this:

lambda x: x