Author pfremy
Recipients
Date 2004-03-03.09:40:46
SpamBayes Score
Marked as misclassified
Message-id
In-reply-to
Content
Logged In: YES 
user_id=233844

I have exactly the same need as the original poster. The
only difference in my case is that I inhreted a dictionnary.

I want to use the eval() function as a simple expression
evaluator. I have the
follwing dictionnary:
d['a']='1'
d['b']='2'
d['c']='a+b'

I want the following results:
d[a] -> 1 
d[b] -> 2 
d[c] -> 3

To do that, I was planning to use the eval() function and
overloading the __getitem__ of the global or local dictionnary:

class MyDict( dict ) : 
	def __getitem__( self, key ):
		print "__getitem__", key
		val = dict.__getitem__( self, key )
		print "val = '%s'" % val
		return eval( val , self )

But it does not work:
d[a]:
__getitem__ a
val = '1'
-> 1

d[b]:
__getitem__ b
val = '2'
-> 2

d[c]:
__getitem__ c
val = 'e+1'
ERROR
Traceback (most recent call last):
  File "test_parse_jaycos_config.py", line 83, in testMyDict
    self.assertEquals( d['c'], 2 )
  File "parse_config_file.py", line 10, in __getitem__
    return eval( val , self )
  File "<string>", line 0, in ?
TypeError: cannot concatenate 'str' and 'int' objects

d['c'] did fetch the 'a+1' value, which was passed to eval.
However, eval()
tried to evaluate the expression using the content of the
dictionnary instead
of using __getitem__. So it fetched the string '1' for 'a'
instead of the value 1, so the result is not suitable for
the addition.

History
Date User Action Args
2007-08-23 13:50:45adminlinkissue215126 messages
2007-08-23 13:50:45admincreate