Classes derived from dict and eval
Robert Kern
rkern at ucsd.edu
Tue Sep 20 16:59:50 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.
In [1]: eval?
Type: builtin_function_or_method
Base Class: <type 'builtin_function_or_method'>
String Form: <built-in function eval>
Namespace: Python builtin
Docstring:
eval(source[, globals[, locals]]) -> value
Evaluate the source in the context of globals and locals.
The source may be a string representing a Python expression
or a code object as returned by compile().
The globals must be a dictionary and locals can be any mappping,
defaulting to the current globals and locals.
If only globals is given, locals defaults to it.
globals needs to be a real dictionary. The implementation uses the C
API, it doesn't use the overridden __getitem__. The locals argument,
apparently can be some other kind of mapping.
--
Robert Kern
rkern at ucsd.edu
"In the fields of hell where the grass grows high
Are the graves of dreams allowed to die."
-- Richard Harter
More information about the Python-list
mailing list