assigning in nested functions

Antoon Pardon apardon at
Mon Oct 10 10:43:06 CEST 2005

Op 2005-10-09, jena schreef <jena at>:
> Hi
> I have code
> def test():
>   def x():
>     print a
>     a=2 # ***
>   a=1
>   x()
>   print a
> test()
> 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

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

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)
  print scope.a


Antoon Pardon

More information about the Python-list mailing list