class derived from dict in eval

Seo Sanghyeon unendliche at hanmail.net
Mon Mar 3 07:15:04 EST 2003


"Andrew Dalke" wrote:

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

Indeed. First, it seems eval() raises NameError, not
KeyError. And key_end calculation is wrong. Finally, the
last line's `k` is typo of `key`.

Following is Python interactive session that uses correct
version of above code.

----
Python 2.2.2 (#37, Oct 14 2002, 17:02:34) [MSC 32 bit (Intel)] on win32
Type "copyright", "credits" or "license" for more information.
IDLE 0.8 -- press F1 for help
>>> class mydict(dict):
...     def __getitem__(self, key):
...         return dict.__getitem__(self, key) * 2

>>> d = mydict()
>>> d['x'] = 1
>>> eval('x', d) # doesn't do what we want
1
>>> # exception message changes through time
>>> try:
...     foo
... except NameError, msg:
...     msg = str(msg)
...     key_start = msg.find('foo')
...     key_end = -(len(msg) - key_start) + len('foo')

>>> msg[key_start:key_end]
'foo'
>>> def super_eval(s, d):
...     real_d = {}
...     while 1:
...         try:
...             return eval(s, real_d)
...         except NameError, msg:
...             key = str(msg)[key_start:key_end]
...             real_d[key] = d[key]

>>> super_eval('x', d) # it works!
2
>>>




More information about the Python-list mailing list