Function closure inconsistency
Terry Reedy
tjreedy at udel.edu
Fri Jul 23 18:21:06 EDT 2010
On 7/23/2010 2:30 PM, SeanMon wrote:
> 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():
In 3.x, add
nonlocal x
> x += 1
> return x
> return g1
You meant g
def f1():
x = 0
def g():
nonlocal x
x += 1
return x
return g
f=f1()
print(f())
print(f())
print(f())
print(f())
1
2
3
4
--
Terry Jan Reedy
More information about the Python-list
mailing list