Sub topic 12
string.Template for user-supplied templates
This chapter assumes you know f-strings, str.format(), and % formatting from the earlier chapters. It also assumes you can use dictionaries, try/except, and keyword arguments. By the end you should be able to fill in templates written by someone else without giving that person access to your program's internals.
Why a separate templating tool exists
An f-string is Python source code. It runs with your variables in scope, and only you can write it. A str.format() template looks like data, because it is an ordinary string that could come from a file, a database, or a web form. It is more powerful than it looks, though. A format field can reach into attributes and items of the objects you pass in.
class User:
def __init__(self, name):
self.name = name
self._token = "s3cret"
user = User("Ada")
template = "Hello {user.name}, {user._token}"
print(template.format(user=user))This prints Hello Ada, s3cret. The person who wrote the template never touched your code, yet they read a private attribute. With a deeper path such as {user.__class__.__init__.__globals__}, they can reach module globals as well.
string.Template removes this whole class of problem. It supports one operation: replace a named placeholder with str(value). It has no attribute access, no indexing, no format specs, and no expression evaluation.
The working model
A Template stores the text. A call to substitute() or safe_substitute() scans it for placeholders and looks each name up in a mapping. Then it joins the pieces together.
from string import Template
t = Template("Hello, $name! You owe ${amount}USD. Price: $$5")
print(t.substitute(name="Ada", amount=12))This prints Hello, Ada! You owe 12USD. Price: $5. There are three placeholder forms.
| Syntax | Meaning |
|---|---|
| `$name` | Replaced by the value for `name`. The name ends at the first character that cannot be part of an identifier. |
| `${name}` | The same, but with explicit boundaries. Use it when letters follow directly, as in `${amount}USD`. |
| `$$` | A literal dollar sign. |
A name is made of ASCII letters, digits, and underscores, and cannot start with a digit. Matching ignores case, but lookup does not. $Name and $name are different keys.
Providing the values
You can pass a mapping, keyword arguments, or both. If a key appears in both, the keyword argument wins.
from string import Template
t = Template("$greeting, $name!")
values = {"greeting": "Hello", "name": "Ada"}
print(t.substitute(values))
print(t.substitute(values, greeting="Welcome"))The output is Hello, Ada! followed by Welcome, Ada!.
Every value is passed through str(). A Template accepts no format spec, so $price with 3.14159 prints 3.14159. Format numbers yourself before substituting:
from string import Template
t = Template("$name paid $amount")
print(t.substitute(name="Ada", amount=f"{1234.5:,.2f}"))This prints Ada paid 1,234.50. The f-string is trusted code you wrote. The template is the untrusted part.
Errors and `safe_substitute()`
substitute() is strict. It raises KeyError when a name has no value, and ValueError when a $ is not followed by a valid placeholder. safe_substitute() never raises for these two reasons. It leaves the offending text in the output.
from string import Template
t = Template("Hi $name, your code is $code.")
try:
t.substitute(name="Ada")
except KeyError as e:
print("missing:", e)
print(t.safe_substitute(name="Ada"))
bad = Template("Cost: $ 5")
try:
bad.substitute()
except ValueError:
print("invalid placeholder")
print(bad.safe_substitute())The output is:
missing: 'code'
Hi Ada, your code is $code.
invalid placeholder
Cost: $ 5Choose based on who is at fault when a value is missing:
- Use
substitute()when a missing value is a bug in your program. Failing loudly finds the bug. - Use
safe_substitute()for partial rendering, such as filling in some fields now and the rest later. It also suits previews of a user's draft template.
One trap: safe_substitute() hides typos. If $nmae is never filled in, the output silently contains $nmae. Check for leftover placeholders before sending the result anywhere important.
Validating a user's template up front
Python 3.11 added two methods for checking a template before you render it. is_valid() reports whether every $ is well-formed. get_identifiers() lists the placeholder names in order of first appearance, without duplicates.
from string import Template
ALLOWED = {"name", "order_id"}
def check_template(text):
t = Template(text)
if not t.is_valid():
return "Template has a malformed placeholder."
unknown = set(t.get_identifiers()) - ALLOWED
if unknown:
return f"Unknown fields: {', '.join(sorted(unknown))}"
return None
print(check_template("Hi $name, order $order_id shipped."))
print(check_template("Hi $name, your $secret is ready."))
print(check_template("Costs $ 5"))The first call returns None, the second reports Unknown fields: secret, and the third reports the malformed placeholder. On Python 3.10 and earlier these two methods do not exist. There you can catch the ValueError from substitute() instead.
Customizing the syntax
Template is designed for subclassing. Three class attributes control the grammar:
delimiteris the character that starts a placeholder. The default is$.idpatternis a regular expression for names. The default is(?a:[_a-z][_a-z0-9]*).flagsholds thereflags. The default isre.IGNORECASE.
A custom delimiter helps when your text contains many dollar signs:
from string import Template
class HashTemplate(Template):
delimiter = "#"
t = HashTemplate("Order #id costs $5 (#{qty} items)")
print(t.substitute(id=42, qty=3))This prints Order 42 costs $5 (3 items). Here $ is plain text, and ## would produce a literal #.
A custom idpattern can allow dotted names. This is still a plain dictionary lookup with the key "user.name". It does not walk attributes.
from string import Template
class DottedTemplate(Template):
idpattern = r"[a-z_][a-z0-9_]*(?:\.[a-z_][a-z0-9_]*)*"
t = DottedTemplate("Hello $user.name")
print(t.substitute({"user.name": "Ada"}))Write the pattern with non-capturing groups (?:...), as above. A capturing group would break the way Template combines its patterns into one regular expression.
Limits and gotchas
- No attribute access. In
$user.name, the placeholder is$user, and.nameis literal text that follows it. Without a customidpattern, this raisesKeyError: 'user'unless you supplyuser. - No format specs, no conversions. Format every value before you pass it in.
- Lookup is exact. The name matching ignores case, but the dictionary lookup does not.
- Passing objects still matters. Template calls
str()on each value. If you pass a custom object, its__str__may expose more than you intend. Pass plain strings and numbers. - Templates are not escaping.
Templatedoes not sanitize its output. If you insert user text into HTML, SQL, or a shell command, you must still escape it for that target. - Speed.
Templateis slower than an f-string and offers fewer features. Use it for its restricted behavior, not for performance.
Choosing between the tools
| Situation | Best choice |
|---|---|
| Text and values are both written in your source code | f-string |
| Template is stored in your own code or config, and you need format specs | `str.format()` |
| Template comes from users, files, or a database you do not control | `string.Template` |
| Maintaining old code | Whatever it already uses (`%` or `.format()`) |
If you need conditionals or loops in user templates, Template is too small. A sandboxed templating library is the next step, but that is outside this chapter.
Exercises
Exercise
What do Template("$a-$b").substitute(a="x", b="y") and Template("${a}1").substitute(a="x") print, and why is the braced form needed in the second?
Show answer
The first prints x-y, because - is not an identifier character, so each name ends there. The second prints x1. Without braces, $a1 would be read as a placeholder named a1, which has no value and raises KeyError. Braces mark where the name ends.
Exercise
A user stores the template "Dear $name, your balance is $balance." You call safe_substitute(name="Ada"). What is the result, and what is one risk of using safe_substitute() here instead of substitute()?
Show answer
The result is "Dear Ada, your balance is $balance." The risk is that a missing or misspelled value does not raise an error. The raw $balance placeholder ends up in the output, and may reach a customer unnoticed. Check for leftover placeholders, or use substitute() when a missing value is a bug.
Exercise
Why is "{user._token}".format(user=user) a problem when the template is user-supplied, while Template("$user").substitute(user="Ada") is not?
Show answer
str.format() lets a template read attributes and items of the objects you pass, so a template author can reach private data such as _token. Template only substitutes names with str(value). It has no attribute or index syntax, so the template can only see the values you chose to put in the mapping.