[Python-ideas] String formatting and namedtuple

Guido van Rossum guido at python.org
Wed Feb 11 22:10:17 CET 2009

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):
      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))

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

More information about the Python-ideas mailing list