if not global -- then what?

Jonathan Gardner jgardner at jonathangardner.net
Sun Feb 21 00:42:14 EST 2010


On Sat, Feb 20, 2010 at 5:53 PM, Steven D'Aprano
<steve at remove-this-cybersource.com.au> wrote:
> 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.
>

Oops. :-(

-- 
Jonathan Gardner
jgardner at jonathangardner.net



More information about the Python-list mailing list