4 ms·
The problem I have with Python is that for loops don't have their own scope, only methods. Add that to the lack of variable declarations (even optional ones, a
by tacostakohashi 10y ago
The problem I have with Python is that for loops don't have their own scope, only methods.
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()
- Retra 10y agoThe obvious solution to that is to break your code into smaller functions.
- Shizka 10y agoBut doesn't this just happen because n is a pointer? What would you expect it to print? 1,2,3,4?
- ufo 10y agoIn Lua it prints 1,2,3,4. It has to do with each loop iteration behaving as if it declared a different variable instead of sharing the same variable across the loop. 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)
- bb88 10y agoYeah... so I agree that's confusing. It's akin to: 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.