[Python-ideas] String formatting and namedtuple

Guido van Rossum guido at python.org
Wed Feb 11 21:53:15 CET 2009


On Wed, Feb 11, 2009 at 12:11 PM, Raymond Hettinger <python at rcn.com> wrote:
>
> [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

Hm... I see a feature request brewing. In some use cases it might make
a *lot* of sense to have a variant of .format() that uses __getattr__
instead of __getitem__...

-- 
--Guido van Rossum (home page: http://www.python.org/~guido/)



More information about the Python-ideas mailing list