[Tutor] "farkadoodle" or: unique global names, was Re: Data persistence problem

Albert-Jan Roskam fomcl at yahoo.com
Sat Jun 22 21:59:12 CEST 2013


<snip>
 
> One catch with Python nested scopes is that binding a name defaults to
> the local scope. You can get around this by using a mutable container,
> just as was done with globals before the "global" keyword was added in
> version 0.9.4 (1991). The better solution is a new keyword, but adding
> keywords is radical surgery. The "nonlocal" keyword, as Peter used,
> had to wait for 3.x.

I was playing around with this a bit and arrived at the following surprising (for me at least) result. I thought the global/local/nonlocal keywords could be used to get values from another scope. Though this could also happen implicitly, e.g. if only x = "I am global" is defined and x is used (and not redefined) inside a function, then python still knows this variable inside that function. 

Is there any way to make this work? (it may not be desirable, though)

#Python 3.2.3 (default, Apr 10 2013, 05:29:11) [GCC 4.6.3] on linux2
>>> x = "I am global"
>>> def outer():
...     x = "I am nonlocal"
...     def inner():
...         x = "I am local"
...         print(x)  # expecting to print 'I am local' 
...         nonlocal x
...         print(x)  # expecting to print 'I am nonlocal' 
...         global x
...         print(x)  # expecting to print 'I am global' 
...     inner()
... 
<stdin>:6: SyntaxWarning: name 'x' is assigned to before nonlocal declaration
<stdin>:8: SyntaxWarning: name 'x' is assigned to before global declaration
SyntaxError: name 'x' is nonlocal and global


More information about the Tutor mailing list