[Python-ideas] String formatting and namedtuple
Calvin Spealman
ironfroggy at gmail.com
Wed Feb 11 22:19:03 CET 2009
On Wed, Feb 11, 2009 at 4:10 PM, Guido van Rossum <guido at python.org> wrote:
> On Wed, Feb 11, 2009 at 1:05 PM, Calvin Spealman <ironfroggy at gmail.com> wrote:
>> 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:
>>>> 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
>> wrapper.
>
> I don't think you need vars(). vars() is for discovery of *all*
> attributes, but .format() doesn't need that. An adaptor like this
> would do it, but it would be nice if there was a shorthand for
> something like this (untested) snippet:
>
> class GetItemToGetAttrAdaptor:
> def __init__(self, target):
> self.target = target
> def __getitem__(self, key):
> try:
> return getattr(self.target, key)
> except AttributeError as e:
> raise KeyError(str(e))
>
> You could then use "re={real} im={imag}".format(GetItemToGetAttrAdaptor(1j+2))
What if non-__dict__-having objects were treated exactly like that by
vars(), returning this adapter and providing a uniform interface? Note
that it would not, especially when invoked via vars(), allow
setitem->setattr mapping.
--
Read my blog! I depend on your acceptance of my opinion! I am interesting!
http://techblog.ironfroggy.com/
Follow me if you're into that sort of thing: http://www.twitter.com/ironfroggy
More information about the Python-ideas
mailing list