Is there a builtin identity function in python?

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 wont 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


_ = lambda x: x
  • advantage: doesnt change the type of the parameter
  • disadvantage: takes exactly 1 positional parameter

An identity function, as defined in, 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. Thats fine, but then you hit a problem as Python functions dont 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 thats 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)

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

So, in summary, theres no identity function defined in Python because:

  1. The formal definition (a single argument function) isnt that useful, and is trivial to write.
  2. Extending the definition to multiple arguments is not well-defined in general, and youre 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 its intended to be used. Id be pretty shocked if performance were a crucial consideration here.

Is there a builtin identity function in python?

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

lambda x: x

Leave a Reply

Your email address will not be published. Required fields are marked *