isPrime works but UnBoundLocalError when mapping on list

Fredrik Lundh fredrik at pythonware.com
Wed Jul 16 15:01:27 CEST 2008


Andreas Tawn wrote:

> I don't have experience of too many other languages, but in C++ (and I
> guess C)...

That's invalid C (you cannot declare variables in the "for" statement 
itself, at least not in C89).  And back in the old days, some C++ 
compilers did in fact leak declarations from "for" loops, and others 
didn't...

> Is the Python behaviour just a happy side effect of the target list
> assignment or specific design decision?

I'd say it all follows from the fact that Python doesn't have variable 
declarations; if you want to stick to the principle that variables can 
introduced simply by assigning to them, you cannot introduce new blocks 
nilly-willy.  So none of the basic structural elements do that; 
variables introduced inside an "if" statement or a "for-in" statement 
are no different from variables introduced outside them.  And intro-
ducing a new block only for the loop variables would be confusing and 
rather impractical, given how fundamental looping over sequences and 
iterables are in Python.

(the discussions about loop variables in list comprehensions and 
generator expressions are a bit different; they're expressions, not 
statements, and shouldn't really do assignments as a side effect, any 
more than function calls should leak parameter names into the calling 
scope...)

</F>




More information about the Python-list mailing list