1

In functional programming is sometimes useful to have an identity function. Is there a built-in or a function defined in some module that does this?

0

1 Answer 1

5

The identity function can be simply defined as:

identity = lambda x: x

I'm not aware of this function defined in any module, but it could be a good fit for functools.

Sign up to request clarification or add additional context in comments.

3 Comments

Do you people think it could be good to open a PEP?
Although it is clean in this case, assigning a lambda to a variable is against the PEP-8 standards. So adding it to functools might actually make sense here.
The identity function is useful if you are sub-classing a class that uses a transform function as one of it's attributes and you want to be able to support a NOP function for those sub-classes that don't need one, or perhaps default the super class to identity. You can always assign None but then that requires a check for None which can interrupt a convenient generator or comprehension.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.