HyperAIHyperAI

Command Palette

Search for a command to run...

**Python 3.14 to Introduce T-Strings: Enhancing Safety and Flexibility in String Processing**

Template strings, also known as t-strings, have been officially accepted as a feature in Python 3.14, which is due to ship in late 2025. This new feature promises to bring safer and more flexible string processing to the Python programming language. ### What's the Big Idea with T-Strings? Since their introduction in Python 3.6, f-strings have become a favorite among developers for their simplicity, readability, and power. However, they are often misused in scenarios involving user input, such as in SQL queries and HTML generation. For instance, an f-string like `f"SELECT * FROM users WHERE name = '{user_name}'"` can be vulnerable to SQL injection if `user_name` contains malicious data. Similarly, `f"<div>{user_name}</div>"` can lead to cross-site scripting (XSS) attacks if `user_name` includes harmful HTML. To address these issues, t-strings generalize the concept of f-strings. Instead of immediately evaluating to a string, t-strings create a `Template` object, which needs to be processed before use. This intermediate step allows developers or libraries to safely escape or manipulate dynamic content, ensuring security and flexibility. ### How Do T-Strings Work? To use t-strings, you import the `Template` class from the `string.templatelib` module: ```python from string.templatelib import Template name = "World" template: Template = t"Hello {name}!" ``` Importantly, `Template` objects are not strings and do not provide a `__str__()` method. Therefore, you cannot directly convert a `Template` object to a string. Instead, you must process the template, for example, using a library function that safely escapes or formats the dynamic content. For instance, a library could provide an `html()` function that takes a `Template` object and returns a safely escaped string: ```python 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>" ``` T-strings also support more complex string processing. The `html()` function could return a new type, such as `HTMLElement`, which can handle various substitutions: ```python attributes = {"src": "roquefort.jpg", "alt": "Yum"} template = t"<img {attributes} />" element = html(template) assert str(element) == "<img src='roquefort.jpg' alt='Yum' />" ``` ### Working with T-Strings T-strings provide access to their components before they are combined into a final string. The `strings` and `values` properties return tuples of the static strings and dynamic values, respectively: ```python name = "World" template = t"Hello {name}!" assert template.strings == ("Hello ", "!") assert template.values == (name,) ``` You can also iterate over a `Template` object to process each component individually: ```python name = "World" template = t"Hello {name}!" contents = list(template) assert contents[0] == "Hello " assert contents[1].value == name assert contents[2] == "!" ``` For more advanced use cases, developers can access detailed information about each interpolation, including the value, expression, conversion, and format specification: ```python name = "World" template = t"Hello {name!s:>8}!" assert template.interpolations[0].value == name assert template.interpolations[0].expression == "name" assert template.interpolations[0].conversion == "s" assert template.interpolations[0].format_spec == ">8" ``` T-strings can be instantiated directly, allowing for precise control over the order and format of static and dynamic content: ```python from string.templatelib import Template, Interpolation template = Template( "Hello ", Interpolation(value="World", expression="name"), "!" ) ``` ### Example: Pig Latin Conversion with T-Strings To illustrate the flexibility of t-strings, consider a function that converts substituted words into pig latin: ```python def pig_latin(template: Template) -> str: """Convert a Template to pig latin.""" result = [] for item in template: if isinstance(item, str): result.append(item) else: word = item.value if word and word[0] in "aeiou": result.append(word + "yay") else: result.append(word[1:] + word[0] + "ay") return "".join(result) name = "world" template = t"Hello {name}!" assert pig_latin(template) == "Hello orldway!" ``` While this example is simple and somewhat whimsical, it demonstrates the potential for t-strings to handle a wide range of string processing tasks securely and efficiently. ### What's Next Once T-Strings Ship? The introduction of t-strings is a significant step forward for Python, especially in applications that handle user input. Developers can expect to see t-strings integrated into various libraries and frameworks, enhancing security and flexibility. For example, web frameworks could use t-strings to generate safe HTML, and database libraries could leverage them to construct secure SQL queries. Moreover, the broader Python ecosystem is likely to adapt to support t-strings. Tools like Black and Ruff may include features to format t-string contents, and IDEs such as Visual Studio Code could provide syntax highlighting and autocomplete for common t-string use cases, such as HTML and SQL. ### Evaluation by Industry Insiders and Company Profiles Industry experts are excited about the potential of t-strings. They see this feature as a game changer for Python's string processing capabilities, particularly in mitigating security risks associated with dynamic content. The Python community, known for its collaborative spirit, has been instrumental in shaping PEP 750, the proposal for t-strings. Contributions from key figures like Jim, Paul, Koudai, Lysandros, and Guido van Rossum, the creator of Python, have been pivotal in bringing this feature to life. As t-strings become available, the community continues to play a crucial role in developing best practices and integrating this feature into existing and new projects.

Related Links

Hacker NewsHacker News