[New-bugs-announce] [issue6081] str.format_from_mapping()

Raymond Hettinger report at bugs.python.org
Fri May 22 01:23:16 CEST 2009


New submission from Raymond Hettinger <rhettinger at users.sourceforge.net>:

The old % formatting allowed arbitrary mappings:

  >>> class Default(dict):
  ...     def __missing__(self, key):
  ...         return key
  ...
  >>> s = '%(name)s was born in %(country)s'
  >>> s % Default(name='Guido')
  'Guido was born in country'

But the new str.format() demands mappings be first converted to a
regular dict using **kwargs, so something like the above is not possible.

  >>> s = '{name} was born in {country}'
  >>> s.format(**Default(name='Guido'))
  Traceback (most recent call last):
    File "<pyshell#27>", line 1, in <module>
      s.format(**Default(name='Guido'))
  KeyError: 'country'

There is a work-around using string.vformat() but it is obscure and awkward:

  >>> import string
  >>> string.Formatter().vformat(s, (), Default(name='Guido'))
  'Guido was born in country'

Instead, it would be better to offer an alternate method:

  >>> s.format_from_mapping(Default(name='Guido'))
  'Guido was born in country'

----------
messages: 88173
nosy: rhettinger
severity: normal
status: open
title: str.format_from_mapping()
type: feature request
versions: Python 2.7, Python 3.2

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue6081>
_______________________________________


More information about the New-bugs-announce mailing list