1

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

e271p314
  • 3,841
  • 7
  • 36
  • 61

2 Answers2

2

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/

Ioan Alexandru Cucu
  • 11,981
  • 6
  • 37
  • 39
0

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
Vincent
  • 12,919
  • 1
  • 42
  • 64
  • This is basically how it works now, but since I'm running in multithreaded application I prefer to avoid global variables. Why can't python look up the stack for variables? – e271p314 Nov 13 '13 at 13:43