[Python-ideas] String formatting and namedtuple
ironfroggy at gmail.com
Wed Feb 11 22:05:25 CET 2009
On Wed, Feb 11, 2009 at 3:53 PM, Guido van Rossum <guido at python.org> wrote:
> 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__...
Perhaps the feature request here should be that vars() be able to work
on built-in types like these, so we could just use it as a simple
> --Guido van Rossum (home page: http://www.python.org/~guido/)
> Python-ideas mailing list
> Python-ideas at python.org
Read my blog! I depend on your acceptance of my opinion! I am interesting!
Follow me if you're into that sort of thing: http://www.twitter.com/ironfroggy
More information about the Python-ideas