Lesson 47 of 52Real projects
What Changed in Python 3.11 to 3.15
Know what each recent Python release added and removed, read code written for any of them, and upgrade a real project without surprises.
Your first ticket at a new job says "Upgrade the billing service from Python 3.11 to 3.14". The repo has from __future__ import annotations at the top of every file, TypeVar declarations everywhere, a datetime.utcnow() in the invoice code, and a CI job that has been green for two years. Meanwhile a library you want needs 3.12, and a colleague's pull request uses except A, B: without brackets, which will not even parse on 3.13. Python changes every October, and working engineers are expected to know what each release brought, which old idioms are now legacy, and how to move a codebase forward safely. This lesson is that map, release by release, ending with the upgrade checklist teams actually use.
The release cycle and support windows
Since 3.9, CPython ships one feature release every October (PEP 602). Each release gets roughly two years of bugfix releases (3.14.1, 3.14.2 and so on), then security-only fixes as source releases until five years after launch, then end of life: no fixes at all, even for serious vulnerabilities.
As of late October 2026, according to the Python developer guide:
3.10
End of life (2026-10-01)
No more fixes of any kind. Anything still on 3.10 should be upgraded now. Many libraries are dropping it too.
3.11
Security fixes only
Released October 2022. Security releases until about October 2027.
3.12
Security fixes only
Released October 2023. Security releases until about October 2028.
3.13
Security fixes only
Released October 2024. Moved to security-only in October 2026, ends about October 2029.
3.14
Bugfix
Released October 2025. Full bugfix releases, a sensible default for production today.
3.15
Bugfix (newest)
Released 9 October 2026. Wait for your key libraries to publish wheels before moving production to it.
3.16
In development
Planned for October 2027. Its alpha and beta releases are for testing only.
What this means at work:
requires-pythoninpyproject.toml(you met it in Project Structure and uv) is a promise. An application can set it to the one version it deploys on. A library usually supports every non-EOL version, so in late 2026 that means>=3.11, and drops each version shortly after it reaches end of life.- Upgrade every year or two, not every five. Jumping one release at a time is easy; jumping four at once means fixing four years of deprecations in one go.
3.11: faster, with better errors and exception groups
Speed. The Faster CPython project made 3.11 noticeably faster with no code changes, thanks to a specialising interpreter that adapts bytecode to the types it actually sees. The release notes report around 25% on the standard benchmark suite; your own code may gain more or less. This release made "just upgrade" a real performance strategy.
Fine-grained error locations. Tracebacks point at the exact expression that failed with ^^^^ markers, so user["profile"]["email"] tells you which subscript was None.
Exception groups and except*. When several things fail at once, such as tasks in an asyncio.TaskGroup (also new in 3.11, covered in Async and Await), you need to raise all the errors, not just the first. ExceptionGroup bundles them, and except* handles each type inside the group separately. add_note() attaches extra context to any exception without wrapping it.
Also in 3.11: tomllib for reading TOML (read only; writing needs a third-party library), typing.Self, StrEnum (see Enums), datetime.UTC, and typing.assert_never.
Press Run (⌘ Enter) to see what happens.Notice that both except* clauses ran. With a normal except, only the first matching clause runs. With except*, each clause takes the matching part of the group, and anything left unhandled is re-raised as a smaller group.
What does this print?
try:
raise ExceptionGroup("batch", [
KeyError("a"), ValueError("b"), KeyError("c"),
])
except* KeyError as eg:
print("keys", len(eg.exceptions))
except* ValueError as eg:
print("values", len(eg.exceptions))3.12: new type syntax and freer f-strings
PEP 695 type parameter syntax. Generics no longer need module-level TypeVar objects. You write def first[T](items: list[T]) -> T and class Repo[T], and a type statement declares an alias that is evaluated lazily. Type Hints showed the basics; the point here is reading old code: T = TypeVar("T") at the top of a file is the pre-3.12 spelling of the same thing.
PEP 701 f-strings. The f-string grammar became part of the real parser. You can reuse the same quote type inside the braces, write multi-line expressions and add comments inside them. Before 3.12, f"{user["name"]}" was a syntax error.
typing.override marks a method that is meant to override a parent's. If someone renames the parent method, the type checker flags the orphan.
Also in 3.12: itertools.batched, much better error suggestions, and per-interpreter GILs at the C level (the foundation for 3.14's interpreters module). Removed: distutils, so old setup.py files that import it need setuptools. Deprecated: datetime.utcnow() and utcfromtimestamp(), because they return naive datetimes that silently lose the time zone. Use datetime.now(datetime.UTC).
Press Run (⌘ Enter) to see what happens.3.13: a new REPL, and experiments under the hood
A new interactive shell, based on PyPy's, with colour, multi-line editing and history that keeps whole blocks. Set PYTHON_BASIC_REPL to get the old one back.
The free-threaded build (PEP 703) arrived as an experimental, separate build, usually installed as python3.13t, with the GIL disabled. An experimental JIT (PEP 744) also landed, off by default and only present if CPython is built with it. Neither changes the normal python3.13 you install. Threads and the GIL covers what free-threading means for your code.
Typing: TypeIs for user-defined narrowing functions (preferred over TypeGuard in most cases), ReadOnly for TypedDict items, and defaults for type parameters (PEP 696). Advanced Typing Patterns goes deeper.
@warnings.deprecated (PEP 702) marks a function or class as deprecated for type checkers and emits a DeprecationWarning when it is called. copy.replace() makes a modified copy of a frozen dataclass, named tuple or any class with __replace__.
locals() got defined semantics (PEP 667): inside a function it now returns an independent snapshot, which matters if old code relied on writing to it.
Dead batteries removed (PEP 594): 19 old modules are gone, including cgi, cgitb, telnetlib, crypt, imghdr, pipes, nntplib and uu. An upgrade from 3.12 that fails with ModuleNotFoundError: No module named 'cgi' is this. The PEP lists replacements for each.
Press Run (⌘ Enter) to see what happens.3.14: deferred annotations, template strings, free-threading supported
3.14 is the release you are most likely to run in production in late 2026, and it changes several things you will notice in everyday code.
Deferred evaluation of annotations (PEP 649 and PEP 749). Annotations are no longer evaluated when a function or class is defined. Python stores a small function that computes them, and runs it only when someone asks. Forward references just work without quotes, and importing a module no longer pays for evaluating every annotation. The new annotationlib module reads them in different formats: real values, strings, or values with unresolved names left as forward references. This makes from __future__ import annotations legacy: it is now deprecated, still behaves as before in 3.14, and will not be removed until after 3.13 reaches end of life in 2029. New code should drop it; remove it from old code when you are sure all supported versions are 3.14 or newer.
Template strings (PEP 750). A t"..." literal looks like an f-string but produces a string.templatelib.Template, not a str. It keeps the static text and the interpolated values separate, so a library can escape values for HTML, quote them for SQL or structure them for logs before joining. It is a building block for safer APIs, not a replacement for f-strings.
except without brackets (PEP 758). except TimeoutError, ConnectionError: is now legal, but only when there is no as clause. With as, you still need the brackets.
return, break or continue leaving a finally block now raises a SyntaxWarning (PEP 765), because they silently swallow the exception being propagated.
Press Run (⌘ Enter) to see what happens.Concurrency. Free-threaded Python is now officially supported (PEP 779), but it is still an optional, separate build, not the default. concurrent.interpreters (PEP 734) exposes multiple interpreters in one process, each with its own GIL, and concurrent.futures.InterpreterPoolExecutor uses them. On Unix platforms other than macOS, the default multiprocessing start method changed from fork to forkserver. That is the 3.14 upgrade change most likely to break real code: programs that relied on children inheriting module globals now see NameErrors or pickling errors. Multiprocessing and Free-threading covers the fix.
Batteries. compression.zstd adds Zstandard (PEP 784), and tarfile, zipfile and shutil understand it. uuid gains uuid6(), uuid7() and uuid8(). pathlib.Path gains copy(), copy_into(), move() and move_into(). asyncio.get_event_loop() now raises RuntimeError when there is no current event loop instead of creating one; use asyncio.run().
Debugging live processes. python -m pdb -p PID attaches the debugger to a running process (PEP 768), and python -m asyncio ps PID or pstree PID shows what every task in a running asyncio program is waiting on. Both are a big deal for diagnosing a stuck production worker.
from compression import zstd
from pathlib import Path
blob = zstd.compress(b"log line\n" * 10_000)
Path("report.csv").copy("backup/report.csv") # 3.14+
from concurrent.futures import InterpreterPoolExecutor
with InterpreterPoolExecutor() as pool: # one interpreter per worker
print(list(pool.map(pow, [2, 3], [10, 10])))t"Hello {name}" evaluate to?3.15: lazy imports, UTF-8 everywhere, frozendict
3.15 was released on 9 October 2026. Its headline changes are below; this new syntax does not run on 3.14, so these examples are not runnable here.
Explicit lazy imports (PEP 810). lazy is a soft keyword: lazy import json binds a lightweight proxy and only loads the module the first time the name is used. CLIs and serverless functions that import heavy libraries but use only some of them on each run start much faster. A failing import now raises at first use, and the traceback shows both places. Lazy imports are allowed only at module level, and not inside try blocks, functions or class bodies, or with *. Code that must also run on older versions can list module names in __lazy_modules__ instead. -X lazy_imports=all (or PYTHON_LAZY_IMPORTS) makes every import lazy for experiments.
UTF-8 by default (PEP 686). open("notes.txt") without an encoding now uses UTF-8 everywhere, regardless of the system locale. On Linux and macOS this rarely changes anything. On Windows, where the default used to be the legacy code page, scripts that read local files without an explicit encoding can change behaviour. Opt out with PYTHONUTF8=0 or -X utf8=0. The best habit is unchanged: pass encoding= explicitly for files that matter.
Unpacking in comprehensions (PEP 798): [*row for row in rows] flattens one level, and {**d for d in dicts} merges dicts.
frozendict (PEP 814) is a new built-in immutable mapping. It is hashable when its contents are, keeps insertion order, and is not a subclass of dict, so code that checks isinstance(x, dict) will not accept it; check against collections.abc.Mapping instead. A built-in sentinel type (PEP 661) also arrives, for unique marker values such as "argument not passed"; check the docs for its exact constructor before using it.
Profiling (PEP 799). A new profiling package holds profiling.tracing (the deterministic profiler formerly known as cProfile, which remains as an alias) and profiling.sampling, a low-overhead sampling profiler called Tachyon that can attach to a running process and write flame graphs. The old pure-Python profile module is deprecated, for removal in 3.17. Profiling Python covers how to use them.
Typing: TypedDict can be closed or declare typed extra_items (PEP 728), and TypeForm (PEP 747) lets a function accept a type expression like int | None as a value with a precise type. re.prefixmatch() is added as a clearer name for re.match(), which is now soft deprecated: it is not going away, but new code can say what it means.
Free-threading: still not the default build. 3.15 adds a stable ABI for free-threaded builds (abi3t, PEP 803), so extension authors can publish one wheel for several versions, and the official macOS installer now installs free-threading support by default alongside the normal interpreter. The experimental JIT was significantly upgraded but remains experimental.
lazy import json
lazy from pathlib import Path
nested = [[1, 2], [3], [4, 5]]
flat = [*row for row in nested] # [1, 2, 3, 4, 5]
merged = {**d for d in ({"a": 1}, {"b": 2})} # {'a': 1, 'b': 2}
DEFAULTS = frozendict(region="eu-west-2", retries=3)
cache = {DEFAULTS: "ok"} # hashable, so usable as a key
def main() -> None:
data = json.loads(Path("config.json").read_text()) # json loads hereMatch each feature to the release that introduced it.
Upgrading a real project safely
Back to the billing service. A version upgrade is a small project with a known shape. Do it the same way every time.
1. Read the "Porting to" section of each What's New page you are crossing, and check that your key dependencies publish wheels for the target version. Free-threaded wheels have their own tags (cp314t), so check those separately if you plan to try that build.
2. Make deprecations loud on the current version before changing anything. Deprecation warnings are hidden by default outside __main__ and tests, so turn them into errors in your test run and fix what breaks. pytest also accepts this in its filterwarnings setting.
python -W error::DeprecationWarning -m pytest3. Add the new version to CI alongside the old one, so both are tested on every pull request.
jobs:
test:
runs-on: ubuntu-latest
strategy:
matrix:
python: ["3.11", "3.14"]
steps:
- uses: actions/checkout@v5
- uses: astral-sh/setup-uv@v6
- run: uv run --python ${{ matrix.python }} pytest -W error::DeprecationWarningCheck the current major versions of these actions before copying them; they move faster than Python does.
4. Switch the runtime: bump .python-version, the Docker base image and requires-python, then deploy to a staging environment and watch memory, latency and error rates. The forkserver change, UTF-8 by default and removed modules show up here rather than in unit tests.
5. Modernise the syntax, as a separate pull request so reviewers can tell refactors from behaviour changes. Ruff's UP rules (from pyupgrade) rewrite old idioms automatically once you tell Ruff your minimum version: List[int] to list[int], Optional[X] to X | None, TypeVar declarations to PEP 695 syntax, and more.
[project]
requires-python = ">=3.14"
[tool.ruff]
target-version = "py314"
[tool.ruff.lint]
extend-select = ["UP"]ruff check --fix .Order the steps of a safe minor-version upgrade for a production service.
- Tap the steps below in the right order.
Supporting several versions at once
Libraries often support four or five versions at once, so they cannot use the newest syntax. Three techniques cover most cases.
Version checks with sys.version_info >= (3, 13) around imports or behaviour that changed. Type checkers understand these checks and analyse each branch for the right version.
typing_extensions backports new typing features (TypeIs, ReadOnly, override, deprecated, TypeVar defaults) to older versions, and the type checkers treat them exactly like the typing originals. Import from it until your minimum version has the feature.
Gradual adoption hooks that new features provide on purpose: __lazy_modules__ for lazy imports, from __future__ import annotations (still working, though deprecated) for code that also runs before 3.14, and typing.TYPE_CHECKING blocks for imports only needed by annotations.
Syntax is the hard limit. A file containing a t-string, except A, B: or lazy import fails to parse on older versions, so no runtime check can save it. Keep such syntax out of libraries until the oldest supported version understands it.
- PEP 602
- The annual release cycle: a new Python every October, about two years of bugfixes, then security fixes until five years.
- end of life (EOL)
- The point after which a Python version gets no fixes at all, including security fixes. 3.10 reached it on 2026-10-01.
- ExceptionGroup and except*
- A bundle of several exceptions raised together, and the clause that handles each type inside it separately (3.11).
- deferred annotations
- 3.14 behaviour where annotations are computed only when requested, read through
annotationlib. - template string
- A
t'...'literal (3.14) that produces aTemplatewith text and values kept separate, not astr. - lazy import
- A 3.15 import that binds a proxy and loads the module only when the name is first used.
- free-threaded build
- An optional CPython build without the GIL: experimental in 3.13, supported in 3.14, still not the default in 3.15.