[Tutor] Code evaluation inside of string fails with __get_item

Peter Otten __peter__ at web.de
Sat Dec 11 13:27:20 CET 2010


Tim Johnson wrote:

> This is a resend. I note that the original had an incorrect
> `reply-to' ID attached to it. (sorry)
> ------------------------------------------------------------------
> 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 __getitem__(self, key):

> Under certain circumstances, the embedded is code *not* executed.

The first step is to concentrate on just one class, at one point in the 
code. Then try to control the input to the method and find an argument where 
the code reproducibly fails.

> 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

Nothing, provided 

(1) the method is spelt __getitem__ (two leading and two trailing 
underscores)

(2) the left side is a python string with legal "%(...)s"-style format 
expressions. Given a format string

s = "%(s.upper())s" 

try to feed it a real dict

print s % {"s.upper()":"OK") # should print OK

to verify that that precondition is met.

Peter



More information about the Tutor mailing list