[Python-ideas] String formatting and namedtuple

Georg Brandl g.brandl at gmx.net
Mon Feb 16 22:16:19 CET 2009

Guido van Rossum schrieb:
> On Mon, Feb 16, 2009 at 12:48 AM, Christian Tanzer <tanzer at swing.co.at> wrote:
>> A fair amount of my use cases involve a non-literal format string
>> (i.e., passed in as argument, defined as module or class variable, or
>> even doc-strings used as format strings). I'd guess that most
>> non-literal format strings are used together with dictionaries.
>> Unfortunately, it's hard to grep for this :-(, so I can't give you
>> hard numbers.
> It would be pretty simple to rig up 2to3 to report any string literals
> containing e.g. '%(...)s' that are not immediately followed by a %
> operator.

The major problems I see are

1) __mod__ application with a single right-hand operand (a tuple makes it
   a string formatting to 100%, at least without other types overloading %)
2) format strings coming from external sources

The first can't be helped easily.  For the second, a helper function that
converts %s format strings to {0} format strings could be imagined.  A call
of the form

   fmtstr % (a, b)

would then be converted to

   _mod2format(fmtstr).format(a, b)

To fix 1), _mod2format could even return a wrapper that executes .__mod__
on .format() if fmtstr is not a string. <half-wink>

>> Another, probably fairly common, use case involving non-literal
>> strings is %-formatting in I18N strings -- though it might be possible
>> to fix these automatically.
> Plus, i18n is one of the motivators for .format() -- less chance of
> forgetting to type the trailing 's' in '%(foobar)s' and the ability to
> rearrange positional arguments a la "foo {1} bar {0} baz".

I expect future generations of translators will be thankful.  Current
generation may be angry when they have to revise their .po files :)


Thus spake the Lord: Thou shalt indent with four spaces. No more, no less.
Four shall be the number of spaces thou shalt indent, and the number of thy
indenting shall be four. Eight shalt thou not indent, nor either indent thou
two, excepting that thou then proceed to four. Tabs are right out.

More information about the Python-ideas mailing list