[Tutor] Code evaluation inside of string fails with __get_item

Tim Johnson tim at johnsons-web.com
Sat Dec 11 01:24:52 CET 2010

I'm using Python 2.6.5.
The following problem is coming from inside of a complex code base
and involves an implementation that I have used for years, and is
now failing to execute in certain conditions.
This problem occurs with either of the follow two classes, which are
'lifted' from 'Python Cookbook'. Class code follows:
class Eval:
    def __init__(self, globals=None, locals=None):
        self.globals = globals or {}
        self.locals = locals or None

    def __getitem__(self, key):
        if self.locals is None:
            self.locals = sys._getframe(1).f_locals
        key = key % self
        return eval(key, self.globals, self.locals)
## and this one:
class Evalx: 
	def __init__(self, localvals = None, globalvals = None):
		if localvals is None : 
			self.locals = sys._getframe(1).f_locals
		else : 
			self.locals = locals
		if globalvals is None : 
			self.globals = sys._getframe(1).f_globals
		else : 
			self.globals = globals
	def __getitem__(self,key):
		return eval(key,self.globals,self.locals)
## either are used the same way: To evaluate code inside of a string
## A larger description can be found at:
## http://code.activestate.com/recipes/66018-evaluating-code-inside-strings/
The execution looks like this:
self.content = formatted_string % Evalx()
## where 'self' refers to an object of another class, that uses the
## Eval class 
Under certain circumstances, the embedded is code *not* executed. 
By inserting debugging stubs, I can see that the the Eval/Evalx instantiation
does occur, but the overloaded function call to __get_item does
*not* occur. I have also found that a seemingly unrelated event having
to do with file I/O must be causing a side effect. However, to keep
things simple, I am first asking the following question:
What would cause __get_item__ not to be called? I can confirm by
other testing that the embedded codde is properly composed with
matching keywords.

This is probably the most difficult to resolve problem I've ever run
into in python. My lack of understand of the underlying code in the
Eval classes is probably a contributing factor. 

tim at johnsons-web.com or akwebsoft.com

More information about the Tutor mailing list