S
SeanMon
I was playing around with Python functions returning functions and the
scope rules for variables, and encountered this weird behavior that I
can't figure out.
Why does f1() leave x unbound, but f2() does not?
def f1():
x = 0
def g():
x += 1
return x
return g1
def f2():
x = []
def g():
x.append(0)
return x
return g
a = f1()
b = f2()
a() #UnboundLocalError: local variable 'x' referenced before
assignment
b() #No error, [0] returned
b() #No error, [0, 0] returned
scope rules for variables, and encountered this weird behavior that I
can't figure out.
Why does f1() leave x unbound, but f2() does not?
def f1():
x = 0
def g():
x += 1
return x
return g1
def f2():
x = []
def g():
x.append(0)
return x
return g
a = f1()
b = f2()
a() #UnboundLocalError: local variable 'x' referenced before
assignment
b() #No error, [0] returned
b() #No error, [0, 0] returned