First of all, `python3.14` is not yet officially out. But the Release Candidate 2 is available to be downloaded and installed. This is fairly grok-able.
sudo tar xvf Python-3.14.0rc2.tgz`
cd Python-3.14.0rc2/
sudo ./configure --enable-optimizations --enable-shared LDFLAGS="-Wl,-rpath=/usr/local/lib"
sudo make -j$(nproc)
sudo make altinstall
a = "Abhiram"
c = t"Hello {a}"
print(c)
# Template(strings=('Hello ', ''), interpolations=(Interpolation('Abhiram', 'a', None, ''),))
So, why does this matter? Surely f-strings were enough?
a = "Abhiram"
c = f"Hello {a}"
print(c)
# Hello Abhiram
This had pretty much the same effect. Printing the t-string needs this additional formatting -
from string.templatelib import Template
def render_plain(template: Template) -> str:
parts = []
# interleave strings and interpolation values
for literal, value in zip(template.strings, template.values + ("",)):
parts.append(literal)
parts.append(str(value))
return "".join(parts)
print(render_plain(c))
# Hello Abhiram
Now, why would I go through this additional work when there’s a perfectly good f-string sitting in the barn?
The reason comes from the very motivation for creating t-strings.
Classic SQL injection:
Your app asks: “Enter your user ID”
A malicious person types:
1; DROP TABLE users
If you naïvely write:
query = f"SELECT * FROM users WHERE id = {user_id}"
they control your database. This is exactly what happened in many famous breaches (e.g. early 2000s PHP forums, login forms).
Until now, Python said:
“You, the programmer, must remember to escape alll sequences yourself.”
But we are fallible. Frameworks like Django, SQLAlchemy, logging libraries etc. had to reinvent their own templating syntaxes ({{ name }}, %s, etc.) just to protect developers.
t-strings move this responsibility into the language:
They give libraries the chance to auto-sanitize by default.
They make unsafe string building harder by design.
The usage of this as a commonplace practice is going to take a while to be adopted and is likely going to be in niche cases as required. But this is a great first step in the Python ecosystem to be supported natively.
Thanks for reading this edition of Everything Python! Subscribe for free to receive new posts and support my work.
Also check out my Youtube channel and Subscribe. I hope to create more videos on all things Engineering - From coding in Python to Databases and GenAI !