Classes derived from dict and eval

Jeremy Sanders jeremy+python at jeremysanders.net
Tue Sep 20 16:40:22 EDT 2005


Hi -

I'm trying to subclass a dict which is used as the globals environment of
an eval expression. For instance:

class Foo(dict):
    def __init__(self):
        self.update(globals())
        self['val'] = 42
                 
    def __getitem__(self, item):
        # this doesn't get called from the eval statement
        print "*", item
        return dict.__getitem__(self, item)

a = Foo()

print a['val']
print eval('val*2+6', a)

The first print statements also prints "* val", but __getitem__ is never
called by the evaluation in the eval statement.

Is this a bug? Does anyone have an idea for a workaround? I'm using
Python 2.3.3.

Thanks

Jeremy



More information about the Python-list mailing list