exec with custom dict

A

Anand

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
 

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

Similar Threads


Members online

Forum statistics

Threads
473,968
Messages
2,570,154
Members
46,702
Latest member
LukasConde

Latest Threads

Top