[Python-ideas] String formatting and namedtuple

Raymond Hettinger python at rcn.com
Wed Feb 11 21:11:28 CET 2009


[Lie Ryan]
> I've been experimenting with namedtuple, it seems that string formatting 
> doesn't recognize namedtuple as mapping. 

That's because a named tuple isn't a mapping ;-)
It's a tuple that also supports getattr() style access.


> from collections import namedtuple
> Nt = namedtuple('Nt', ['x', 'y'])
> nt = Nt(12, 32)
> print 'one = %(x)s, two = %(y)s' % nt
> 
> # output should be:
> one = 12, two = 32
> 
> currently, it is possible to use nt._asdict() as a workaround, but I 
> think it will be easier and more intuitive to be able to use namedtuple 
> directly with string interpolation

This is not unique to named tuples.  String interpolation and the string format
do not use getattr() style access with any kind of object:

     print '<%(real)s, %(imag)s>' % (3+4j)    # doesn't find real/imag attributes


Raymond



More information about the Python-ideas mailing list