string interpolation for python

Steven D'Aprano steve+comp.lang.python at pearwood.info
Mon Apr 2 07:54:53 EDT 2012


On Mon, 02 Apr 2012 02:11:46 -0700, Yingjie Lan wrote:


> Both template based and dict-based formatting require writing the
> identifier three times:

> >>> name = 'Peter'
> >>> "Are you %(name)s"%{'name':name}

They don't *require* this at all.

"Are you %s" % name

For trivial examples, you have trivial syntax. For more complex examples, 
you have a more powerful system: % can accept *any* dictionary, so you 
aren't limited to just pre-existing variables.

That, by the way, is perhaps the biggest problem with this idea of 
dynamic strings: not that it is too powerful, but that it is TOO WEAK. It 
can only retrieve names from a single namespace, and the programmer has 
no control over which namespace that will be. The only way to feed named 
values into the dynamic string is by creating variables.

With existing formatting systems, the programmer has complete control 
over what names get used. You can set up a series of separate namespaces 
and choose between them as needed:

a = dict(name="Fred", job="butcher")
b = dict(name="Sue", job="SAS sharp-shooter")
c = dict(name="Mary", job="brain surgeon")
d = dict(name="Tony", job="enforcer for the Russian mob")
for namespace in (a, b, c, d):
    print ("%(name)s works as a %(job)s." % namespace)


Using your dynamic strings:

for namespace in (a, b, c, d):
    name = namespace["name"]
    job = namespace["job"]
    print ("$name$ works as a $job$.")

and it has the side-effect that it has created some variables that are no 
longer needed.

Also notice that because you have to create variables first, the dynamic 
string actually requires you to write the identifier MORE times, not 
fewer.

So your proposal is actually weaker than what Python already has. So why 
bother? All this does is add more things to learn, more complexity in the 
compiler and parser, for what? Things that you can already do.


> If dynamic string is used:
> >>> "Are you $name$?"

And where does name come from? It's all too magical. With the existing 
format strings, the programmer has *complete* control of where it comes 
from:

"Are you %(name)s?" % locals()  # from a local variable `name`
"Are you %(name)s?" % globals()  # from a global variable `name`
"Are you %(name)s?" % namespace  # from any namespace you like

and similar for both format() and Template.


-- 
Steven



More information about the Python-list mailing list