assigning in nested functions

Paul Rubin http
Sun Oct 9 08:15:10 EDT 2005


jena <jena at vlakosim.com> writes:
> # BEGIN CODE
> def test():
>   def x():
>     print a
>     a=2 # ***
>  a=1
>   x()
>   print a
> 
> test()
> # END CODE
> 
> This code fails (on statement print a in def x), if I omit line marked
> ***, it works (it prints 1\n1\n). It look like when I assign variable
> in nested function, I cannot access variable in container function.
> I need to assign variable in container function, is any way to do this?

No, this is a big bug in Python, there's no way to specify what scope
you want.  The compiler implicitly decides that since you set a to
something inside x(), a must be a local variable.  The principle that
explicit is better than implicit was ignored here.

There's a kludgy workaround which is to box the variable:

  def test():
    def x():
      print a[0]
      a[0] = 2
    a = [1]
    print a[0]

However, the arbiters of Python style would prefer that you use a
class instance instead.



More information about the Python-list mailing list