class derived from dict in eval

Andrew Dalke adalke at mindspring.com
Tue Feb 25 10:00:49 EST 2003


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

Wow!  Totally different and much cleaner than my code, which looks
like

# exception message changes through time
try:
  {}["QWE"]
except KeyError, msg:
  msg = str(msg)
  key_start = msg.find("QWE")
  key_end = -(len(msg) - key_start + 3)


def super_eval(s, d):
    real_d = {}
    while 1:
        try:
          return eval(s, real_d)
        except KeyError, msg:
          key = str(msg)[key_start:key_end]
          real_d[key] = d[k]

(from memory and untested so there may be some mistakes)

I never even thought of compiling the code to look for the list of
names.  I think I'll rewrite that bit of code now.

Thanks Alex!

                    Andrew
                    dalke at dalkescientific.com






More information about the Python-list mailing list