Late binding eval()?

Kevin Smith Kevin.Smith at sas.com
Tue Aug 24 14:25:54 EDT 2004


I want to evaluate an expression using eval(), but I only want to supply 
the variable values "on demand."  For example, let's say that I want to 
evaluate 'x+y'.  Normally, I would create a dictionary containing 'x' 
and 'y' with their corresponding values and pass it in as the globals or 
locals.  However, in my application, I'm getting an arbitrary expression 
from the user.  I thought that I could just create a dictionary-like 
object and override __getitem__ to look up values in a database as they 
were called for, but that didn't work.

Another way of doing this would be to parse the expression and find all 
of the top-level variables.  This could be a little tricky (i.e. [x for 
x in mylist] would only require 'mylist' to be in the dictionary of 
globals/locals.

Does anyone have any ideas on how to do this?

-- 
Kevin Smith
Kevin.Smith at sas.com



More information about the Python-list mailing list