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

exec with custom dict

P: n/a

Hi,

I am trying to use exec with custom dict.
I am trying to print the value of variable x in 2 places. It is
printing it at the first place and failing at the second place.

class Env(dict):
def __getitem__(self, key):
return self.get(key, key)

code = """
print x
def f(): return x
"""

env = Env()
exec(code, env)
print env['f']()

Here is the output I'm getting.

x
Traceback (most recent call last):
File "a.py", line 14, in <module>
print env['f']()
File "<string>", line 3, in f
NameError: global name 'x' is not defined

Can somebody explain me what is happening?

-Anand
Jun 27 '08 #1
Share this question for a faster answer!
Share on Google+

This discussion thread is closed

Replies have been disabled for this discussion.