method to intercept string formatting % operations

bradallen bradallen137 at gmail.com
Fri Feb 5 15:57:18 CET 2010


Hello,

For container class derived from namedtuple, but which also behaves
like a dictionary by implementing __getitem__ for non-integer index
values, is there a special reserved method which allows intercepting %
string formatting operations? I would like for my container type to
behave appropriately depending on whether the string formatting
operation has a string like this :

"whatever %s yadayada" % mycontainer  # needs to act like a tuple

"whatever %(key)s yadayada" % mycontainer  # needs to act like a
dictionary

I looked through the Python data model docs at <http://docs.python.org/
reference/datamodel.html#emulating-container-types> but only found
this:

"If the left operand of a % operator is a string or Unicode object, no
coercion takes place and the string formatting operation is invoked
instead."

Thanks!




More information about the Python-list mailing list