Python critique

Jean-Michel Pichavant jeanmichel at sequans.com
Fri Dec 10 09:02:50 EST 2010


Octavian Rasnita wrote:
> It is true that Python doesn't use scope limitations for variables?
>
> Octavian
>   
Python does have scope.  The problem is not the lack of scope, to 
problem is the shadow declaration of some python construct in the 
current scope.

print x # raise NameError
[x for x in range(10)] # shadow declaration of x
print x # will print 9

it can become a problem if you write such code:

index = 1
myNewList = [index*2 for index in [1,2,3,4,5]]
print myNewList(index) # here most new commer would want to use index=1.

To compare to some C construct, python declares the variable in the 
current scope while the C construct will create a new scope for the 
following block.

IMO, i don't see this one as an issue, because even when coding in C, 
you do NOT use the same name for 2 different things. Python shadow 
declarations would be a problem for someone used to take "advantage" of 
the C construct.
The author states that this is bug prone, I did write a lot of python 
lines, never happened to me.

JM

PS : pylint reports such shadow declaration, W0631:  4: Using possibly 
undefined loop variable 'x'





More information about the Python-list mailing list