[Python-ideas] String formatting and namedtuple

Adam Olsen rhamph at gmail.com
Wed Feb 11 09:41:21 CET 2009


On Tue, Feb 10, 2009 at 3:43 AM, Lie Ryan <lie.1296 at gmail.com> wrote:
> I've been experimenting with namedtuple, it seems that string formatting
> doesn't recognize namedtuple as mapping.
>
> 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
>
> Sorry, if this issue has been discussed before.

Exposing a dict API would pollute namedtuple.  What's more, it's
unnecessary in python 2.6/3.0:

>>> print('one = {0.x}, two = {0.y}'.format(nt))
one = 12, two = 32

(And before you ask, no, I don't think it's worth adding the dict API
just to make old-style formatting a tiny bit easier.)

-- 
Adam Olsen, aka Rhamphoryncus



More information about the Python-ideas mailing list