[Python-ideas] Add an identity function

Rob Cliffe rob.cliffe at btinternet.com
Sun Aug 7 10:21:45 CEST 2011


On 07/08/2011 03:07, dag.odenhall at gmail.com wrote:
>> So, while I want an identity function, I don't want an identity function
>> which requires actually calling a function at runtime. What I really want is
>> compiler black magic, so that I can write:
>>
>> def len_sum(iterable, transformation=None):
>>     """Sum iterable, returning length and sum in one pass."""
>>     count = 0
>>     total = 0
>>     for x in iterable:
>>         count += 1
>>         total += transformation(x)
>>     return count, total
>>
>>
>> and the compiler is smart enough to do the Right Thing for me, without
>> either the need to repeat code, or the function call overhead. (And also a
>> pony.) Without that level of black magic, I don't think adding an identity
>> function to the standard library is worth the time or effort.
> -1 on silently pretending that None is callable as the identity
> function. If you have an actual function, an optimizer could probably
> strip it away in cases like len_sum.
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> http://mail.python.org/mailman/listinfo/python-ideas
>
How about (for this use case at any rate)

         total += x if transformation is None else transformation(x)
         # avoids unnecessary function call, fairly readable IMO

Rob Cliffe



More information about the Python-ideas mailing list