Sub topic 12
string.Template for user-supplied templates
This chapter assumes you know f-strings, str.format(), dictionaries, and try/except. Here you will learn when string.Template is the safer choice and how to use it.
Why a separate template tool exists
An f-string is written in your source code, so only you control it. Sometimes the template text comes from outside the program, such as a config file, a database row, or a form where a user writes an email greeting. You cannot use an f-string for that, and str.format() is risky.
str.format() placeholders can reach into objects. A user who can write the template can read attributes you never meant to share:
class User:
def __init__(self, name, password):
self.name = name
self.password = password
user = User("Ada", "s3cret")
user_template = "Hello, {user.password}"
print(user_template.format(user=user))This prints Hello, s3cret. The template author reached an attribute you did not intend to expose.
string.Template only substitutes plain names. It has no attribute access, indexing, or format specs, so there is much less a template author can do.
Basic syntax
A placeholder is $ followed by an identifier. Use ${name} when letters follow the name directly. Write $$ for a literal dollar sign.
from string import Template
t = Template("Dear $name, you owe ${amount}USD. Fee: $$5.")
print(t.substitute(name="Ada", amount=40))
print(t.safe_substitute(name="Ada"))
try:
t.substitute(name="Ada")
except KeyError as e:
print("missing:", e)This prints:
Dear Ada, you owe 40USD. Fee: $5.
Dear Ada, you owe ${amount}USD. Fee: $5.
missing: 'amount'You can pass values as keyword arguments or as one dictionary: t.substitute({"name": "Ada"}).
substitute versus safe_substitute
| Method | Missing key | Malformed placeholder, such as a lone `$` |
|---|---|---|
| `substitute()` | Raises `KeyError` | Raises `ValueError` |
| `safe_substitute()` | Leaves the placeholder in the text | Leaves it in the text |
Use substitute() when a missing value is a bug you want to catch. Use safe_substitute() when the template is partly filled in stages, or when you would rather show an unfilled placeholder than crash.
Formatting numbers is your job
Template has no format specs. $price:.2f would insert the price and then print the characters :.2f. Format values first, then pass the strings in:
from string import Template
price = 1234.5
t = Template("Total: $total")
print(t.substitute(total=f"{price:,.2f}"))This prints Total: 1,234.50. The program decides how each value looks, and the template author only decides where it goes.
Common errors
- Writing
$name_suffixand expecting$namefollowed by_suffix. Identifiers include underscores, so use${name}_suffix. - Forgetting
$$in text with prices, which causes aValueErrorfromsubstitute(). - Expecting
$user.nameto read an attribute. It substitutes$userand leaves.nameas plain text. - Passing user-supplied values to
safe_substitute()and assuming nothing is left unfilled. Search the result for leftover$if that matters.
Exercise
A user-supplied template is "Hi $name, your code is ${code}X". You call substitute(name="Ada") and get an error. Which error is it, and which method would return text instead of raising?
Show answer
substitute() raises KeyError because the key "code" is missing. safe_substitute(name="Ada") returns "Hi Ada, your code is ${code}X" and leaves the unfilled placeholder in place.