class derived from dict in eval
Andrew Dalke
adalke at mindspring.com
Wed Feb 26 01:50:46 EST 2003
Alex:
> Wow -- heroic, really...
Naah, more like stubborn. ;)
> Hmmm, one architectural one, I think -- what happens if
> d is, say, {'a': 23}, while s is, say, '{}["a"]', which
> SHOULD raise a KeyError? I think this will loop forever...
In the context from which this is done, that cannot happen
because I haven't documented that {} is valid. *ahem*
OTOH, your code would be tricky because I do have a
reference to 'math', so people can do math.abs(). The co_names
solution yields
>>> compile("math.abs(c)", "<string>", "eval")
<code object ? at 014BD900, file "<string>", line -1>
>>> _.co_names
('math', 'abs', 'c')
>>>
Hmmm... it's theoretically possible that my dict-like object
defines an 'abs' which takes a long time to compute, so that a
possible workaround like
for name in co_names:
try:
real_d = d[name]
except KeyError:
pass
eval(compiled, real_d)
would trigger computing an 'abs' when it shouldn't. I say
theoretically because all of the names used should be all
caps, possibly with an "_", but that's not prohibited.
So what I think I'll do is just add your double check and leave
my code as it is.
> You're welcome! I'm slightly surprised I didn't already
> post this kind code in the past, put it in the cookbook,
> or something like that, but some googling suggests I didn't.
Feel free to add my trick with your fix - it might be useful for
a few cases.
Andrew
dalke at dalkescientific.com
More information about the Python-list
mailing list