Re: Replacing globals in exec by custom class

2010-12-09 Thread Jonathan S
Thanks for your response! (And sorry about the syntax error, I forgot to test my code after cleaning up some debug statements before posting, the else should have been elif indeed.) It's very interesing, how Python works internally. According to a thread on the Python mailing list in 2002, it seem

Re: Replacing globals in exec by custom class

2010-12-08 Thread Terry Reedy
On 12/8/2010 8:01 AM, Jonathan S wrote: class Global(dict): def __init__(self): pass def __getitem__(self, key): import __builtin__ if key == 'xx': return 'xx' if hasattr(__builtin__, key): return getattr(__builtin__, key)

Re: Replacing globals in exec by custom class

2010-12-08 Thread DevPlayer
Shouldn't return 'xx' be return self['xx' I don't know why precisely you're using a class as a global namespace, not that I personally find fault with it. But here are some other things you can do. Idea one: == class NS(object): """plac

Re: Replacing globals in exec by custom class

2010-12-08 Thread DevPlayer
Shouldn't return 'xx' be return self['xx'] -- http://mail.python.org/mailman/listinfo/python-list

Re: Replacing globals in exec by custom class

2010-12-08 Thread DevPlayer
Couple of things: I don't think this is what you want: def __getitem__(self, key): import __builtin__ if key == 'xx': return 'xx' I won't return a KeyError for any string you give g[] It will return 'xx' only if you supply key='xx' and ignore every other key=??? Wit

Replacing globals in exec by custom class

2010-12-08 Thread Jonathan S
Hi all, I wonder if anyone can explain some weird behaviour in Python. What I'm trying to do is to execute a string of python code through the 'exec' statement. I pass an instance of my Global class, which acts like a dict. By overriding the __getitem__ method, the Global should pretend that a glo