Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change outer function local variables from an inner function in Python? [duplicate]

Tags:

python

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.


1 Answers

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
like image 132
Ashwini Chaudhary Avatar answered Sep 17 '25 21:09

Ashwini Chaudhary