method to intercept string formatting % operations

Raymond Hettinger python at rcn.com
Fri Feb 5 21:53:51 CET 2010


On Feb 5, 6:57 am, bradallen <bradallen... at gmail.com> wrote:
> 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


The implementation for str.__mod__ refuses to
treat tuples and tuple subclasses as a dictionary.
Since namedtuples are a subclass of tuple, you're
not going to have any luck with this one.

To see actual C code, look at PyString_Format() in
http://svn.python.org/view/python/trunk/Objects/stringobject.c?view=markup

	PyObject *dict = NULL;
          . . .
	if (Py_TYPE(args)->tp_as_mapping && !PyTuple_Check(args) &&
	    !PyObject_TypeCheck(args, &PyBaseString_Type))
		dict = args;

Since automatic conversion is out, you can instead use
the namedtuple._asdict() method for an explicit conversion:

>>> from collections import namedtuple
>>> Point = namedtuple('Point', 'x y')
>>> p = Point(5, 12)
>>> 'x: %(x)s' % p._asdict()
'x: 5'


Raymond



More information about the Python-list mailing list