assigning in nested functions

Antoon Pardon apardon at forel.vub.ac.be
Mon Oct 10 04:43:06 EDT 2005


Op 2005-10-09, jena schreef <jena at vlakosim.com>:
> Hi
> I have code
>
> # 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?

I think the best solution with current python in this situation is to
wrap the nested scope variable in a one element list and use slice
notation to change the variable in a more nested function. Something like the
following:

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

Another solution, IMO more workable if you have more of these variables
is to put them all in a "Scope" object aka Rec, Bunch and probably some
other names and various implementatiosn. (I don't remember from who this
one is. Something like the following:

class Scope(object):
     def __init__(__, **kwargs):
         for key,value in kwargs.items():
             setattr(__, key, value)
     __getitem__ = getattr
     __setitem__ = setattr

def test():

  def x():
    print scope.a
    scope.a = 2

  scope = Scope(a=1)
  x()
  print scope.a

test()

-- 
Antoon Pardon



More information about the Python-list mailing list