Here is a rather self-explanatory code snippet in python:
globl = 1
def foo():
def bar():
return free+capture
capture = globl #not seen, when bar is defined
return bar
free = 2
a = foo()
globl = 4
b = foo()
print(a()) #3
print(b()) #6
print(a.__closure__[0].cell_contents) # 1
print(b.__closure__[0].cell_contents) # 4
When 'bar' is defined, both 'free' and 'captured' variables are free. they do not exist in parent envirionment, neither in root. When 'bar' returned from 'foo', 'capture' will be captured. From a stack!
So I assume python closes over environment on return of a function. Why is that the case? Why not on definition time of 'bar'?
Same snippet also works if we replace bar with lambda:
bar = lambda : free+capture
