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?
1 Answer
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.
3 Comments
enrico.bacis
Do you people think it could be good to open a PEP?
Ivo Merchiers
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.
NeilG
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.