yet another recipe on string interpolation

Raymond Hettinger vze4rx4y at verizon.net
Mon Nov 8 15:11:12 EST 2004


> By using named methods instead of the % operator:
> * we avoid the precedence issues associated with %
> * we avoid confusion as to whether a tuple is an acceptable second argument
> * we avoid confusion with "%s" style inputs.
> * we enable keyword arguments:  mytempl.substitute(weather="rainy")
> * we get something more documenting than punctuation.

s/documenting/self-documenting


One other thought.  In both the original and current design, it is possible and
perhaps likely that the template instantiation and method application will be
remote from one another.  Unfortunately, the original design forced the
safe/non-safe decision to be made at the time of instantiation.

When you think about it, that was a mis-assignment of responsibilities.  The
choice of safe vs. non-safe has nothing to do with the contents of the template
and everything to do with how the template is used. The code that uses the
template (applies the method) needs to know whether it should handle exceptions
or not.  Hence, it should be the one to make the safe / non-safe choice.

Consider whether the following fragment is correct:

     mytemp % values

Should it have been wrapped in a try/except?  Can values be a tuple?  Do we have
a reasonable expectation of whether mytemp contains $placeholder ro
%(placeholder)s?  The approach taken by the revised pep makes all of the issues
clear.

There were a couple of downsides to switching the API.  Formerly, if you knew
that client code used the % operator with a dictionary, then you could pass in
an instance of the Template class and have it do the right thing (polymorphism
on a good day).  Also, most folks already know what % means, so there was less
of a learning curve.  IOW, the switch was an improvement, but not a pure win.
C'est le vie.


Raymond Hettinger





More information about the Python-list mailing list