Need an identity operator because lambda is too slow

Deron Meranda deron.meranda at gmail.com
Sun Feb 18 00:59:18 EST 2007


This is an optimization problem, one that occurs deep inside a loop
that gets executed thousands of times.  I'm looking for something in
Python which would act like an identity operator, or I-combinator: a
do-nothing function.  The best I know of is:  (lambda x: x), but it is
not ideal.

Consider a much-simplified example of such an iteration where
sometimes you need to transform an item by some function, but most of
the time you don't:

    if some_rare_condition:
        func = some_transform_function
    else:
        func = lambda x: x
    for item in some_sequence:
        item2 = func(item)
        ..... # more stuff

Now the "lambda x:x" acts suitably like an identity operator.  But it
is very slow, when compared to using more complex-looking code:

    do_transform = some_rare_condition
    for item in some_sequence:
        if do_transform:
            item2 = transform_function(item)
        else:
            item2 = item
        ..... # more stuff

What python needs is something like a built-in "operator.identity"
function, which acts like "lambda x:x", but which the byte compiler
could recognize and completely optimize away so there is no function
call overhead.

Does this exist someplace in the corners of the language, or are there
any ideas about how best to do something like this without having to
push a bunch of ugly if-then-else constructs inside all the loops
rather than a more elegant function object?  (The need for this is
more obvious in my real-world code versus the simplified examples
above).

Thanks
--
Deron Meranda




More information about the Python-list mailing list