[Python-ideas] String formatting and namedtuple

Christian Tanzer tanzer at swing.co.at
Tue Feb 17 08:47:57 CET 2009


Georg Brandl wrote at Mon, 16 Feb 2009 22:16:19 +0100:

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

Please note that the right-hand operand can be a dictionary
(more specifically, any object implementing `__getitem__()`)

For objects implementing `__getitem__`, the stuff inside the
parentheses of `%(...)s` can get pretty fancy.

--
Christian Tanzer                                    http://www.c-tanzer.at/



More information about the Python-ideas mailing list