intricated functions: how to share a variable

alex23 wuwei23 at gmail.com
Wed Aug 5 15:35:19 CEST 2009


TP <Tribulati... at Paralleles.invalid> wrote:
> Then, as advised Diez, perhaps the best solution is to have "true" global
> variables by using a class and defining the variable a as a member self.a
> of the class. By doing like this, a will be known everywhere.

Or, as Bearophile suggested, you could use the standard way of passing
arguments into a function:

>>> def tutu():
...   a = 2
...   def toto(a=a):
...     print 'toto', a
...     a = 4
...     print 'toto', a
...   print 'tutu', a
...   toto()
...   print 'tutu', a
...
>>> tutu()
tutu 2
toto 2
toto 4
tutu 2

You could also just do 'toto(a)', but as you're trying to create a
closure here, binding the external scope 'a' to toto via the default
argument will (probably) do what you need.



More information about the Python-list mailing list