Question

How do I get this code to work?

def f1():
    def f2():
        print g
        g = 1
        print g
    g = 0
    print g
    f2()
    print g

f1()

The expected result is of course 0, 0, 1, 1, printed line by line

Was it helpful?

Solution

If you don't want to use globals:

def f1():
    def f2():
        print g[0]
        g[0] = 1
        print g[0]
    g =[0]
    print g[0]
    f2()
    print g[0]

    f1()

This is to get around the problem of not being able to reassign a variable belonging to the outer scope. When you reassign it you basically create a new variable within the nested function. To get around that, you wrap your value in a list and reassign the list's element instead.

This is a problem in python 2. Python 3 fixes it through the use of the nonlocal statement:

http://technotroph.wordpress.com/2012/10/01/python-closures-and-the-python-2-7-nonlocal-solution/

OTHER TIPS

What about this :

def f1():
    def f2():
        global g
        print g
        g = 1
        print g
    global g
    g = 0
    print g
    f2()
    print g

f1()

Output :

0
0
1
1
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top