intricated functions: how to share a variable

Peter Otten __peter__ at web.de
Wed Aug 5 12:46:28 CEST 2009


TP wrote:

> Hi everybody,
> 
> See the following example:
> 
> #########
> def tutu():
> 
>     def toto():
> 
>         print a
>         a = 4
>         print a
> 
>     a=2
>     toto()
> 
> tutu()
> ##########
> 
> I obtain the following error:
> "UnboundLocalError: local variable 'a' referenced before assignment"
> 
> This is because Python looks in the local context before looking in the
> global context.
> 
> The use of "global a" in toto() does not help because global allows to
> force Python to look for the variable at the module level.
> 
> So, how to share a variable between intricated functions?

This limitation is removed in Python 3 with the 'nonlocal' statement:

>>> def outer():
...     def inner():
...             nonlocal a
...             print(a)
...             a = 4
...             print(a)
...     a = 2
...     inner()
...     print(a)
...
>>> outer()
2
4
4

Peter




More information about the Python-list mailing list