Python 3.15 upgrade guide: what breaks, what's worth using, and how to measure it

A practical guide to what breaks, what's worth adopting, and how to measure lazy imports and the Tachyon profiler on your own code.

11 min read
AI-assisted

Author's AI disclosure

The author reports using AI to help with this article.

The author confirms reviewing this article.

Python 3.15 upgrade guide: what breaks, what's worth using, and how to measure it

Python 3.15.0 came out on October 9, 2026. If you're on 3.13 or 3.14, the upgrade is mostly painless, but a few changes can bite: a new default text encoding, a batch of long-deprecated APIs that are finally gone, and tighter behavior in sqlite3, argparse and unittest.

This guide follows the order I'd work through an upgrade. First what can break, then the features worth adopting, then two small experiments so you can see whether the performance work matters for your code.

Everything about what changed comes from the official What's new in Python 3.15 page, the profiling.sampling reference, PEP 686 and python.org's release pages. The timing scripts are templates, and there are no benchmark numbers in this post on purpose. Your app's import graph decides the result, so run them on your own code.

Before you upgrade

Use 3.15.2 or newer. As of December 1, 2026, python.org lists 3.15.2 (released October 25) as the latest 3.15 release. It was an expedited security release, with fixes in ssl, tarfile and http.cookiejar. It also fixes a regression that matters if you run threads: 3.15.0 introduced a problem where threads doing first-time import package.submodule imports at the same time could deadlock or hit spurious import errors.

Coming from 3.14.0 to 3.14.4? Those releases shipped a new incremental garbage collector. After reports of heavy memory pressure in production, it was reverted to the generational GC from 3.13. That's what 3.14.5 and later use, and it's what 3.15 uses. If you tuned anything around early 3.14 memory behavior, check it again.

UTF-8 is now the default encoding

Python now uses UTF-8 as the default encoding regardless of the system's environment (PEP 686). This only applies when you don't pass encoding=.

Before, a bare open() followed the machine's locale. PEP 686 points out that most Unix systems already use a UTF-8 locale, so this change mostly affects Windows users. Now it's UTF-8 everywhere, which is usually what you wanted, but any file you wrote in a legacy encoding without saying so will be read wrongly.

The fix is to say what you mean:

# Depends on the machine (or, in 3.15, quietly assumes UTF-8)
with open("notes.txt") as f:
    text = f.read()

# Explicit, same result on every Python version
with open("notes.txt", encoding="utf-8") as f:
    text = f.read()

To find the calls you missed, run your tests once with the opt-in encoding warning:

python -X warn_default_encoding -m pytest

If you need the old behavior back, set PYTHONUTF8=0 or pass -X utf8=0. For files that really are in the locale encoding, encoding="locale" says so explicitly and has worked since Python 3.10.

Removals that can break imports and calls

These were deprecated for a while and are now gone. The ones most likely to appear in real code:

If your code uses

In 3.15

Use instead

sre_compile, sre_constants, sre_parse

Modules removed

The public re API

Loader.load_module(), zipimporter.load_module()

Removed; the import system no longer calls load_module() on custom loaders

exec_module()

glob.glob0(), glob.glob1()

Removed

glob.glob() with root_dir=

NamedTuple("Point", x=int, y=int)

No longer supported

Class syntax, or the functional form with a list of pairs

TypedDict("TD") or TypedDict("TD", None)

No longer supported

TypedDict("TD", {}) or a class

datetime.strptime() with %d and no year

Raises ValueError

Include a year directive

AST node constructors with a missing required field or an unknown keyword

Raise TypeError (this was a DeprecationWarning since 3.13)

Pass every required field

http.server.CGIHTTPRequestHandler and --cgi

Removed

Nothing listed in the docs

The rest of the removals
  • ctypes.SetPointerType()

  • codeobject.co_lnotab (use co_lines())

  • pathlib.PurePath.is_reserved() (use os.path.isreserved())

  • platform.java_ver()

  • typing.no_type_check_decorator

  • wave marker methods: getmark(), setmark(), getmarkers()

  • The package parameter of importlib.resources.files()

  • sysconfig.is_python_build()'s check_home parameter

  • Arbitrary arguments to the C implementation of threading.RLock

  • collections.abc.ByteString and typing.ByteString are out of __all__. They still exist, but importing them now emits a DeprecationWarning, and removal is scheduled for 3.17. Use collections.abc.Buffer, or a union like bytes | bytearray | memoryview.

A quick way to find the usual suspects in your own code:

grep -rnE "sre_(compile|constants|parse)|load_module\(|glob\.glob[01]\(|CGIHTTPRequestHandler|co_lnotab|no_type_check_decorator|java_ver\(|is_reserved\(" --include="*.py" .

Don't rely on grep alone. Run your suite with deprecation warnings turned into errors, and what's about to break shows up as test failures: python -m pytest -W error::DeprecationWarning.

Behavior changes in the standard library

These won't fail at import time, but they can change results or start failing tests:

  • sqlite3: every parameter of sqlite3.connect() except database is now keyword-only. The first three parameters of create_function() and create_aggregate() are positional-only, and so is the first parameter of set_authorizer(), set_progress_handler() and set_trace_callback().

  • argparse: with add_argument('-f', '-foo'), dest is now inferred as foo, not f. Pass dest explicitly to keep the old name. Also, suggest_on_error now defaults to True.

  • base64.urlsafe_b64decode(): input no longer needs padding. Pass padded=True if you want padding required.

  • unittest: assertWarns() and assertWarnsRegex() no longer swallow warnings that don't match. Tests may start leaking warnings that used to be hidden.

  • xml.etree.ElementTree.iterparse(): an unclosed iterator that opened a file now triggers a resource warning. Close it, or wrap it in contextlib.closing().

  • importlib.metadata: a metadata directory with no metadata file now raises MetadataNotFound, where it used to return an empty PackageMetadata.

  • venv: on POSIX, platlib directories are created as real directories instead of a lib64 -> lib symlink, on platforms where sys.platlibdir isn't lib.

  • email: generators raise an error when a message can't be flattened accurately because of a non-ASCII mailbox in an address header.

  • __cached__: modules no longer get it set, and nothing in the import system or standard library reads it. Use __spec__.cached.

Deprecations to put on the calendar

Nothing here breaks today, but each has a removal date:

Version

What goes

3.16

The asyncio policy system (get_event_loop_policy() and friends), and asyncio.iscoroutinefunction(). Use asyncio.run(main(), loop_factory=...) and inspect.iscoroutinefunction().

3.17

The profile module (use profiling.tracing), ByteString, and webbrowser.MacOSXOSAScript. The -b and -bb flags become no-ops.

3.19

The string= keyword for hashlib constructors, http.cookies js_output(), altering IMAP4.file.

3.20

__version__, version and VERSION attributes in a long list of stdlib modules. Use sys.version_info.

re.match() is soft-deprecated in favor of the new re.prefixmatch(), but the docs say there's no plan to remove it. If you support older Pythons, keep using match().

What's worth adopting

Lazy imports (PEP 810)

Big applications pay for every import at startup, including modules most runs never touch. 3.15 adds a lazy soft keyword that defers loading until the name is first used:

lazy import json
lazy from pathlib import Path

print("Starting up...")  # neither module is fully imported yet

data = json.loads('{"key": "value"}')  # json loads here
p = Path(".")                          # pathlib loads here

The rules are strict:

  • lazy only works at module scope. Using it inside a function, a class body, or a try/except/finally block is a SyntaxError.

  • Star imports and from __future__ imports can't be lazy.

  • If the module doesn't exist, you find out at first use, not at import time. The traceback shows both where you used the name and the original import statement.

A lazy module runs its top-level code later. Anything that depends on import-time side effects, like registering plugins, patching things or filling a registry, will now happen at first use, or not at all if nothing touches the name.

You can also turn it on without editing source. -X lazy_imports=all (or the environment variable PYTHON_LAZY_IMPORTS=all) makes eligible module-scope imports lazy by default. The default value, normal, only honors the lazy keyword and __lazy_modules__. The restrictions apply in both modes.

If you still support older Pythons, __lazy_modules__ lets plain import statements be lazy on 3.15 and later:

__lazy_modules__ = ["json", "pathlib"]

import json     # lazy on 3.15+
import os       # still eager

For finer control, sys.set_lazy_imports_filter() takes a callable that decides per import. This keeps your own modules lazy and third-party ones eager:

import sys

def myapp_filter(importing, imported, fromlist):
    return imported.startswith("myapp.")

sys.set_lazy_imports_filter(myapp_filter)
sys.set_lazy_imports("all")

import myapp.slow_module  # lazy, matches the filter
import json               # eager, doesn't match

frozendict (PEP 814)

There's now an immutable mapping in builtins. It's hashable as long as its keys and values are, it keeps insertion order, and equality ignores order:

>>> a = frozendict(x=1, y=2)
>>> a['z'] = 3
TypeError: 'frozendict' object does not support item assignment
>>> b = frozendict(y=2, x=1)
>>> hash(a) == hash(b)
True
>>> a == b
True

One catch: frozendict is not a subclass of dict. Code that checks isinstance(x, dict) will say no. Check (dict, frozendict) instead, or collections.abc.Mapping if you want to accept other mapping types too.

json.load() and json.loads() also gained an array_hook parameter. Combine it with object_pairs_hook and you get a deeply immutable structure from parsed JSON:

import json

raw = '{"name": "demo", "ports": [80, 443]}'
config = json.loads(raw, object_pairs_hook=frozendict, array_hook=tuple)

Unpacking in comprehensions (PEP 798)

* and ** now work inside comprehensions and generator expressions, as a replacement for nested loops and itertools.chain:

lists = [[1, 2], [3, 4], [5]]
flat = [*items for items in lists]            # [1, 2, 3, 4, 5]

dicts = [{"a": 1}, {"b": 2}, {"a": 3}]
merged = {**d for d in dicts}                 # {'a': 3, 'b': 2}

Later keys win, same as with {**a, **b}.

Smaller things worth knowing

  • A new sentinel builtin (PEP 661) for unique placeholder values with a readable repr.

  • Better AttributeError hints. [1, 2, 3].push(4) now suggests .append, and a missing attribute that exists one level down suggests the full path, like .inner.area.

  • bytearray.take_bytes() hands over the buffer's contents without a copy.

  • asyncio.TaskGroup.cancel() ends a task group early, without the old trick of raising a throwaway exception from an extra task.

  • tomllib now reads TOML 1.1.0, including multi-line inline tables with trailing commas.

  • re.prefixmatch() is a clearer name for what re.match() does.

  • PEP 829 adds .start files for startup code, a more auditable alternative to import lines in .pth files. Those lines are now silently deprecated.

The interpreter itself

The experimental JIT got a large upgrade. The docs report a 7 to 8% geometric-mean improvement over the standard interpreter on x86-64 Linux, and 11 to 12% over the tail-calling interpreter on AArch64 macOS. Against builds with no JIT, individual benchmarks range from roughly a 15% slowdown to more than a 100% speedup. It's still experimental and needs a JIT-enabled build, so treat those numbers as a reason to test, not a reason to switch.

The official Windows 64-bit binaries now use the tail-calling interpreter. The docs cite 15 to 20% on the pyperformance geometric mean on one test machine. On macOS, the official binaries now install free-threading support by default.

For extension authors

Two changes affect anyone shipping C extensions:

  1. Frame pointers are on by default (PEP 831). CPython builds with -fno-omit-frame-pointer and -mno-omit-leaf-frame-pointer, which makes native stack unwinding faster and more reliable for system profilers, debuggers and eBPF tools. The flags are exposed through sysconfig, so extensions built from Python's config inherit them. If you use a custom build system, keep those flags. The docs warn that a single native component built without frame pointers can break unwinding for the whole process. Builders can opt out with --without-frame-pointers.

  2. A stable ABI for free-threaded builds, called abi3t (PEP 803). Extensions that target the stable ABI can now build for free-threaded CPython, but it usually takes real source changes: moving to the PEP 697 type-data API and replacing PyInit_ with the new PyModExport_* hook. meson-python, scikit-build-core and Maturin support it. If you can't switch, keep building abi3 and cp315t separately.

Experiment 1: does lazy loading help your startup time?

You don't have to touch your code to find out. -X lazy_imports=all flips the default, so a quick comparison shows how much startup time is lazy-import-shaped.

Save this as bench_startup.py:

import statistics
import subprocess
import sys
import time


def time_runs(cmd, runs=20):
    subprocess.run(cmd, check=True, capture_output=True)  # warm-up, not counted
    samples = []
    for _ in range(runs):
        start = time.perf_counter()
        subprocess.run(cmd, check=True, capture_output=True)
        samples.append((time.perf_counter() - start) * 1000)
    return samples


def report(label, samples):
    print(
        f"{label:<22} median {statistics.median(samples):7.1f} ms"
        f"   min {min(samples):7.1f} ms   max {max(samples):7.1f} ms"
    )


if __name__ == "__main__":
    module = sys.argv[1]  # the module your app imports at startup, e.g. myapp.cli
    code = f"import {module}"

    report("normal imports", time_runs([sys.executable, "-c", code]))
    report("lazy_imports=all", time_runs([sys.executable, "-X", "lazy_imports=all", "-c", code]))

Run it with a 3.15 interpreter against whatever your app imports first:

python3.15 bench_startup.py myapp.cli

If the two medians are close, lazy imports won't buy you much, and you can stop here. If they're far apart, find out which imports are expensive:

python3.15 -X importtime -c "import myapp.cli" 2> imports.txt
sort -t'|' -k2 -n -r imports.txt | head -20

The second column is cumulative time in microseconds, so the heaviest imports float to the top. Mark those with lazy, rerun the benchmark without the -X flag, and compare.

Two things to keep in mind. -X lazy_imports=all is a blunt experiment, not a deployment plan, because it makes everything eligible lazy, including code you haven't checked for import-time side effects. And a python -c "import ..." run measures import cost, not your app's first request. Measure both if startup matters to you.

Experiment 2: profile a running process with Tachyon

3.15 adds a profiling package. profiling.tracing is the deterministic profiler, relocated from cProfile, which stays as an alias. profiling.sampling is new: a statistical sampling profiler named Tachyon. It samples stack traces from a live process, so it doesn't need code changes or a restart. The docs describe it as near-zero overhead, with sampling rates up to 1,000,000 Hz.

The profiler reads another process's memory, so attaching needs permissions. On Linux that means root, CAP_SYS_PTRACE, or loosening Yama's ptrace_scope (the default of 1 restricts ptrace to parent processes). On macOS it means root or a debugger entitlement, and on Windows administrator rights. The profiler and its target must also run the same Python minor version, and a free-threaded build can't attach to a standard build or the other way around.

The command form is python -m profiling.sampling <subcommand> [options] ..., with options before the target. The examples below follow the profiling.sampling reference page.

Targets, as listed in the docs:

  • attach: profile an already-running process by PID

  • run: run and profile a script from the start

  • run -m: do the same for a module

  • dump: print a one-shot stack for every thread, or every asyncio task with --async-aware, which helps with hung processes

  • replay: convert a saved binary profile (made with --binary) into another output format

Modes decide what gets measured: --mode wall (the default) counts real elapsed time including I/O and sleeps, --mode cpu counts only active CPU time, --mode gil counts time spent holding the GIL, and --mode exception samples only threads with an active exception. Output formats include --pstats (the default, a text table), --collapsed for flame-graph tools, --flamegraph (a self-contained interactive HTML file), --gecko for the Firefox Profiler, --heatmap for line-level counts, and --binary for saving a profile to replay later. -o sets the output path. --live gives a terminal view, but it needs curses, so it doesn't work on Windows. Sampling defaults to 1 kHz (-r changes it), runs until the target finishes unless you set -d, and only looks at the main thread unless you pass -a.

The wall versus CPU difference is the quickest way to see what the profiler is telling you. Save this as busy.py:

import time


def spin(n):
    total = 0
    for i in range(n):
        total += i * i
    return total


def nap():
    time.sleep(0.2)


for _ in range(20):
    spin(3_000_000)
    nap()

Then profile it both ways:

# wall-clock (the default): nap() should look huge, because sleeping is time
python3.15 -m profiling.sampling run busy.py

# CPU time: the sleeps drop out and spin() takes over
python3.15 -m profiling.sampling run --mode=cpu busy.py

# the same profile as an interactive flame graph
python3.15 -m profiling.sampling run --flamegraph -o profile.html busy.py

# a process that's already running (replace 12345 with its PID)
python3.15 -m profiling.sampling attach 12345
python3.15 -m profiling.sampling dump 12345

If both modes give you the same picture on real code, your process is CPU-bound. If wall time is dominated by something CPU mode barely sees, you're waiting on I/O, locks or sleeps, and optimizing the Python won't help. The same split matters for services in production, which is where attaching without a restart pays off.

Upgrade checklist

  • CI runs on Python 3.15.2 or newer

  • Tests pass with -W error::DeprecationWarning

  • Ran once with -X warn_default_encoding and fixed every bare open() that mattered

  • Searched for removed APIs: sre_*, load_module(), glob0/glob1, NamedTuple keyword syntax, strptime with %d and no year

  • Reviewed sqlite3.connect() calls and argparse options with a short and a single-dash long name

  • Rebuilt C extensions and confirmed your dependencies publish 3.15 wheels

  • Measured startup with and without -X lazy_imports=all, and decided whether any lazy imports are worth adding

  • Tried Tachyon on one real workload

For the full list of changes, including the module-by-module details this guide skips, read What's new in Python 3.15.

Comments0

Log in to join the discussion.

No comments yet.

Pushpum Vats

Read articles by this author.

Subscribe to Pushpum Vats's newsletter

Get the articles this author chooses to send by email.