Stackoverflow question: Is there a built-in identity function in Python?
Peter Otten
__peter__ at web.de
Thu Dec 7 15:24:40 EST 2017
Ethan Furman wrote:
> On 12/07/2017 10:53 AM, Peter Otten wrote:
>> Ethan Furman 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)
>>
>> Hm, what does -- and what should --
>>
>> identity(('spam', 'eggs', 7))
>>
>> produce?
>
> Well, since it's the lowly "," that makes a tuple (not the parentheses),
> those extra parentheses don't have any affect.
identity((a, b, c))
calls identity() with one argument whereas
identity(a, b, c)
calls identity() with three arguments. That's certainly an effect; you just
undo it with your test for len(args) == 1. That means that your identity()
function throws away the information about the number of arguments it was
called with. I would expect an identity() function to be lossless
("bijective") and I think that is possible only if you restrict it to a
single argument.
>
> If you were trying to get a 3-item tuple inside a 1-item tuple:
>
> (('spam', 'eggs', 7), )
>
> Then you would need:
>
> --> identity( (('spam', 'eggs', 7), ) )
> (('spam', 'eggs', 7),)
>
> Okay, actually sometimes it takes both. ;)
>
> --
> ~Ethan~
More information about the Python-list
mailing list