intricated functions: how to share a variable

Diez B. Roggisch deets at nospam.web.de
Wed Aug 5 06:39:54 EDT 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?

You could use a class :)

Another often used trick is to have a mutable container-object, like this:

def tutu():
   a = [2]

   def toto():
       a[0] = 4
    
   toto()
   
Diez



More information about the Python-list mailing list