[Tutor] Code evaluation inside of string fails with __get_item

Tim Johnson tim at johnsons-web.com
Sat Dec 11 17:42:32 CET 2010

* Peter Otten <__peter__ at web.de> [101211 03:41]:
> (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.
  Should be 
  print s % {"s.upper()":"OK"} ## closing brace
  I've never had the occasion to use assert() or any other
  python - shooting tools, any thoughts on that?

  I am dealing with a programmatically composed format
  string, that originates from a source (html) file
  It may be 

  1)read from the file external to the object
    and the source string passed into the object at instantiation.
    The composed string is then translated correctly and
	the embedded is evaluated.

  2)read from the source file 'within' the object namespace.
    In this case, the embedded code within the composed format
	is *not* evaluated. And <blush> I can observe the
	legal "%(...)s"-style format expressions.

  3)*But* (and here is the kicker), if the composed format
    string is then dumped to a pickle file and then loaded
	from that pickle file it is then evaluated. 

  :) As near as I can see. And that suggests a workaround.
  Unfortunately, no error messages are generated either at
  runtime or by pychecker.

  Thanks Peter
tim at johnsons-web.com or akwebsoft.com

More information about the Tutor mailing list