Cannot pass UserDict to eval()?

Frank Niessink frankn=nuws at cs.vu.nl
Tue Aug 15 12:39:14 EDT 2000


Ryan LeCompte <rmlecompte at hotmail.com> wrote:

> Try this:
> eval('x+1', {}, u.data)

> That will give you what you're looking for. u is just a class instance, and
> the 'data' attribute actually contains the dictionary. u is just a wrapper
> around the dictionary object.

Unfortunately, that doesn't help. I want to do lazy evaluation, so it's 
vital that u.__getitem__ is called, which doesn't happen if I just 
pass u.data.                    

The expression may contain variables that need to be read from a database.
I don't know beforehand which variables are used in the expression, and
I don't want to read all possible variables from the database. 

[while I'm typing this I'm actually getting to the solution!]

Another way to find out which variables are used in the expression
is of course to use compile(). E.g.:

>>> c = compile('x=1','<string>','eval')
>>> print c
<code object ? at 121db8, file "<string>", line 0>
>>> print c.co_names
('x',)

Cool. Problem solved.

Cheers, Frank

-- 
"Get to the ship," shouted Ford. "I don't want to know, I don't want to see, 
I don't want to hear," he yelled as he ran, "this is not my planet, I didn't
choose to be here, I don't want to get involved, just get me out of here, and
get me to a party, with people I can relate to!"
	-- Douglas Adams, 'Life, the Universe, and Everything'



More information about the Python-list mailing list