assigning in nested functions

Diez B. Roggisch deets at nospam.web.de
Sun Oct 9 08:09:38 EDT 2005


jena wrote:
> 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?

No. You can access them, but not rebind them. That's a crucial 
difference. So, if a contains a mutable, you can alter that:

def test():
    a = {"foo": "bar"}
    def x():
       a["foo"] = "pillepalle"
    x()
    print a

Or you return that value:

def test()
    a = 10
    def x():
       return a * 10
    a = x()


Diez



More information about the Python-list mailing list