4 ms·
In Python (yes, the heresy of using Python in a lisp article), you can define a closure this way: def foo(x): y = x def bar():
by falcolas 16y ago
In Python (yes, the heresy of using Python in a lisp article), you can define a closure this way:
def foo(x):
y = x
def bar():
print y
return bar
>>> z = foo(1)
>>> z()
1
The value of y is preserved, even through it is not assigned in the function bar (outside of its lexical scope). You can pass bar around all you want, and it will maintain its value of y. Even if you create another instance of bar, they will retain their individual values of y.
- Tycho 16y agoso if I did this (following from your example): n = 35 a = foo(n) a() n = 42 a() I would get 35 printed both times, despite n having changed. is that the idea?
- falcolas 16y agoLanguage specifics mean that this might not always be the case. i.e. >>> s = "%03d" >>> f = lambda x: s % x # Identical behavior for a regular function closure >>> map(f, range(10)) ['000', '001', '002', '003', '004', '005', '006', '007', '008', '009'] >>> s = "%04d" >>> map(f, range(10)) ['0000', '0001', '0002', '0003', '0004', '0005', '0006', '0007', '0008', '0009'] I would try and think of it as more of a function parameter that you pre-fill, and never have to provide again for that instance of the function.