Question re local bindings in nested scopes

Chris Goringe goringe at avaya.com
Thu Jun 7 00:22:16 EDT 2001


This isn't really new in 2.1; below b() refers to the global 'a', but
c(), because it contains an assignment to 'a' binds to a local
variable and dies. d() fixes this by declaring global.

So, is there an analogue of global for nested scopes?

>>> a = 1
>>> def b():
...     print a
...
>>> def c():
...     print a
...     a = a + 1
...
>>> def d():
...     global a
...     print a
...     a = a + 1
...
>>> b()
1
>>> c()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 2, in c
UnboundLocalError: Local variable 'a' referenced before assignment
>>> d()
1



More information about the Python-list mailing list