Replacing globals in exec by custom class
DevPlayer
devplayer at gmail.com
Wed Dec 8 12:32:58 EST 2010
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=???
With the above code you can do g['yyy'] and you would get None
For your example code to work, line 14 in your example needs to be:
elif key in self.__dict__: # (change else to elif)
for your dict (or globalscl) to act like other dicts() add
an else:
raise KeyError( 'Key not found: %s' % (key,))
__dict__ of a dict I believe is not the namespace of dict. I thought
dict[key] and dict.__dict__[key] where not the same place
__dict__ of dict in Python 2.5 and prior was rumored to be buggy and
unused. Don't know about Python 2.6 +
I thought __getitem__() did not look in __dict__ of dict().
If I copy your code into a module globalcl.py
and comment out "print xx" in the string,
and in PyCrust I "import globalcl"
I too get the results and errors you claim.
If I then do:
>>>globalcl.g.keys()
I get: ['__builtins__']
>>>globalcl.g['__builtins__']
I get: nothing (or None)
>>>globalcl.g['__builtin__']
I get: nothing (or None)
# -------------------------
# interesting part
>>>globalcl.g['xx']
I get: 'xx'
>>>if 'xx' in globalcl.g:
... print True
...else:
... print False
I get: False
# -------------------------
>>>globalcl.g.__builtins__
AttributeError: 'Global' object has no attribute __builtins__'
>>>globalcl.g.__builtins__
AttributeError: 'Global' object has no attribute '__builtin__'
>>>globalcl.g.__dict__
{'q': <function q at 0x01C738B0>}
More information about the Python-list
mailing list