Python is Considered Harmful

Isaac To kkto at csis.hku.hk
Mon Oct 27 01:50:18 EST 2003


>>>>> "mike420" == mike420  <mike420 at ziplip.com> writes:

    mike420> As you might have heard, the ever so generous GvR allowed us
    mike420> write the same in Python (literal translation, really):

    mike420> map(lambda f: f(1), [lambda x: x + 1 for i in range(3)])

    mike420> What do you think this evaluates to: also [1, 2, 3] or [3, 3,
    mike420> 3] as before?

    mike420> Guess again, it's [2, 2, 2] !

Did you really mean

  map(lambda f: f(1), [lambda x: x+i for i in range(3)])

?  If so, it does return [3, 3, 3].  The only problem here is that Python
variables are name lookups over dictionaries, and as such the value of "i"
is not coined into the lambda.  Rather it is "external", binded dynamically.
I believe the behaviour can be fixed rather easily by some directives, say
making it

  map(lambda f: f(1), [lambda x: x+(*i) for i in range(3)])

where the * construct would get the reference of i at function definition
time rather than at function invocation time (anyone can point me to an
PEP?).  On the other hand, I basically never use lambda this way.

    mike420> Pythonista, you are all very welcome to learn Haskell.  You
    mike420> will find the syntax very familiar. Haskell is short too
    mike420> (compare one line above that gives the correct result to
    mike420> several Python lines that surprise you)

Yes, tried.  Failed, unluckily.  It is clear that I'm not the kind of people
who will map every programming problem into a mathematical problem and solve
it that way.  So I hate maps and reduces.  I hate that I cannot assign a new
value to an existing value to change its binding.  I hate having to remember
the unintuitive meanings of all the symbols.  I hate having to guess when
variables will get its bindings and when functions will be invoked during
lazy evaluation.  There is no way that anyone can turn me to Haskell.
Basically every strong point Haskellers talk about turn me off.  This is
very unlucky.

Regards,
Isaac.




More information about the Python-list mailing list