Comparison of functions

Steven D'Aprano steve at REMOVETHIScyber.com.au
Sat Jul 30 07:45:38 EDT 2005


Playing around with comparisons of functions (don't ask), I discovered an
interesting bit of unintuitive behaviour:

>>> (lambda y: y) < (lambda y: y)
False

Do the comparison again and things become even more bizarre:

>>> (lambda y: y) < (lambda y: y)
True
>>> (lambda y: y) < (lambda y: y)
False

This behaviour should be easy for experienced Pythonisters to answer, but
will probably confuse beginners greatly.

For the benefit of beginners, imagine we expand the first line into two,
and commit what some people call an abuse of lambdas: we bind them to
names.

>>> a = lambda y: y
>>> b = lambda y: y
>>> a
<function <lambda> at 0xf70598ec>
>>> b
<function <lambda> at 0xf7059844>

a and b are now bound to two objects, each of which is an anonymous
function that just happens to do the same thing. But each time you create
a lambda function, you get a different object at some unpredictable
location in memory.

This is where my level of Python knowledge fails me. I don't understand
how Python is comparing the two objects since neither a nor b have any
rich comparison methods or even the old-style __cmp__ method.

>>> a < b
False

So I'm puzzled about how Python compares the two.

If we compare a and b again, we will always get the same answer. But if we
create a new pair of anonymous functions with lambda, and compare them, it
is the luck of the draw each time whether the first compares bigger or
smaller than the second.


-- 
Steven.




More information about the Python-list mailing list