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?

enrico.bacis
  • 30,497
  • 10
  • 86
  • 115

1 Answers1

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.

enrico.bacis
  • 30,497
  • 10
  • 86
  • 115
  • 3
    Do you people think it could be good to open a *PEP*? – enrico.bacis Jan 21 '16 at 14:37
  • 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. – Ivo Merchiers May 20 '19 at 11:44
  • 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. – NeilG Nov 19 '21 at 07:19