[Python-ideas] string.Template v2

Stephen J. Turnbull stephen at xemacs.org
Fri Nov 29 02:13:04 CET 2013


anatoly techtonik writes:

 > Good question. I'd say format language is too complicated. It is the
 > same cryptic printf-like char-micromanagement language syntax, where
 > every byte counts even if unreadable.

In fact, .format() is *not* complicated in its basic use:

"I propose a fine of ${payment} for not reading the docs.".format(payment=100)

(Note that this isn't Perl, the "$" is a literal. :-)  But when you
don't have a TABLE element available for formatting tables, width,
precision, base, and the like are *necessary* information for nice
output.  Do you really think it's readable to write

"I propose a fine of ${payment: type=float precision=2} for not reading the docs.".format(payment=100)

vs.

"I propose a fine of ${payment:.2f} for not reading the docs.".format(payment=100)

.format() provides simple syntax for simple tasks, and more complex
syntax for tasks requiring more precision of expression.  It's true
that the marshalling of substitution values (either as keyword
arguments or in a **kw dictionary) is exposed here in the invocation
of .format() itself, but you don't avoid marshalling in Django or
other web frameworks, it's just in a different place with somewhat
different requirements.  Web framework templating languages do avoid
"cryptic printf-like char-micromanagement", but they can do that
because they delegate the styling to HTML and CSS.

It's true that such template languages allow things like object
attribute access, but there are severe restrictions, and deciding on
the restrictions is a very subtle matter.  It's generally agreed that
separation of business logic from presentation is a Good Thing[tm], so
allowing attribute access and filtering is *apparently* a step in the
Wrong direction.  Where "apparent" becomes "actual" is unclear,
especially for the general-purpose facility that Python must provide.

Although AFAIK attribute access and filter syntax are common features
of popular templating languages, I don't think it's a good idea for
Python to advocate a particular set of features in its format language
when the set of commonly accepted features is quite restricted (eg,
one level of object attribute access), so in practice templating
languages are not going to go away.  On the Python side, Python cannot
assume that the output language will be a structured markup language
with styling features; the low-level formatting syntax is still
needed.

-1 on adding more templating features to Python's stdlib; .format()
already hits the sweet spot given current best practice IMO.



More information about the Python-ideas mailing list