class derived from dict in eval

Alex Martelli aleax at aleax.it
Mon Feb 24 17:12:35 EST 2003


<posted & mailed>

Florian Schulze wrote:

> I want to use my own class which is derived from dict as locals in the
> eval function, but I can't get it to work. My class calculates values
> dependant on the key. Is this possible at all, or am I at a dead end here?
> If it's possible, then please tell me which methods I have to implement.

You have to prepare a real dictionary for the names used
in the expression you're interested in, because, as others
said responding to you, the LOAD_NAME operation bypasses
polymorphic behavior and goes for actual dict item access.

Fortunately, it's not too hard:

def evalWithSpecialDict(expression, specialDict):
    compiled = compile(expression, '<string>', 'eval')
    realDict = {}
    for varname in compiled.co_names:
        realDict[varname] = specialDict[varname]
    return eval(compiled, realDict)

class SpecialExample:
    def __getitem__(self, key): return key

print evalWithSpecialDict('a+b', SpecialExample())


will print


ab


Basically, evalWithSpecialDict(expr, special) gives just
the same effect as eval(expr, special) would if special
was in fact an ordinary dict rather than an arbitrary
mapping.  Interestingly enough, this question was basically
the first interesting one I asked when I started posting
on comp.lang.python, and as I recall nobody would give a
straight answer... I had to puzzle it out by myself from
hints hidden in the middle of harangues about why I should
NOT be doing this...;-).


Alex





More information about the Python-list mailing list