Question re: eval()

Fredrik Lundh fredrik at effbot.org
Fri Dec 29 15:36:23 EST 2000


Clarence Gardner wrote:
> 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?

not really "lazy" evaluation, but the following trick
lets you figure out what names you need to define
before evaluating it:

def getvalue(name):
    # get value of variable "name"
    print "fetch", name
    return len(name)

myexpr = "a + bb + ccc"

# compile expression
code = compile(myexpr, "<string>", "eval")

# populate dictionary
dict = {}
for name in code.co_names:
    dict[name] = getvalue(name)

print "result", eval(code, dict)

</F>

<!-- (the eff-bot guide to) the standard python library:
http://www.pythonware.com/people/fredrik/librarybook.htm
-->





More information about the Python-list mailing list