Stackoverflow question: Is there a built-in identity function in Python?

Ethan Furman ethan at stoneleaf.us
Thu Dec 7 15:10:47 EST 2017


On 12/07/2017 11:46 AM, Paul Moore wrote:
> On 7 December 2017 at 18:28, Ethan Furman <ethan at stoneleaf.us> wrote:
>> The simple answer is No, and all the answers agree on that point.
>>
>> It does beg the question of what an identity function is, though.
>>
>> My contention is that an identity function is a do-nothing function that
>> simply returns what it was given:
>>
>> --> identity(1)
>> 1
>>
>> --> identity('spam')
>> 'spam'
>>
>> --> identity('spam', 'eggs', 7)
>> ('spam', 'eggs', 7)
>>
>> Of the five answers to that SO question, mine is the only one that will
>> correctly handle those three examples.  If you agree with my contention feel
>> free to up-vote my answer.  :)
>
> IMO (as a mathematician ;-)) the identity function is a
> *single-argument* function that returns the value passed to it. So:
>
>      def identity(x):
>          return x
>
> See https://en.wikipedia.org/wiki/Identity_function
>
> identity(1,2) is an error.
>
> Extending the definition to multiple arguments causes all sorts of
> confusion, as you've seen.

So in other words:

for thing in (
         1,
         (2, 3),
         'spam',
         ('eggs', 'green', 4.15),
         (1, ),
     ):
     assert thing == identity(thing)

try:
     identity('too', 'many', 'things')
except TypeError:
     pass
else:
     raise Exception('identity should only be passed a single item')

Thank you for clearing that up, Paul!

I up-voted your answer, hopefully others will also: https://stackoverflow.com/a/47702881/208880

--
~Ethan~



More information about the Python-list mailing list