intricated functions: how to share a variable

Bearophile bearophileHUGS at lycos.com
Wed Aug 5 06:47:19 EDT 2009


TP:
> 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?

Generally your purpose as a programmer is to write the least intricate
code. Because the less tricky it is, the more readable it becomes and
also the bug count decreases.

So probably a better solution is to just use the normal function
semantics: you pass them an argument and you take an argument as
return value. Such return value will be the new version of the value
you talk about.

Python3+ has the "nonlocal" statement that may do what you ask for.
But as many other things in Python it must be used with judgment, to
avoid writing intricate code.

Bye,
bearophile



More information about the Python-list mailing list