3 ms·
I didn't know the answer to this, but it seems like this actually behaves closer to `funcs.append("""print(i)""")` since funcs = list() for i in range(
by mdaniel 3y ago
I didn't know the answer to this, but it seems like this actually behaves closer to `funcs.append("""print(i)""")` since
funcs = list()
for i in range(10):
funcs.append(lambda: print(i))
del i
for f in funcs:
f()
actually NameErrors during f() so I don't think it is actually closing over the i as much as the i was left in scope and the code was seemingly lazy evaluated
- InfamousRece 3y agoRight. In this example lambda does not capture i at all. You would need something like funcs.append(lambda i=i: print(i))
- assbuttbuttass 3y agoNo, it definitely captures i Maybe this example where it returns the closures from a function is convincing? def fs(): funcs = list() for i in range(10): funcs.append(lambda: print(i)) return funcs for f in fs(): f()
- germandiago 3y agoprints all 9s.
- assbuttbuttass 3y agoPython has real closures. In my example, it is closing over i. In your example, you're deleting the closed-over variable. It's a bit weird, and Python is the only language that I know of that lets you do this.