Proposed new syntax

Steve D'Aprano steve+python at pearwood.info
Mon Aug 14 10:30:22 EDT 2017


On Mon, 14 Aug 2017 09:03 pm, Rustom Mody wrote:

> For myself, if the python docs contradict the last 100 years or prior art/math
> history, the latter takes precedence

When theory disagrees with the facts, you ignore the facts?


> All I want to say is the gratuitous incidental resemblance of for-loops
> with comprehensions confuses not just beginners but even the python
> implementers:

You have misinterpreted what you are seeing.

The Python 2 variable leak has nothing to do with whether comprehensions are
for-loops or not. It is a scoping issue: list comps previously shared the same
scope as their surrounding, but no longer.


> However this leak still remains:
> 
>>>> fl = [(lambda x : x + i) for i in range(5)]
>>>> [f(2) for f in fl]
> [6, 6, 6, 6, 6]

This has nothing to do with list comprehensions or for-loops. We can unroll the
loop and demonstrate the same behaviour:

fl = []
i = 0
fl.append(lambda x: x + i)
i = 1
fl.append(lambda x: x + i)
i = 2
fl.append(lambda x: x + i)
i = 3
fl.append(lambda x: x + i)
i = 4
fl.append(lambda x: x + i)
[f(2) for f in fl]


It's not a "leak", it's not "bugginess", it has nothing to do with for loops or
comprehensions. It's just the standard, normal name resolution.

The example in the list comprehension is *slightly* different: the functions
there are closures over i, whereas in the unrolled version the functions simply
do a global name lookup.

But the behaviour is the same because both use late binding semantics: the value
of i isn't copied into the function at the time of function creation, it is
retrieved only when needed when the function is called.

Haskell (it seems) uses early binding instead.

Which is "correct"? Both are. Both early and late binding are reasonable design
choices, with good reasons for choosing either. Python uses early binding for
function default values, and late binding for closures. You might argue for the
other choice, but the decision is made and won't change. And neither has
anything to do with for-loops.




-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.




More information about the Python-list mailing list