[Python-ideas] a identity function?

Raymond Hettinger python at rcn.com
Mon Mar 23 01:27:26 CET 2009

[Benjamin Peterson]
> I've found as I write more and more decorators I need an identity function
> often. For example I might write:
> def replace_maybe(reason):
>    if reason == "good reason":
>        return lambda x: x
>    def decorator(func):
>        # do fancy stuff here
>    return decorator
> I hate lambdas, so usually I write
> def _id(x):
>    return x
> It'd be nice to have a shortcut in the stdlib, though. Would this go well in the
> operator or functools modules well?


I and Paul Rubin considered this a long time ago.  It stayed on the todo
list for a while and then fell by the wayside as its downsides became

One problem is that many of the places whether it is tempting to
use an identity function, it is just a slower way to do something
that we should have used a simple if-statement for.  In your
example, there is no cost, but it is terrible to end-up with variants
of map(func, iterable) where func defaults to lambda x: x. 

The other issue is that different signatures were needed for
different tasks.

    identity = lambda *args: args
    identity = lambda *args:  args[0] if args else None
    identity = lambda x: x

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


More information about the Python-ideas mailing list