eval() and local variables
Peter Otten
__peter__ at web.de
Tue Apr 20 08:01:52 EDT 2004
Peter Luciak wrote:
> Hi,
> I need to do something like this:
>
> def my():
> a,b=1,2
> func = "lambda x: a*x+b"
> map(eval(func),[1,2,3])
>
> my()
>
> NameError: global name 'a' is not defined
>
> Why do I have to make a,b global for this to work?
You don't:
>>> def my():
... a, b = 1, 2
... return map(eval("lambda x: a*x+b", locals()), [1,2,3])
...
>>> my()
[3, 4, 5]
That makes my's local variables eval's globals.
However, it's not clear to me why you need eval() at all:
>>> def my():
... a, b = 1, 2
... func = lambda x: a*x+b
... return map(func, [1,2,3])
...
>>> my()
[3, 4, 5]
Peter
More information about the Python-list
mailing list