[Python-ideas] String formatting and namedtuple

Guido van Rossum guido at python.org
Wed Feb 11 22:23:50 CET 2009


On Wed, Feb 11, 2009 at 1:19 PM, Calvin Spealman <ironfroggy at gmail.com> wrote:
> 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.

Having a __dict__ is not the deciding factor, it would be whether
__getitem__ is defined. You could try

try:
  val = x[key]
except AttributeError:
  val = getattr(x, key)

but I worry this is likely to mask bugs where one simply passed the
wrong object.

(Also I realize that my example .format(Adaptor(...)) doesn't work --
it would have to be .format(**Adaptor(...)).)

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



More information about the Python-ideas mailing list