[Python-ideas] Add an identity function

Steven D'Aprano steve at pearwood.info
Sun Aug 7 03:28:36 CEST 2011


dag.odenhall at gmail.com wrote:
> Yes, I know, it's merely a (lambda x: x), but I find a need for this
> often enough that dedicated, documented function would help
> readability and encourage certain patterns. Whether it should go in
> builtins or functools is debatable. A name that is neither in conflict
> or easily confused with the id() builtin is another problem (the
> Haskell identity function is called 'id').
> 
> So what is the use case? A common example is the pattern of "key
> functions" as used with sorting: the default is typically the
> "identity function". Another example is gettext catalogs, which
> effectively are defaultdicts of the identity function.

I frequently find myself wanting an identify function. Here's a (grossly 
simplified) example from one of my library functions:


def len_sum(iterable, transformation=lambda x:x):
     """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

Except that the overhead of calling the identity function is 
significant. So I end up repeating myself:

def len_sum(iterable, transformation=None):
     """Sum iterable, returning length and sum in one pass."""
     count = 0
     total = 0
     if transformation is None:
         for x in iterable:
             count += 1
             total += x
     else:
         ... # you get the picture
     return count, total



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.



-- 
Steven



More information about the Python-ideas mailing list