iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
👀

Experimenting with and Introducing New Features in Python 3.14

に公開

Introduction

Python 3.14.0 was released on October 7, 2025.
This article introduces new features with sample code.

The investigation for this article was conducted in the following environment.
Therefore, the sample code in the middle works only in this environment.

Python information:

import sys
>>> sys.version_info
sys.version_info(major=3, minor=14, micro=0, releaselevel='final', serial=0)
>>> sys._is_gil_enabled()
True

Machine environment:
- macOS 15.4.1
- 2 GHz Quad-Core Intel Core i5
- 16 GB 3733 MHz LPDDR4X

New Features in Python 3.14

  • Deferred evaluation of annotations
  • Multiple interpreters
  • Template Strings
  • Allow except and except* expressions without parentheses
  • Control flow restrictions in finally blocks
  • zstd support
  • Safe external debugger interface for CPython
  • Asyncio introspection capabilities

For details, see the following documentation:
https://www.python.org/downloads/release/python-3140/
https://docs.python.org/3.14/whatsnew/3.14.html

Deferred evaluation of annotations

Annotations are a mechanism for attaching meta-information to variables and functions, and are used for type hints, etc.
For example, in Python 3.13 and earlier, you can check annotations of variables, functions, and classes as follows:

x :int = 3
y: list[str] = ["a", "b"]
print("__annotations__", __annotations__)
def y(a: str, b:int)->list[str]:
  return []
print("y", y.__annotations__)
class C:
  a: int = 1
  b: int = 2
print("C", C.__annotations__)

With deferred evaluation of annotations, the following implementation now works correctly:

def f(x: Cls) -> None: ...
class Cls: pass

# With deferred evaluation in 3.14:
# {'x': <class 'Cls'>, 'return': None}
print(f.__annotations__)

In Python 3.13 and earlier, this would raise NameError: name 'Cls' is not defined, and you would need to declare it as follows to work correctly:

def f(x: 'Cls') -> None: ...
class Cls: pass

Also, because the behavior of __annotations__ has changed, some behavior has changed. For example, running the following code in Python 3.14 will result in name '__annotations__' is not defined.[1]

x :int = 3
y: list[str] = ["a", "b"]
print("__annotations__", __annotations__)

Instead of using __annotations__, it is recommended to use annotationlib to retrieve annotation information.

from annotationlib import get_annotations
import sys
x :int = 3
y: list[str] = ["a", "b"]
print(get_annotations(sys.modules[__name__]))

def y(a: str, b:int)->list[str]:
  return []
print(get_annotations(y))
class C:
  a: int = 1
  b: int = 2
print(get_annotations(C))


def f(x: Cls) -> None: ...
class Cls: pass

# With deferred evaluation in 3.14:
# {'x': <class 'Cls'>, 'return': None}
print(get_annotations(f))

References

Multiple Interpreters

In Python, the interpreter compiles Python script files and executes bytecode.
Python has a Global Interpreter Lock (GIL), which restricts the execution of bytecode to a single thread within the same interpreter. While this mechanism ensures safe execution of Python, it is an obstacle that prevents achieving parallelism, even though concurrency is possible.

In Python 3.14, you can run multiple interpreters simultaneously. This means the GIL is no longer an obstacle to achieving parallelism.

The following code illustrates the difference between running a single interpreter with multiple threads and running multiple interpreters.

Experiment Code

Sample Code

from concurrent.futures import InterpreterPoolExecutor, ThreadPoolExecutor
import os, threading, sysconfig, sys, math, time, builtins

def work(limit: int):
    start = time.perf_counter()
    print(f"start... count_primes limit:{limit} pid:{os.getpid()} thread_id:{threading.get_ident()} id(main): {id(sys.modules['__main__'])} id(builtins): {id(builtins)}", flush=True)
    cnt = 0
    for n in range(2, limit):
        root = int(math.isqrt(n))
        for d in range(2, root + 1):
            if n % d == 0:
                break
        else:
            cnt += 1
    print('end... count_primes', limit, time.perf_counter() - start, flush=True)
    return cnt

if __name__ == "__main__":
    # Check if GIL is enabled
    print("free-threaded build?  ", bool(sysconfig.get_config_var("Py_GIL_DISABLED")))
    print("GIL enabled at runtime:", getattr(sys, "_is_gil_enabled", lambda: True)())
    pattern = [1_000_000, 500_000, 900_000]
    print(f"id(main): {id(sys.modules['__main__'])} id(builtins): {id(builtins)}")
    print('****** Sequential')
    start = time.perf_counter()
    results = [work(p) for p in pattern]
    print(time.perf_counter() - start, results)

    print('****** ThreadPoolExecutor')
    start = time.perf_counter()
    with ThreadPoolExecutor() as pool:
        results = list(pool.map(work, pattern))
    print(time.perf_counter() - start, results)

    print('****** InterpreterPoolExecutor')
    start = time.perf_counter()
    with InterpreterPoolExecutor() as pool:
        results = list(pool.map(work, pattern))
    print(time.perf_counter() - start, results)

Execution Results

free-threaded build?   False
GIL enabled at runtime: True
id(main): 4539170176 id(builtins): 4538709984
****** Sequential
start... count_primes limit:1000000 pid:17971 thread_id:140704398269376 id(main): 4539170176 id(builtins): 4538709984
end... count_primes 1000000 4.183276683965232
start... count_primes limit:500000 pid:17971 thread_id:140704398269376 id(main): 4539170176 id(builtins): 4538709984
end... count_primes 500000 1.098561302991584
start... count_primes limit:900000 pid:17971 thread_id:140704398269376 id(main): 4539170176 id(builtins): 4538709984
end... count_primes 900000 2.609074859006796
7.891064839961473 [78498, 41538, 71274]
****** ThreadPoolExecutor
start... count_primes limit:1000000 pid:17971 thread_id:123145587011584 id(main): 4539170176 id(builtins): 4538709984
start... count_primes limit:500000 pid:17971 thread_id:123145603801088 id(main): 4539170176 id(builtins): 4538709984
start... count_primes limit:900000 pid:17971 thread_id:123145620590592 id(main): 4539170176 id(builtins): 4538709984
end... count_primes 500000 3.4312552110059187
end... count_primes 900000 6.604183859017212
end... count_primes 1000000 7.053750675986521
7.054385666968301 [78498, 41538, 71274]
****** InterpreterPoolExecutor
start... count_primes limit:1000000 pid:17971 thread_id:123145620590592 id(main): 4555515168 id(builtins): 4552875904
start... count_primes limit:900000 pid:17971 thread_id:123145587011584 id(main): 4553418016 id(builtins): 4550778752
start... count_primes limit:500000 pid:17971 thread_id:123145603801088 id(main): 4554466592 id(builtins): 4551827328
end... count_primes 500000 1.2162047760211863
end... count_primes 900000 2.9336666130111553
end... count_primes 1000000 3.3933817240176722
3.4818163299933076 [78498, 41538, 71274]

In this experiment, the sequential execution took about 7.9 seconds, ThreadPoolExecutor about 7 seconds, and InterpreterPoolExecutor about 3.5 seconds. Since the GIL is enabled, ThreadPoolExecutor has limited concurrency benefits, but InterpreterPoolExecutor has no such limitation. Also, it can be observed that builtins and sys.modules['__main__'] have different IDs, indicating independent environments.

Currently, multiple interpreters have several limitations:

  • Starting each interpreter is not yet optimized
  • Each interpreter uses more memory than necessary (work on broader internal sharing between interpreters is ongoing)
  • There aren't many options yet for sharing objects and other data between interpreters (currently limited to memoryview and Queue)
  • Many third-party extension modules on PyPI are not yet compatible with multiple interpreters (all standard library extension modules are compatible)
  • The approach of writing applications using multiple independent interpreters is still unfamiliar to most Python users.

References

Template String

f-strings are a mechanism to evaluate {...} and immediately embed the result into a string. Therefore, there is no way to hook and process/inspect the value at the exact moment before embedding. As a result, there are cases where f-strings cannot be used safely when constructing SQL or HTML.

The following code compares the behavior of f-strings and t-strings.

from html import escape
from string.templatelib import Template, Interpolation
user_input = '<img src=x onerror=alert(1)>'

print('f-string ----------')
html_f = f"<p>Hello, {user_input}</p>"
print(html_f)
# => <p>Hello, <img src=x onerror=alert(1)></p>   ← Dangerous (event handler remains alive)

print('t-string------------')
def html(tmpl: Template) -> str:
    """
    For t-string, keep static parts as-is, HTML-escape interpolated values, and concatenate.
    This is just an example and should not be used in production code.
    """
    out = []
    for part in tmpl:
        if isinstance(part, Interpolation):
            val = part.value
            print('  ', val, part.expression, part.format_spec)
            # Special handling for attribute dictionaries: expand to key="value"
            if isinstance(val, dict):
                attrs = []
                for k, v in val.items():
                    if v is None:
                        continue
                    attrs.append(f'{k}="{escape(str(v), quote=True)}"')
                out.append(" ".join(attrs))
            else:
                # Regular interpolation: HTML-escape
                out.append(escape(str(val), quote=True))
        else:
            # Static text: use as-is
            out.append(part)
    return "".join(out)

safe = html(t"<p>Hello, {user_input}</p>")
print(safe)
# => <p>Hello, &lt;img src=x onerror=alert(1)&gt;</p>  ← Sanitized (rendered as text)

References

Allow except and except* expressions without brackets

In Python 3.13 and earlier, the following syntax was not allowed, but it is now allowed in 3.14:

try:
    pass
except ValueError, ZeroDivisionError:
    print('Error!')

References

Control flow restrictions in finally blocks

Using return, break, or continue in a finally block will now issue a warning. For example, if you use return in a finally block, the exception or return value is suppressed:

def f():
    try:
        1 / 0
        return "...1"
    except:
        return "...2"
    finally:
        return "...3"      # ← Exception is not re-raised here

print(f()) # ...3

A warning has been introduced to alert about this behavior when return, break, or continue is present in a finally block.

References

zstd Support

Compression and decompression using zstd is now supported.

from compression import zstd
import math
# Compress and decompress with zstd
# https://en.wikipedia.org/wiki/Zstandard
data = str(math.pi).encode() * 20
print("Original data:", data)
compressed = zstd.compress(data)
print(compressed)
ratio = len(compressed) / len(data)
print(f"Achieved compression ratio of {ratio} compressed size: {len(compressed)}")

# Decompress
restored = zstd.decompress(compressed)
print("Restored data:", restored)
assert restored == data

References

Safe External Debugger Interface for CPython

Using sys.remote_exec, it is now possible to execute a specified script within a running process. This allows debugging a running process without restarting it. However, due to permissions, you may need to run sudo as necessary.

Example of remote_exec use

Remote execution example

Folder Structure

├── controller.py
├── remote_script.py
└── target.py

target.py
The script that runs in the target process on which the script is executed.

# target.py -- a long-running Python 3.14 process to be remote-exec'ed.
import os, time, pathlib, sys

pid = os.getpid()
pathlib.Path("/tmp/target.pid").write_text(str(pid))
print(f"TARGET PID: {pid}", flush=True)

# Keep the interpreter running to provide safe execution points.
try:
    while True:
        time.sleep(0.5)
except KeyboardInterrupt:
    print("Exiting target...")

remote_script.py
The script to be executed remotely.

# remote_script.py -- this file is executed *inside* the target process via sys.remote_exec()
import os, pathlib, sys, time

# Simple observable side-effect
p = pathlib.Path("/tmp/remote_exec_ok")
p.write_text(f"remote code ran in PID {os.getpid()}\n")

# Also print to the target's stdout (visible in `docker compose logs -f app`)
print(f"[remote] Hello from remote execution in PID {os.getpid()}!", flush=True)

controller.py
Executes remote_script.py in the process running target.py.

# controller.py -- call sys.remote_exec() from inside the same container.
# Usage:
#   python controller.py [/abs/or/relative/path/to/script.py]
# If script path is omitted, defaults to /work/remote_script.py

import os, sys, pathlib, time

def main():
    import sys as _sys
    script = pathlib.Path(sys.argv[2])
    pid = int(sys.argv[1])
    if not script.exists():
        print(f"ERROR: Script not found: {script}", file=sys.stderr); sys.exit(2)
    print(f"Submitting remote_exec(pid={pid}, script={script}) ...", flush=True)
    try:
        # https://docs.python.org/ja/3/library/sys.html#sys.remote_exec
        _sys.remote_exec(pid, str(script))
        print("Submitted. Code will execute at the next safe execution point.")
    except Exception as e:
        print(f"remote_exec failed: {e}", file=sys.stderr); sys.exit(3)

if __name__ == "__main__":
    main()

Usage:

  1. Start target.py
python target.py
  1. Open a new terminal and execute the remote script.
python  40284 ./remote_script.py
  • 40284 is the PID from step 1).

References

Asyncio Introspection Capabilities

Two commands, ps and pstree, have been added as tools for asyncio.

# Display a list of async tasks running in the specified process
sudo python -m asyncio ps <PID of process running async tasks>
# Visualize the call tree of async tasks
sudo python -m asyncio pstree <PID of process running async tasks>

For detailed usage examples, refer to:

Other

  • Improved error messages
  • Binary releases for Android are available
  • Free-threaded Python is officially supported
  • Incremental garbage collection
    • Maximum pause time is reduced.
    • gc.collect(1) previously meant to collect only generation 1, but now it means to collect increments of young and old generations.
  • Binary releases for Windows and macOS include an experimental just-in-time compiler.
    • You can try it with the environment variable PYTHON_JIT=1.
    • It further accelerates the specialization results of the adaptive specializer by converting them to machine code.
    • PEP 744 – JIT Compilation
    • JIT
脚注
  1. For classes and functions, __annotations__ does not cause an error even in 3.14. ↩︎

Discussion