Python's new t-strings

https://news.ycombinator.com/rss Hits: 17
Summary

Template strings, also known as t-strings, have been officially accepted as a feature in Python 3.14, which will ship in late 2025. 🎉 I’m excited; t-strings open the door to safer more flexible string processing in Python. What’s the big idea with t-strings? Since they were introduced in Python 3.6, f-strings have become a very popular way to format strings. They are concise, readable, and powerful. In fact, they’re so delightful that many developers use f-strings for everything… even when they shouldn’t! Alas, f-strings are often dangerously (mis)used to format strings that contain user input. I’ve seen f-strings used for SQL (f"SELECT * FROM users WHERE name = '{user_name}'") and for HTML (f"<div>{user_name}</div>"). These are not safe! If user_name contains a malicious value, it can lead to SQL injection or cross-site scripting. Template strings are a generalization of Python’s f-strings. Whereas f-strings immediately become a string, t-strings evaluate to a new type, string.templatelib.Template: from string.templatelib import Template name = "World" template: Template = t"Hello {name}!" Importantly, Template instances are not strings. The Template type does not provide its own __str__() implementation, which is to say that calling str(my_template) does not return a useful value. Templates must be processed before they can be used; that processing code can be written by the developer or provided by a library and can safely escape the dynamic content. We can imagine a library that provides an html() function that takes a Template and returns a safely escaped string: evil = "<script>alert('bad')</script>" template = t"<p>{evil}</p>" safe = html(template) assert safe == "<p>&lt;script&gt;alert('bad')&lt;/script&gt;</p>" Of course, t-strings are useful for more than just safety; they also allow for more flexible string processing. For example, that html() function could return a new type, HTMLElement. It could also accept all sorts of useful substitutions in the HTML...

First seen: 2025-04-21 07:34

Last seen: 2025-04-21 23:39