Python is Considered Harmful

Jeremy Fincher tweedgeezer at hotmail.com
Mon Oct 27 09:25:39 EST 2003


mike420 at ziplip.com wrote in message news:<D5ODMGKEL3JQLZOFIJAGKINUHSIEBVOLPZKLOPNS at ziplip.com>...
> Ladies and Gentlemen,
> 
> I present to you the final and ultimate proof of Python's
> brain-damage:
> 
> As you may remember,
> 
> flist = []
> 
> for i in range(3)
>     f = lambda x: x + i
>     flist.append(f)
> 
> [f(1) for f in flist]
> 
> produces [3, 3, 3] in Python.
> 
> In Haskell, we would express this as follows:
> 
> map (\f -> f 1)  [\x -> x + i | i <- [0..2]]

First, let's remove the list comprehension syntactical sugar.  This is
actually:

map (\f -> f 1) (map (\i -> (\x -> x + i)) [0..2])

So, as you can see clearly without the sugar, you're basically
creating closures, since a new lexical scope is introduced at function
creation.

> This, of course, evaluates to the expected [1, 2, 3]

Expected by functional programmers who expect new lexical scopes to be
created at every block, sure.  But Python isn't a functional
programming language, and doesn't create a new lexical scope in every
block.
 
> As you might have heard, the ever so generous GvR allowed us write
> the same in Python (literal translation, really):
> 
> map(lambda f: f(1), [lambda x: x + 1 for i in range(3)

Others have pointed out your typo here; I'll assume you meant "lambda
x: x + i" instead of 1.

Again, let's remove the syntactical sugar here:

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

The observed result, [3, 3, 3] is perfectly in keeping with the fact
that Python does not create a new lexical scope in for suites (or if
suites, or any other non-class, non-function suite).

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

The Python result is only surprising to those who try to impose other
languages' semantics on Python.

> All this Python bashing is starting to feel like mocking
> a retarded child...

You, sir, are a poor representative of the Haskell community.

Jeremy




More information about the Python-list mailing list