class derived from dict in eval

Andrew Dalke adalke at
Tue Feb 25 16:00:49 CET 2003

> 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

# exception message changes through time
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:
          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!

                    dalke at

More information about the Python-list mailing list