Classes derived from dict and eval
Kent Johnson
kent37 at tds.net
Wed Sep 21 10:09:39 EDT 2005
Jeremy Sanders wrote:
> 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.
Try Python 2.4.1:
Python 2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC v.1310 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> 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']
* val
42
>>> print eval('val*2+6', a)
* val
90
Kent
More information about the Python-list
mailing list