This guide explains Template String Interpolations and Safe Processing through a focused example and practical reasoning. No prior knowledge of this specific operation is required.
Understanding the Concept
A t-string stores interpolation details so an application can decide how to render or validate them. This is useful for contextual escaping, but it is only safe when the processor applies the right rules for the output format.
When You Would Use This
Build a minimal HTML text renderer that escapes interpolated values.
Step-by-Step Example
from html import escape
def render_html_text(template):
result_parts = [template.strings[0]]
for interpolation, literal_text in zip(template.interpolations, template.strings[1:]):
result_parts.append(escape(str(interpolation.value)))
result_parts.append(literal_text)
return "".join(result_parts)
user_label = "<Admin>"
message_template = t"Hello {user_label}!"
print(render_html_text(message_template))
How the Example Works
The result contains <Admin>, so the untrusted value does not become an HTML tag in text context. This small demonstration does not handle arbitrary template HTML structure or attribute/URL contexts.
Important Details
For database operations, use parameterized queries rather than building SQL by converting any template to a string.
Try It Yourself
Try user_label = "A&B" and inspect the escaped result.
Common Beginner Mistakes
- Concatenating interpolation values directly into HTML without escaping.
- Using the same escaping rules for HTML text, attributes, URLs and SQL.
- Assuming t-strings automatically prevent injection even when the renderer is unsafe.
Key Takeaways
- A t-string stores interpolation details so an application can decide how to render or validate them.
- The result contains
<Admin>, so the untrusted value does not become an HTML tag in text context. - Avoid this mistake: Concatenating interpolation values directly into HTML without escaping.