Direct concatenation between Template and str objects is prohibited in Python because it creates ambiguity about how the string should be
interpreted.
When you concatenate a Template with a str, it’s unclear whether the str should be:
- Treated as a static string part of the template
- Treated as an interpolation value that should be processed dynamically
This ambiguity can lead to unexpected behavior and makes the code’s intent unclear. Python’s PEP 750 specification explicitly prohibits this
operation to force developers to be explicit about their intentions.
The Template type is designed to clearly separate static string parts from dynamic interpolations, and allowing direct concatenation with str would
undermine this design principle.
What is the potential impact?
Direct concatenation of Template and str objects will result in a runtime error, causing the application to fail. Additionally, even if it were
allowed, the ambiguous nature of such operations could lead to security vulnerabilities or incorrect string processing, especially in contexts like
HTML templating or SQL query construction where the distinction between static and dynamic content is critical.
How to fix?
If the string should be treated as static text, wrap it in a Template constructor before concatenation.
Non-compliant code example
name = "World"
template = t"Hello " + name # Noncompliant
Compliant code example
name = "World"
template = t"Hello " + Template(name)
Documentation