Using eval to delay evaluation is bad in both Lisp and Python.
in Python, and in Lisp you can defer evaluation using closure:
def print_it(x): def f(): print g(x) return f f = print_it(42) def g(x): return x * x f()
Note that what is locked is not the value of the variable, but the variable itself, and this is sometimes surprising:
fa = [] for x in range(10): def g(): print x fa.append(g) for f in fa: f() # all of them will print 9 x = 42 fa[0]() # the output will be 42
to solve this problem (which may also be present in Common Lisp), you can see things like:
for x in range(10): def g(x = x): print x fa.append(g)
or (in CL) things like
(let ((aa)) (lambda () (print a)))
Python also has a special lambda form for anonymous functions, but they are limited to one single expression and cannot contain any instruction. A locally def infected function is instead a regular function without any restrictions.
for x in range(10):
Finally, Python 2.x has a syntax limitation, and private variables are read-only, because if a function has an assignment (or extended assignment), there are only two possibilities:
- The variable is global (and was previously declared using
global x ) - This variable is local
and, in particular, he ruled out that the assigned variable may be a local area of ββthe enclosing function.
Python 3.x eliminated this limitation by providing a new possible nonlocal x declaration, and now the well-known adder example can be implemented as
def adder(x): def f(y): nonlocal x x += y return x return f