if not global -- then what?

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sat Feb 20 20:53:46 EST 2010


On Sat, 20 Feb 2010 17:34:15 -0800, Jonathan Gardner wrote:

> In terms of "global", you should only really use "global" when you are
> need to assign to a lexically scoped variable that is shared among other
> functions. For instance:
> 
> def foo():
>     i = 0
>     def inc(): global i; i+=1
>     def dec(): global i; i-=1
>     def get(): return i
>     return (inc, dec, get)

That doesn't do what you think it does:


>>> def foo():
...     i = 0
...     def inc(): global i; i+=1
...     def dec(): global i; i-=1
...     def get(): return i
...     return (inc, dec, get)
...
>>> inc = foo()[0]
>>> inc()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in inc
NameError: global name 'i' is not defined


The problem is that i is not global. Inside the inc and dec functions, 
you need to declare i nonlocal, not global, and that only works in Python 
3 or better.



-- 
Steven



More information about the Python-list mailing list