Question re: eval()

Alex Martelli aleaxit at yahoo.com
Fri Dec 29 19:30:11 EST 2000


"Clarence Gardner" <clarence at netlojix.com> wrote in message
news:978109654.339714327 at news.silcom.com...
>
> I want to eval() an expression, but have some of the variables in it be
> lazily evaluated.  E.g.,
>
> class D:
>     def __getitem__(self, name):
>         if name == 'n':
>             return 3
>
> d = D()
> x = eval('n + 1', d)
>
> but the eval function accepts only a dictionary as the second parameter.
> Is there any amazing way to do this?

Funny, that was one of my first serious questions to this forum
as I really cranked up my Python use, in 1999 -- and I was soundly
flamed for asking this (timbot was apparently adamant that it was
a better design to have the user enter the expression as 'd.n + 1',
where d.n is easily lazy-evaluated via __getattr__).  I see that this
time you HAVE been given the answer -- the co_names attribute
of the code object that you get by compiling the expression is
almost good enough (not real lazy-evaluation, but at least you do
get to learn which variable names the expression uses -- in some
cases, precomputing those can be OK; this only matters in terms
of performance if a LOT of and/or use (shortcircuiting) in your
typical expressions COULD potentially save you _many_ costly
variable-fetches -- in practice, in my case, using co_names was
more or less OK, though not quite as good as the 'd.n + 1' idea).


Alex






More information about the Python-list mailing list