[Python-Dev] PEP 292, Simpler String Substitutions

Barry A. Warsaw barry@zope.com
Wed, 19 Jun 2002 23:13:55 -0400


>>>>> "GvR" == Guido van Rossum <guido@python.org> writes:

    GvR> I think little would be lost if sub() always required a dict
    GvR> (or perhaps keyword args, although that feels like a YAGNI
    GvR> now).

IME, doing the locals/globals trick is really helpful, but I might be
willing to let go on that one, because I can wrap that functionality
in my _() function.

The reason for this is that I'd say 80-90% of the time, you have value
you want to interpolate into the string sitting around handy in a
local variable.  And that local variable has the name of the key in
the template string.  So what you (would) end up doing is:

    ...
    name = getNameSomehow()
    ...
    country = getCountryOfOrigin(name)
    ...
    return '$name was born in $country'.sub({'name': name,
                                             'country': country})

Do that a few hundred times and you start wanting to make that a lot
more concise. :)

    GvR> I think that the key thing here is to set the precedent of
    GvR> using $ and the specific syntax proposed, not necessarily to
    GvR> have this as a built-in string methong.

I'll note that before this idea gained PEPhood, Guido and I discussed
using an operator, like:

    return '$name was born in $country' / dict

but came around to the current proposal's string method.  I agree with
Guido that it's the use of $strings that is important here, and I
don't care how the interpolation is actually done (builtin, string
method, etc.), though relegating it to a module would, I think, make
this a rarely used syntax.

-Barry