by tacostakohashi · 9y ago · 0 comments
Add that to the lack of variable declarations (even optional ones, a la my in perl, var in javascript), and it gets hard to work out what scope of any given variable actually is.
Surprising example:
fns = []
for n in [1,2,3,4]:
def fn():
print(n)
fns.append(fn)
for fn in fns:
fn()Anyway, the problem they were talking about is clearer when you are closing over stuff that other than the loop variable:
fns = []
for n in [1,2,3,4]:
x = n*10
def fn():
print(x)
fns.append(fn) def x(y=[]):
y.append(1)
return y
for z in range(4):
print x()
For your case, I recommend using partial functions, which were created for this type of issue. I think it's also cleaner than closures where x depends on an outside context.