Global surprise

Paul Watson pwatson at redlinepy.com
Wed Nov 24 17:47:28 EST 2004


"Nick" <nospam at nnn.com> wrote in message 
news:co2vp1$ec9$1 at namru.matavnet.hu...
> 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

There is no variable di defined in the test() scope.  Therefore, references 
to di use the di defined in the next outer scope, the module di.

The interactive mode of Python can be very helpful.

$ python
Python 2.1 (#15, May  4 2004, 21:22:34) [MSC 32 bit (Intel)] on win32
Type "copyright", "credits" or "license" for more information.
>>> g = 0
>>> di = {}
>>> def test():
...   global g
...   di[g] = 1
...   g += 1
...
>>> g
0
>>> di
{}
>>> test
<function test at 0083844C>
>>> test()
>>> g
1
>>> di
{0: 1}
>>> test()
>>> g
2
>>> di
{1: 1, 0: 1}
>>> print g, di
2 {1: 1, 0: 1}





More information about the Python-list mailing list