eval() and local variables

P

Peter Luciak

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?

Thanks,
P.
 
P

Peter Otten

Peter said:
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:
.... a, b = 1, 2
.... return map(eval("lambda x: a*x+b", locals()), [1,2,3])
....[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:
.... a, b = 1, 2
.... func = lambda x: a*x+b
.... return map(func, [1,2,3])
....[3, 4, 5]

Peter
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,763
Messages
2,569,562
Members
45,038
Latest member
OrderProperKetocapsules

Latest Threads

Top