By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,767 Members | 1,357 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,767 IT Pros & Developers. It's quick & easy.

eval() and local variables

P: n/a
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.
--
Peter `cuco' Luciak jabber://cu**@jabber.sk
pe***@luciak.org http://www.luciak.org/

Jul 18 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a
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

Jul 18 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.