Python 3.15 was released on 9 October 2026, and its headline changes are explicit lazy imports (lazy import json), two new builtins (frozendict and sentinel), UTF-8 as the default text encoding on every platform, and a new profiling package that ships a sampling profiler called Tachyon. It also removes a batch of APIs that were deprecated in 3.13 and earlier, so most upgrades are smooth but not free. This guide walks through each feature with working code, then gives you a checklist for moving a real project to 3.15.
All behavior described here comes from the official What's New in Python 3.15 page and the accepted PEPs it links to. The final release was originally planned for 1 October in PEP 790, but slipped a week; the python.org release page lists 9 October 2026.
Python 3.15 at a glance
| Feature | PEP | What it gives you |
|---|---|---|
| Explicit lazy imports | PEP 810 | lazy import x defers loading a module until first use |
frozendict builtin |
PEP 814 | An immutable, hashable mapping |
sentinel builtin |
PEP 661 | Unique marker values with a clean repr, usable in type hints |
| Unpacking in comprehensions | PEP 798 | [*it for it in its] and {**d for d in dicts} |
| UTF-8 by default | PEP 686 | open() without encoding= uses UTF-8 everywhere |
profiling package + Tachyon |
PEP 799 | Attach a sampling profiler to a running process by PID |
| Stable ABI for free-threaded builds | PEP 803 / 793 / 820 | C extensions can ship one abi3t wheel for free-threaded Python |
math.integer module |
PEP 791 | Integer-specific math functions in their own namespace |
| Upgraded experimental JIT | — | Still off by default, but substantially reworked |
Explicit lazy imports (PEP 810)
Startup time is the most common complaint about large Python CLIs and serverless functions. A tool that imports pandas, boto3, and requests at module top level pays for all three even when the user just runs --help. Until now the fix was to move imports inside functions, which hurts readability and type checking.
Python 3.15 adds a lazy soft keyword:
lazy import json
lazy from pathlib import Path
print("Starting up...") # json and pathlib are not fully imported yet
data = json.loads('{"key": "value"}') # json gets fully imported here
p = Path(".") # pathlib gets fully imported here
A lazy import binds the name to a lightweight proxy. The real import runs the first time the name is used. If the import fails, the exception is raised at that first use, and the traceback shows both the access site and the original lazy import line, so debugging is not as painful as it sounds.
Rules you need to know
lazyis only allowed at module scope. Using it inside a function, class body, ortry/except/finallyblock is aSyntaxError.lazy from module import *andlazy from __future__ import ...are bothSyntaxError.- Because
lazyis a soft keyword, existing variables or functions namedlazykeep working.
Turning laziness on globally
You can switch the whole process with -X lazy_imports=all or the PYTHON_LAZY_IMPORTS environment variable (all or normal; normal is the default and respects only explicit lazy statements). For finer control there is a runtime filter API in sys:
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 filter)
import json # eager (does not match filter)
sys.get_lazy_imports() returns the current mode, and types.LazyImportType lets you detect a not-yet-loaded proxy if a framework needs to.
Supporting 3.14 and 3.15 in the same codebase
The lazy keyword is a syntax error on older interpreters, so libraries that support several versions cannot use it directly. PEP 810 adds a compatible escape hatch: define __lazy_modules__ at module top level. On 3.15 the listed modules are imported lazily; older versions simply ignore the variable and import eagerly.
__lazy_modules__ = ["json", "pathlib"]
import json # lazy
import os # still eager
To find which imports are worth deferring, measure first with the long-standing -X importtime flag:
python3.15 -X importtime -c "import myapp.cli" 2> importtime.log
sort -t '|' -k2 -n importtime.log | tail -20
Side-effect imports (modules that register plugins or patch things on import) are the main trap: if nothing ever touches the name, the side effect never happens. Keep those eager.
frozendict: an immutable mapping builtin (PEP 814)
Python has had frozenset forever; 3.15 finally adds the dictionary equivalent. frozendict is not a subclass of dict. It inherits directly from object, which the PEP authors chose so that dict methods cannot be used to mutate it.
>>> a = frozendict(x=1, y=2)
>>> 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
Key behaviors from the PEP:
- It is hashable when all keys and values are hashable, so it works as a dict key, a set member, or an
functools.cacheargument. - It keeps insertion order for iteration, but equality and hashing ignore order.
frozendict | otherreturns a newfrozendict;|=rebinds the name to a new object instead of mutating.- Mutating methods (
update,pop,setdefault,clear,popitem) do not exist. frozendict(x=1) == dict(x=1)isTrue.
A practical use is caching a function whose argument is configuration:
from functools import cache
@cache
def build_client(settings: frozendict) -> str:
# expensive setup keyed on the settings mapping
return f"client for {settings['region']}"
cfg = frozendict(region="eu-west-1", retries=3)
print(build_client(cfg))
print(build_client(frozendict(retries=3, region="eu-west-1"))) # cache hit: equal and same hash
The standard library was updated to understand it: copy, json, pickle, pprint, marshal, and xml.etree.ElementTree accept it. json also gained an array_hook parameter, so you can load a fully immutable document:
import json
doc = json.loads(
'{"name": "svc", "ports": [80, 443], "tags": {"tier": "web"}}',
object_pairs_hook=frozendict,
array_hook=tuple,
)
print(doc) # frozendict({'name': 'svc', 'ports': (80, 443), 'tags': frozendict({'tier': 'web'})})
If your code does isinstance(x, dict) to accept "any mapping", it will reject a frozendict. Check isinstance(x, (dict, frozendict)) or, better, collections.abc.Mapping.
sentinel: unique marker values (PEP 661)
Every codebase has a _MISSING = object() somewhere to distinguish "argument not passed" from None. The problems: the repr is <object object at 0x7f...>, it does not survive copying or pickling cleanly, and type checkers cannot express it. The new builtin has the signature sentinel(name, /, *, repr=None):
MISSING = sentinel('MISSING')
def foo(value: int | MISSING = MISSING) -> int:
if value is MISSING:
return 0
return value
Sentinels keep their identity when copied, support | in type expressions as shown above, and can be pickled when they are importable by module and name. Always compare with is. Each call to sentinel() creates a new distinct object, so define it once at module level and import it where needed.
Unpacking in comprehensions (PEP 798)
A small syntax addition that removes a common nested-loop idiom:
its = [[1, 2], [3], [4, 5]]
dicts = [{"a": 1}, {"b": 2}, {"a": 3}]
flat = [*it for it in its] # [1, 2, 3, 4, 5]
merged = {**d for d in dicts} # {'a': 3, 'b': 2}
unique = {*it for it in its} # {1, 2, 3, 4, 5}
lazy_flat = (*it for it in its) # generator
These are equivalent to [x for it in its for x in it] and {k: v for d in dicts for k, v in d.items()}, just easier to read.
UTF-8 is now the default encoding (PEP 686)
This is the change most likely to alter behavior silently. Before 3.15, open("data.txt") without an encoding argument used the locale encoding, which on many Windows machines is a legacy code page like cp1252. In 3.15, Python runs in UTF-8 mode by default, so the same call reads and writes UTF-8 regardless of locale.
For most teams this fixes bugs rather than causing them: files written on Linux CI now read the same way on a Windows laptop. The risk is code that relied on the locale encoding to read files produced by legacy Windows software.
What to do:
- Pass
encoding=explicitly in code that handles files from external systems.encoding="locale"(available since 3.10) asks for the old behavior explicitly. - Run your test suite with
-X warn_default_encodingon 3.14 to find every call site that omits the argument. - If you need a temporary global escape hatch, set
PYTHONUTF8=0or run with-X utf8=0.
The new profiling package and Tachyon (PEP 799)
Python's profilers are reorganized under one package:
profiling.tracing: the deterministic profiler that used to becProfile(cProfilestays as an alias).profiling.sampling: Tachyon, a new statistical sampling profiler.
The old pure-Python profile module is deprecated and scheduled for removal in 3.17.
Tachyon's main selling point is that it can attach to an already running process without code changes or a restart, which is exactly what you want for a production worker that is pegging a CPU. The commands from the profiling.sampling documentation:
# Profile a script from start to finish
python -m profiling.sampling run script.py
# Profile a module with arguments
python -m profiling.sampling run -m mypackage.module arg1 arg2
# Attach to a running process for 30 seconds and write a flame graph
python -m profiling.sampling attach --flamegraph -d 30 -o profile.html 12345
# Live, top-like view (press q to quit)
python -m profiling.sampling attach --live 12345
Other useful options: --mode selects wall (default), cpu, gil, or exception sampling; -a samples all threads; --async-aware reconstructs asyncio task stacks; and output formats include --pstats, --collapsed (for external flame graph tools), --gecko (Firefox Profiler), and --heatmap (per-line HTML). The dump target prints a one-shot stack snapshot of every thread, which is a quick way to see where a hung process is stuck.
Two operational caveats from the docs:
- Permissions. Attaching reads another process's memory. On Linux you need root,
CAP_SYS_PTRACE, or a relaxed Yamaptrace_scope; on macOS you need root or the debugger entitlement. In containers that usually means addingSYS_PTRACEto the pod's security context. - Same minor version. The profiler and the target must both run 3.15. You cannot attach a 3.14 Tachyon to a 3.15 process or vice versa.
Free-threading and the JIT in 3.15
The free-threaded (no-GIL) build became an officially supported option in 3.14 under PEP 779. In 3.15 the important change is for extension authors: PEPs 803, 793, and 820 define an abi3t stable ABI for free-threaded builds, so a C extension can ship one wheel that works across future free-threaded versions instead of rebuilding per release. Build backends with abi3t support include meson-python, scikit-build-core, and Maturin. The official macOS installers also now install free-threading support by default.
For application developers this means the ecosystem gap that kept many people on the default build should narrow over the 3.15 cycle. Check your heavy native dependencies (NumPy, database drivers, cryptography) for cp315t or abi3t wheels before switching.
The experimental JIT was significantly reworked: a new tracing frontend, basic register allocation, and better code generation for x86-64 and AArch64. It is still off by default. The release notes report a 7–8% geometric mean improvement on pyperformance over the standard interpreter on x86-64 Linux, with individual benchmarks ranging from roughly a 15% slowdown to over 100% speedup. Treat it as something to benchmark on your own workload, not something to enable blindly.
Smaller changes worth knowing
- Better error messages.
AttributeErrornow suggests nested attributes and Python equivalents for names from other languages; calling.push()on a list suggests.append. re.prefixmatch()is added as an explicit name forre.match(), which is now soft deprecated (no removal planned).bytearray.take_bytes()returns the buffer's contents asbyteswithout a copy, replacing thebytes(buf); buf.clear()dance.asyncio.TaskGroup.cancel()lets you terminate a task group early.- Colored output for
python --helpand many standard-library CLIs, controllable via the usual color environment variables. __cached__is no longer set by the import system; use__spec__.cached.
What breaks: removals and porting notes
The removals mostly target APIs that have emitted DeprecationWarning for at least two releases. The ones most likely to hit real code:
| Removed or changed | Replacement |
|---|---|
sre_compile, sre_constants, sre_parse modules |
Use re |
http.server.CGIHTTPRequestHandler and --cgi |
A real WSGI/ASGI server |
importlib Loader.load_module() and zipimporter.load_module() |
exec_module() |
pathlib.PurePath.is_reserved() |
os.path.isreserved() |
glob.glob0() / glob.glob1() |
glob.glob(..., root_dir=...) |
typing.no_type_check_decorator |
None; remove usage |
NamedTuple("Point", x=int, y=int) keyword form |
Class syntax or a list of field tuples |
importlib.resources.files(package=...) keyword |
Pass the anchor positionally |
types.CodeType.co_lnotab |
co_lines() |
| AST node constructors with missing/unknown args | Now raise TypeError |
Behavior changes listed under "Porting to Python 3.15" that can fail tests:
sqlite3.connect(): every parameter exceptdatabaseis now keyword-only.sqlite3.connect("app.db", 5.0)must becomesqlite3.connect("app.db", timeout=5.0).argparse: withadd_argument('-f', '-foo'),destis now inferred from the long option ('foo', previously'f'). Passdest=explicitly to keep old names.base64.urlsafe_b64decode()no longer requires padding; passpadded=Trueto enforce it.unittest.assertWarns()no longer swallows warnings that do not match, so previously hidden warnings may now appear.datetime.strptime()raisesValueErrorfor a format with%dbut no year directive.
Also note the deprecations with near-term deadlines: the asyncio policy system (set_event_loop_policy() and friends) and asyncio.iscoroutinefunction() are slated for removal in 3.16, and the profile module in 3.17. If you see those in your logs, fix them now.
Upgrade checklist for Python 3.15
- Install side by side. With uv:
uv python install 3.15, then run your suite withuv run --python 3.15 pytest. We compare uv with other toolchains in uv vs Poetry and uv vs Conda vs Pixi. - Run 3.14 with warnings as errors first:
python -W error::DeprecationWarning -X warn_default_encoding -m pytest. Anything that fails here is likely removed or behavior-changed in 3.15. - Grep for removed names:
sre_parse,load_module,is_reserved,CGIHTTPRequestHandler,co_lnotab,no_type_check_decorator. - Audit
open()calls withoutencoding=that read files from external or Windows-origin systems. - Check positional arguments to
sqlite3.connect()and short-plus-longargparseoptions. - Confirm wheels exist for your native dependencies on 3.15 (and
cp315t/abi3tif you want free-threading). Early in a release cycle, some packages lag. - Add 3.15 to CI as a non-blocking job, then make it blocking once dependencies catch up.
- Only then adopt new syntax.
lazy import, comprehension unpacking, and the new builtins are 3.15-only; libraries supporting older versions should use__lazy_modules__and keepobject()sentinels until they drop 3.14.
Frequently Asked Questions
When was Python 3.15 released?
Python 3.15.0 was released on 9 October 2026, according to the python.org release page. The schedule in PEP 790 originally targeted 1 October, but the final release was postponed by a week after the third release candidate.
Do lazy imports make every Python program faster?
No. Lazy imports reduce startup time by skipping modules that are never used on a given code path. Total work is the same if every module is eventually used, and the first access to a lazily imported name pays the import cost at that moment. The biggest wins are CLIs, serverless handlers, and test collection in large codebases.
Is frozendict a subclass of dict?
No. frozendict inherits from object, not dict, so isinstance(frozendict(), dict) is False. It does compare equal to a dict with the same items, and it implements the collections.abc.Mapping interface, so type-check against Mapping if you want to accept both.
Will the UTF-8 default break my Windows application?
Only if it reads or writes text files without an encoding argument and depends on the Windows code page. Files written by older Windows tools in cp1252 may now decode incorrectly or raise UnicodeDecodeError. Pass encoding="locale" or the exact codec for those files, or set PYTHONUTF8=0 as a temporary workaround.
Is the GIL gone in Python 3.15?
Not in the default build. The free-threaded build without the GIL is a separate, officially supported build (installed by default alongside the standard one by the macOS installers). Python 3.15 makes it easier for C extensions to support it through the new abi3t stable ABI, but you still opt in by using the free-threaded interpreter.
Should I upgrade production to Python 3.15 now?
Upgrade CI first and production once your dependencies publish 3.15 wheels and your test suite is clean under the new removals. The 3.15.2 maintenance release already fixed a threading import deadlock regression introduced in 3.15.0, which is a good reminder to run the latest patch release rather than .0.
Conclusion
Python 3.15 is a practical release. Lazy imports give you a supported way to fix slow startup without contorting your code, frozendict and sentinel replace two idioms almost every project reinvents, and Tachyon turns "why is this worker stuck at 100% CPU?" into a single command. The UTF-8 default and the removal list are the parts that need attention before you flip the version in production. Run the checklist above against your test suite on 3.14 first, fix the warnings, and the jump to 3.15 should be uneventful. For more Python and developer utilities, browse the free developer tools on Butlermind Hub.