import reassignment different at module and function scope

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Sat Jan 31 09:01:05 CET 2009


En Sat, 31 Jan 2009 05:31:47 -0200, Brendan Miller <catphive at catphive.net>  
escribió:

> If I:
>
> import sys
>
> sys = sys.version
>
> This executes find but:
>
> import sys
>
> def f():
>     sys = sys.version
>
> This gives an error indicating that the sys on the right hand side of =
> is undefined. What gives?

Python doesn't have local variable declarations. Inside a function, *any*  
name that is assigned to (e.g. any name appearing on the left side of an  
assignment operation, like "a" in a=8) becomes a local variable. In your  
example, "sys" is a local variable, and it "shadows" (or "hides") the  
global one of the same name.
When the interpreter tries to execute
     sys = sys.version
it complains that it can't evaluate sys.version because the local name  
"sys" has not been assigned yet.

The same thing at the global level is OK, because sys.version refers to  
the global "sys" name.

(This should appear in the FAQ...)

-- 
Gabriel Genellina




More information about the Python-list mailing list