Message24410
eval() does not bind variables in lambda expressions
correctly:
>>>def f(g): return eval('lambda x: g(x)')
>>>f(lambda y: y * 2)(17)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<string>", line 1, in <lambda>
NameError: global name 'g' is not defined
The docs say this about eval():
# If both dictionaries are omitted, the expression is
# executed in the environment where eval is called.
and using plain local variables work as expected:
>>>def h(d): return eval('d(10)')
>>>h(lambda y: y * 2)
20
Also, if locals() is presented as the global dict to
eval(), it works:
>>>def f(g): return eval('lambda x: g(x)', locals(),
locals())
>>>f(lambda y: y * 2)(17)
34
but this does not allow the expression to reference
global variables of course.
|
|
Date |
User |
Action |
Args |
2007-08-23 14:29:50 | admin | link | issue1153622 messages |
2007-08-23 14:29:50 | admin | create | |
|