archive2025

Python 3.14 template strings and lazy annotations, tried on real code

Two Python 3.14 changes that affect everyday code: t-strings for safe string building, and annotations that are evaluated only when needed. Small examples and what to check before upgrading.

4 min read#dev#python

Most of the news about Python 3.14.0, released on 7 October 2025, is about the free-threaded build, which is now officially supported (PEP 779) but still a separate build. That needs its own test. In normal code I will meet two smaller changes first: template strings and lazy annotations.

I installed it next to my other versions with:

uv python install 3.14
uv run --python 3.14 python -c "import sys; print(sys.version)"

Template strings (PEP 750)

A t-string looks like an f-string with a t prefix. The difference: it does not produce a str. It produces a Template object that keeps the static parts and the interpolated values separate. Your code decides how to combine them.

This is useful when values must be escaped or passed separately, for example in SQL. My sensor scripts have a few hand-written SQLite queries. With a small helper:

import sqlite3
from string.templatelib import Template, Interpolation

def sql(t: Template) -> tuple[str, list]:
    parts, params = [], []
    for item in t:
        if isinstance(item, Interpolation):
            parts.append("?")
            params.append(item.value)
        else:
            parts.append(item)
    return "".join(parts), params

sensor = "garage"
since = "2025-10-01T00:00:00"
query, params = sql(t"SELECT ts, value FROM readings WHERE sensor = {sensor} AND ts >= {since}")
# query  -> "SELECT ts, value FROM readings WHERE sensor = ? AND ts >= ?"
# params -> ["garage", "2025-10-01T00:00:00"]

rows = sqlite3.connect("sensors.db").execute(query, params).fetchall()

The call site reads like an f-string, but the values never become part of the SQL text. With an f-string, the same line would be an SQL injection risk.

Some notes:

  • A Template is not a str. It has no string methods, and passing it to an API that checks for str (like execute()) raises a TypeError. Be careful with str(template) and logging, though. That gives the repr, Template(strings=(...), interpolations=(...)), not the rendered text, and no error.
  • Each Interpolation has value, expression (the source text, like "sensor"), conversion and format_spec. So a logging or HTML library can use all of them.
  • Libraries need to add support. Until database drivers and template libraries accept Template, you write small helpers like the one above. I would not build a large helper library myself. I will wait and see what the common libraries do.

Deferred evaluation of annotations (PEP 649 and PEP 749)

In 3.14, annotations are not evaluated when a function or class is defined. They are evaluated later, when someone asks for them. In practice, forward references work without quotes:

from dataclasses import dataclass

@dataclass
class Sensor:
    name: str
    last: Reading | None = None   # Reading is defined below; no quotes needed in 3.14

@dataclass
class Reading:
    ts: str
    value: float

On 3.13 this fails with NameError at class definition, unless you write "Reading" in quotes or use from __future__ import annotations.

To read annotations safely in tools, there is a new module, annotationlib:

import annotationlib

def f(x: UndefinedType) -> None: ...

print(annotationlib.get_annotations(f, format=annotationlib.Format.FORWARDREF))
# {'x': ForwardRef('UndefinedType', owner=<function f at 0x...>), 'return': None}

Accessing f.__annotations__ directly would raise NameError here, because UndefinedType does not exist.

What to check before upgrading:

  • Code that reads __annotations__ directly, for example custom validation or dependency injection code. It may now raise errors at a different time than before. Use annotationlib.get_annotations() or inspect.get_annotations().
  • from __future__ import annotations still works and still turns annotations into strings. You can keep it for now. I plan to remove it only when a project no longer supports 3.13.
  • Pydantic, FastAPI, dataclasses and similar libraries read annotations at runtime. Upgrade them to versions that list 3.14 support before you upgrade Python.

Other things I noticed

  • compression.zstd is in the standard library now (PEP 784). I use zstd for log archives, so one less dependency.
  • concurrent.interpreters (PEP 734) gives access to subinterpreters from Python code. I have not found a use for it yet.

For my own projects, the upgrade plan is short: run the tests on 3.14 in CI next to 3.13, upgrade the libraries that fail, and switch the Docker base image when everything is green. I will not use t-strings in shared code until the projects drop 3.13, because a t-string is a syntax error on older versions.