intricated functions: how to share a variable

Jason Tackaberry tack at urandom.ca
Wed Aug 5 17:38:13 CEST 2009


On Wed, 2009-08-05 at 12:39 +0200, Diez B. Roggisch wrote:
> Another often used trick is to have a mutable container-object, like this:
> 
> def tutu():
>    a = [2]
> 
>    def toto():
>        a[0] = 4
>     
>    toto()

When you need a writable bound variable inside a closure, I prefer this
idiom:

        def foo():
           def bar():
              print bar.a
              bar.a = 4
              print bar.a
           bar.a = 2
           bar()

Python 3's nonlocal is obviously much more elegant.

Cheers,
Jason.




More information about the Python-list mailing list