Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing a Variable from Within a Doubly Nested Function in Python

The following code:

x = 0
print "Initialization: ", x
def f1():
    x = 1
    print "In f1 before f2:", x
    def f2():
        global x
        x = 2
        print "In f2:          ", x
    f2()
    print "In f1 after f2: ", x
f1()
print "Final:          ", x

prints:

Initialization:  0
In f1 before f2: 1
In f2:           2
In f1 after f2:  1
Final:           2

Is there a way for f2 to access f1's variables?

like image 991
kzh Avatar asked Feb 18 '10 17:02

kzh


2 Answers

You can access the variables, the problem is the assignment. In Python 2 there is no way to rebind x to a new value. See PEP 227 (nested scopes) for more on this.

In Python 3 you can use the new nonlocal keyword instead of global. See PEP 3104.

like image 199
nikow Avatar answered Oct 08 '22 16:10

nikow


In Python 3, you can define x as nonlocal in f2.

In Python 2, you can't assign directly to f1's x in f2. However, you can read its value and access its members. So this could be a workaround:

def f1():
    x = [1]
    def f2():
        x[0] = 2
    f2()
    print x[0]
f1()
like image 37
interjay Avatar answered Oct 08 '22 16:10

interjay