(SOLVED) class derived from dict in eval

Florian Schulze florian.proff.schulze at gmx.net
Mon Feb 24 23:47:44 CET 2003

Thanks for this comprehensive answer. Your evalWithSpecialDict is really an 
interesting approach. I learned many new things again.
Though I was able to solve this differently without much problems. It just 
didn't occur to me till an hour later. I just add my dict as a name in the 
eval dict, that way I can just access my keys through dictname['key']. Then 
I added a __getattr__ function and can access the keys through dictname.key 
which isn't a problem besides a little bit more typing.

I'm really impressed by Python. I use it for my first big project now and 
the code I wrote is much more general than anything I wrote before. The 
dynamic nature of it is really awesome.

Thanks and regards,

On Mon, 24 Feb 2003 22:12:35 GMT, Alex Martelli <aleax at aleax.it> wrote:

> <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