Help | Site Map
Connecting Tech Pros Worldwide
 
 
LinkBack Thread Tools
  #1  
Old June 27th, 2008, 05:29 PM
Anand
Guest
 
Posts: n/a
Default exec with custom dict


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
 

Bookmarks

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are Off
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On

What is Bytes?

We are a network of experts and professionals in IT and software development that help one another with answers to tough questions and share insights. Get the best answers to your questions from over network members.
Post your question now . . .
It's fast and it's free

Popular Articles