Possible Duplicate:
Modify the function variables frominner function in python
Say I have this python code
def f():
    x=2
    def y():
        x+=3
    y()
this raises:
UnboundLocalError: local variable 'x' referenced before assignment
So, how do I "modify" local variable 'x' from the inner function? Defining x as a global in the inner function also raised an error.
You can use nonlocal statement in Python 3:
>>> def f():
...     x = 2
...     def y():
...         nonlocal x
...         x += 3
...         print(x)
...     y()
...     print(x)
...
>>> f()
5
5
In Python 2 you need to declare the variable as an attribute of the outer function to achieve the same.
>>> def f():
...     f.x = 2
...     def y():
...         f.x += 3
...         print(f.x)
...     y()
...     print(f.x)
...
>>> f()
5
5
or using we can also use a dictionary or a list:
>>> def f():
...     dct = {'x': 2}
...     def y():
...         dct['x'] += 3
...         print(dct['x'])
...     y()
...     print(dct['x'])
...
>>> f()
5
5
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With