Global surprise

bruno modulix onurb at xiludom.gro
Wed Nov 24 20:16:07 EST 2004


Nick a écrit :
> Hello,
> 
> It must be simple but it seems I misunderstand scopes in Python... :(
> 
> Could someone out there please explain to me why this is printed?
> 2 {0: 1, 1: 1}
> instead of
> 2 {}
> 
> Thanks.
>  N.
> 
> ---- test.py ----
> 
> g = 0
> di = {}
> 
> def test():
>   global g
>   di[g] = 1
>   g += 1
> 
> test()
> test()
> 
> print g, di
> 
> 

Because di is a global variable, modified by the test() function (which 
is a Bad Thing(tm) BTW).

Try this :
g = 0
di = {}

def test():
   global g
   di = {g : 1}
   g += 1

Here you create a local di variable, and bind a new dict to it, so it 
doesnt look for another di variable in the enclosing (here the global) 
scope.

Keep in mind that modifying the state of an object (your code) is not 
the same thing as binding an object to a variable (my code).

HTH
Bruno



More information about the Python-list mailing list