diff --git a/.gitattributes b/.gitattributes
index 823e3e975a2..d6547212393 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -83,6 +83,7 @@ Include/opcode_ids.h generated
Include/token.h generated
Lib/_opcode_metadata.py generated
Lib/keyword.py generated
+Lib/idlelib/help.html generated
Lib/test/certdata/*.pem generated
Lib/test/certdata/*.0 generated
Lib/test/levenshtein_examples.json generated
diff --git a/.github/dependabot.yml b/.github/dependabot.yml
index c8a3165d690..7f3376f8ddb 100644
--- a/.github/dependabot.yml
+++ b/.github/dependabot.yml
@@ -12,6 +12,11 @@ updates:
update-types:
- "version-update:semver-minor"
- "version-update:semver-patch"
+ cooldown:
+ # https://blog.yossarian.net/2025/11/21/We-should-all-be-using-dependency-cooldowns
+ # Cooldowns protect against supply chain attacks by avoiding the
+ # highest-risk window immediately after new releases.
+ default-days: 14
- package-ecosystem: "pip"
directory: "/Tools/"
schedule:
@@ -19,3 +24,5 @@ updates:
labels:
- "skip issue"
- "skip news"
+ cooldown:
+ default-days: 14
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index 6aa99928278..8e15400e497 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -109,20 +109,10 @@ jobs:
python-version: '3.x'
- name: Runner image version
run: echo "IMAGE_OS_VERSION=${ImageOS}-${ImageVersion}" >> "$GITHUB_ENV"
- - name: Restore config.cache
- uses: actions/cache@v4
- with:
- path: config.cache
- # Include env.pythonLocation in key to avoid changes in environment when setup-python updates Python
- key: ${{ github.job }}-${{ env.IMAGE_OS_VERSION }}-${{ needs.build-context.outputs.config-hash }}-${{ env.pythonLocation }}
- name: Install dependencies
run: sudo ./.github/workflows/posix-deps-apt.sh
- name: Add ccache to PATH
run: echo "PATH=/usr/lib/ccache:$PATH" >> "$GITHUB_ENV"
- - name: Configure ccache action
- uses: hendrikmuhs/ccache-action@v1.2
- with:
- save: false
- name: Configure CPython
run: |
# Build Python with the libpython dynamic library
@@ -215,7 +205,6 @@ jobs:
free-threading: true
uses: ./.github/workflows/reusable-macos.yml
with:
- config_hash: ${{ needs.build-context.outputs.config-hash }}
free-threading: ${{ matrix.free-threading }}
os: ${{ matrix.os }}
@@ -247,7 +236,6 @@ jobs:
bolt: true
uses: ./.github/workflows/reusable-ubuntu.yml
with:
- config_hash: ${{ needs.build-context.outputs.config-hash }}
bolt-optimizations: ${{ matrix.bolt }}
free-threading: ${{ matrix.free-threading }}
os: ${{ matrix.os }}
@@ -278,11 +266,6 @@ jobs:
persist-credentials: false
- name: Runner image version
run: echo "IMAGE_OS_VERSION=${ImageOS}-${ImageVersion}" >> "$GITHUB_ENV"
- - name: Restore config.cache
- uses: actions/cache@v4
- with:
- path: config.cache
- key: ${{ github.job }}-${{ env.IMAGE_OS_VERSION }}-${{ needs.build-context.outputs.config-hash }}
- name: Register gcc problem matcher
run: echo "::add-matcher::.github/problem-matchers/gcc.json"
- name: Install dependencies
@@ -304,10 +287,6 @@ jobs:
- name: Add ccache to PATH
run: |
echo "PATH=/usr/lib/ccache:$PATH" >> "$GITHUB_ENV"
- - name: Configure ccache action
- uses: hendrikmuhs/ccache-action@v1.2
- with:
- save: false
- name: Configure CPython
run: ./configure CFLAGS="-fdiagnostics-format=json" --config-cache --enable-slower-safety --with-pydebug --with-openssl="$OPENSSL_DIR"
- name: Build CPython
@@ -339,11 +318,6 @@ jobs:
persist-credentials: false
- name: Runner image version
run: echo "IMAGE_OS_VERSION=${ImageOS}-${ImageVersion}" >> "$GITHUB_ENV"
- - name: Restore config.cache
- uses: actions/cache@v4
- with:
- path: config.cache
- key: ${{ github.job }}-${{ env.IMAGE_OS_VERSION }}-${{ needs.build-context.outputs.config-hash }}
- name: Register gcc problem matcher
run: echo "::add-matcher::.github/problem-matchers/gcc.json"
- name: Install dependencies
@@ -370,10 +344,6 @@ jobs:
- name: Add ccache to PATH
run: |
echo "PATH=/usr/lib/ccache:$PATH" >> "$GITHUB_ENV"
- - name: Configure ccache action
- uses: hendrikmuhs/ccache-action@v1.2
- with:
- save: false
- name: Configure CPython
run: |
./configure CFLAGS="-fdiagnostics-format=json" \
@@ -442,8 +412,6 @@ jobs:
needs: build-context
if: needs.build-context.outputs.run-tests == 'true'
uses: ./.github/workflows/reusable-wasi.yml
- with:
- config_hash: ${{ needs.build-context.outputs.config-hash }}
test-hypothesis:
name: "Hypothesis tests on Ubuntu"
@@ -479,10 +447,6 @@ jobs:
- name: Add ccache to PATH
run: |
echo "PATH=/usr/lib/ccache:$PATH" >> "$GITHUB_ENV"
- - name: Configure ccache action
- uses: hendrikmuhs/ccache-action@v1.2
- with:
- save: false
- name: Setup directory envs for out-of-tree builds
run: |
echo "CPYTHON_RO_SRCDIR=$(realpath -m "${GITHUB_WORKSPACE}"/../cpython-ro-srcdir)" >> "$GITHUB_ENV"
@@ -493,11 +457,6 @@ jobs:
run: sudo mount --bind -o ro "$GITHUB_WORKSPACE" "$CPYTHON_RO_SRCDIR"
- name: Runner image version
run: echo "IMAGE_OS_VERSION=${ImageOS}-${ImageVersion}" >> "$GITHUB_ENV"
- - name: Restore config.cache
- uses: actions/cache@v4
- with:
- path: ${{ env.CPYTHON_BUILDDIR }}/config.cache
- key: ${{ github.job }}-${{ env.IMAGE_OS_VERSION }}-${{ needs.build-context.outputs.config-hash }}
- name: Configure CPython out-of-tree
working-directory: ${{ env.CPYTHON_BUILDDIR }}
run: |
@@ -581,11 +540,6 @@ jobs:
persist-credentials: false
- name: Runner image version
run: echo "IMAGE_OS_VERSION=${ImageOS}-${ImageVersion}" >> "$GITHUB_ENV"
- - name: Restore config.cache
- uses: actions/cache@v4
- with:
- path: config.cache
- key: ${{ github.job }}-${{ env.IMAGE_OS_VERSION }}-${{ needs.build-context.outputs.config-hash }}
- name: Register gcc problem matcher
run: echo "::add-matcher::.github/problem-matchers/gcc.json"
- name: Install dependencies
@@ -611,11 +565,6 @@ jobs:
- name: Add ccache to PATH
run: |
echo "PATH=/usr/lib/ccache:$PATH" >> "$GITHUB_ENV"
- - name: Configure ccache action
- uses: hendrikmuhs/ccache-action@v1.2
- with:
- save: ${{ github.event_name == 'push' }}
- max-size: "200M"
- name: Configure CPython
run: ./configure --config-cache --with-address-sanitizer --without-pymalloc
- name: Build CPython
@@ -647,7 +596,6 @@ jobs:
uses: ./.github/workflows/reusable-san.yml
with:
sanitizer: ${{ matrix.sanitizer }}
- config_hash: ${{ needs.build-context.outputs.config-hash }}
free-threading: ${{ matrix.free-threading }}
cross-build-linux:
@@ -662,11 +610,6 @@ jobs:
persist-credentials: false
- name: Runner image version
run: echo "IMAGE_OS_VERSION=${ImageOS}-${ImageVersion}" >> "$GITHUB_ENV"
- - name: Restore config.cache
- uses: actions/cache@v4
- with:
- path: config.cache
- key: ${{ github.job }}-${{ env.IMAGE_OS_VERSION }}-${{ needs.build-context.outputs.config-hash }}
- name: Register gcc problem matcher
run: echo "::add-matcher::.github/problem-matchers/gcc.json"
- name: Set build dir
diff --git a/.github/workflows/jit.yml b/.github/workflows/jit.yml
index c32bf4fd63c..62325250bd3 100644
--- a/.github/workflows/jit.yml
+++ b/.github/workflows/jit.yml
@@ -68,7 +68,7 @@ jobs:
- true
- false
llvm:
- - 19
+ - 21
include:
- target: i686-pc-windows-msvc/msvc
architecture: Win32
@@ -138,7 +138,7 @@ jobs:
fail-fast: false
matrix:
llvm:
- - 19
+ - 21
steps:
- uses: actions/checkout@v4
with:
@@ -166,7 +166,7 @@ jobs:
fail-fast: false
matrix:
llvm:
- - 19
+ - 21
steps:
- uses: actions/checkout@v4
with:
@@ -183,3 +183,27 @@ jobs:
- name: Run tests without optimizations
run: |
PYTHON_UOPS_OPTIMIZE=0 ./python -m test --multiprocess 0 --timeout 4500 --verbose2 --verbose3
+
+ tail-call-jit:
+ name: JIT with tail calling interpreter
+ needs: interpreter
+ runs-on: ubuntu-24.04
+ timeout-minutes: 90
+ strategy:
+ fail-fast: false
+ matrix:
+ llvm:
+ - 21
+ steps:
+ - uses: actions/checkout@v4
+ with:
+ persist-credentials: false
+ - uses: actions/setup-python@v5
+ with:
+ python-version: '3.11'
+ - name: Build with JIT and tailcall
+ run: |
+ sudo bash -c "$(wget -O - https://apt.llvm.org/llvm.sh)" ./llvm.sh ${{ matrix.llvm }}
+ export PATH="$(llvm-config-${{ matrix.llvm }} --bindir):$PATH"
+ CC=clang-${{ matrix.llvm }} ./configure --enable-experimental-jit --with-tail-call-interp --with-pydebug
+ make all --jobs 4
diff --git a/.github/workflows/reusable-context.yml b/.github/workflows/reusable-context.yml
index d2668ddcac1..66c7cc47de0 100644
--- a/.github/workflows/reusable-context.yml
+++ b/.github/workflows/reusable-context.yml
@@ -17,9 +17,6 @@ on: # yamllint disable-line rule:truthy
# || 'falsy-branch'
# }}
#
- config-hash:
- description: Config hash value for use in cache keys
- value: ${{ jobs.compute-changes.outputs.config-hash }} # str
run-docs:
description: Whether to build the docs
value: ${{ jobs.compute-changes.outputs.run-docs }} # bool
@@ -42,7 +39,6 @@ jobs:
runs-on: ubuntu-latest
timeout-minutes: 10
outputs:
- config-hash: ${{ steps.config-hash.outputs.hash }}
run-ci-fuzz: ${{ steps.changes.outputs.run-ci-fuzz }}
run-docs: ${{ steps.changes.outputs.run-docs }}
run-tests: ${{ steps.changes.outputs.run-tests }}
@@ -100,8 +96,3 @@ jobs:
GITHUB_EVENT_NAME: ${{ github.event_name }}
CCF_TARGET_REF: ${{ github.base_ref || github.event.repository.default_branch }}
CCF_HEAD_REF: ${{ github.event.pull_request.head.sha || github.sha }}
-
- - name: Compute hash for config cache key
- id: config-hash
- run: |
- echo "hash=${{ hashFiles('configure', 'configure.ac', '.github/workflows/build.yml') }}" >> "$GITHUB_OUTPUT"
diff --git a/.github/workflows/reusable-macos.yml b/.github/workflows/reusable-macos.yml
index 3d310ae695b..98d557ba1ea 100644
--- a/.github/workflows/reusable-macos.yml
+++ b/.github/workflows/reusable-macos.yml
@@ -3,9 +3,6 @@ name: Reusable macOS
on:
workflow_call:
inputs:
- config_hash:
- required: true
- type: string
free-threading:
required: false
type: boolean
@@ -36,11 +33,6 @@ jobs:
persist-credentials: false
- name: Runner image version
run: echo "IMAGE_OS_VERSION=${ImageOS}-${ImageVersion}" >> "$GITHUB_ENV"
- - name: Restore config.cache
- uses: actions/cache@v4
- with:
- path: config.cache
- key: ${{ github.job }}-${{ env.IMAGE_OS_VERSION }}-${{ inputs.config_hash }}
- name: Install Homebrew dependencies
run: |
brew install pkg-config openssl@3.0 xz gdbm tcl-tk@9 make
diff --git a/.github/workflows/reusable-san.yml b/.github/workflows/reusable-san.yml
index e6ff02e4838..c601d0b7338 100644
--- a/.github/workflows/reusable-san.yml
+++ b/.github/workflows/reusable-san.yml
@@ -6,9 +6,6 @@ on:
sanitizer:
required: true
type: string
- config_hash:
- required: true
- type: string
free-threading:
description: Whether to use free-threaded mode
required: false
@@ -34,11 +31,6 @@ jobs:
persist-credentials: false
- name: Runner image version
run: echo "IMAGE_OS_VERSION=${ImageOS}-${ImageVersion}" >> "$GITHUB_ENV"
- - name: Restore config.cache
- uses: actions/cache@v4
- with:
- path: config.cache
- key: ${{ github.job }}-${{ env.IMAGE_OS_VERSION }}-${{ inputs.sanitizer }}-${{ inputs.config_hash }}
- name: Install dependencies
run: |
sudo ./.github/workflows/posix-deps-apt.sh
@@ -77,11 +69,6 @@ jobs:
- name: Add ccache to PATH
run: |
echo "PATH=/usr/lib/ccache:$PATH" >> "$GITHUB_ENV"
- - name: Configure ccache action
- uses: hendrikmuhs/ccache-action@v1.2
- with:
- save: ${{ github.event_name == 'push' }}
- max-size: "200M"
- name: Configure CPython
run: >-
./configure
diff --git a/.github/workflows/reusable-ubuntu.yml b/.github/workflows/reusable-ubuntu.yml
index 7f8b9fdf5d6..0c1ebe29ae3 100644
--- a/.github/workflows/reusable-ubuntu.yml
+++ b/.github/workflows/reusable-ubuntu.yml
@@ -3,9 +3,6 @@ name: Reusable Ubuntu
on:
workflow_call:
inputs:
- config_hash:
- required: true
- type: string
bolt-optimizations:
description: Whether to enable BOLT optimizations
required: false
@@ -64,11 +61,6 @@ jobs:
- name: Add ccache to PATH
run: |
echo "PATH=/usr/lib/ccache:$PATH" >> "$GITHUB_ENV"
- - name: Configure ccache action
- uses: hendrikmuhs/ccache-action@v1.2
- with:
- save: ${{ github.event_name == 'push' }}
- max-size: "200M"
- name: Setup directory envs for out-of-tree builds
run: |
echo "CPYTHON_RO_SRCDIR=$(realpath -m "${GITHUB_WORKSPACE}"/../cpython-ro-srcdir)" >> "$GITHUB_ENV"
@@ -79,11 +71,6 @@ jobs:
run: sudo mount --bind -o ro "$GITHUB_WORKSPACE" "$CPYTHON_RO_SRCDIR"
- name: Runner image version
run: echo "IMAGE_OS_VERSION=${ImageOS}-${ImageVersion}" >> "$GITHUB_ENV"
- - name: Restore config.cache
- uses: actions/cache@v4
- with:
- path: ${{ env.CPYTHON_BUILDDIR }}/config.cache
- key: ${{ github.job }}-${{ env.IMAGE_OS_VERSION }}-${{ inputs.config_hash }}
- name: Configure CPython out-of-tree
working-directory: ${{ env.CPYTHON_BUILDDIR }}
# `test_unpickle_module_race` writes to the source directory, which is
diff --git a/.github/workflows/reusable-wasi.yml b/.github/workflows/reusable-wasi.yml
index 7c40e566b2a..91d76fd1b5f 100644
--- a/.github/workflows/reusable-wasi.yml
+++ b/.github/workflows/reusable-wasi.yml
@@ -2,10 +2,6 @@ name: Reusable WASI
on:
workflow_call:
- inputs:
- config_hash:
- required: true
- type: string
env:
FORCE_COLOR: 1
@@ -17,7 +13,7 @@ jobs:
timeout-minutes: 60
env:
WASMTIME_VERSION: 38.0.3
- WASI_SDK_VERSION: 25
+ WASI_SDK_VERSION: 29
WASI_SDK_PATH: /opt/wasi-sdk
CROSS_BUILD_PYTHON: cross-build/build
CROSS_BUILD_WASI: cross-build/wasm32-wasip1
@@ -42,11 +38,6 @@ jobs:
mkdir "${WASI_SDK_PATH}" && \
curl -s -S --location "https://github.com/WebAssembly/wasi-sdk/releases/download/wasi-sdk-${WASI_SDK_VERSION}/wasi-sdk-${WASI_SDK_VERSION}.0-arm64-linux.tar.gz" | \
tar --strip-components 1 --directory "${WASI_SDK_PATH}" --extract --gunzip
- - name: "Configure ccache action"
- uses: hendrikmuhs/ccache-action@v1.2
- with:
- save: ${{ github.event_name == 'push' }}
- max-size: "200M"
- name: "Add ccache to PATH"
run: echo "PATH=/usr/lib/ccache:$PATH" >> "$GITHUB_ENV"
- name: "Install Python"
@@ -55,29 +46,15 @@ jobs:
python-version: '3.x'
- name: "Runner image version"
run: echo "IMAGE_OS_VERSION=${ImageOS}-${ImageVersion}" >> "$GITHUB_ENV"
- - name: "Restore Python build config.cache"
- uses: actions/cache@v4
- with:
- path: ${{ env.CROSS_BUILD_PYTHON }}/config.cache
- # Include env.pythonLocation in key to avoid changes in environment when setup-python updates Python.
- # Include the hash of `Tools/wasm/wasi.py` as it may change the environment variables.
- # (Make sure to keep the key in sync with the other config.cache step below.)
- key: ${{ github.job }}-${{ env.IMAGE_OS_VERSION }}-${{ env.WASI_SDK_VERSION }}-${{ env.WASMTIME_VERSION }}-${{ inputs.config_hash }}-${{ hashFiles('Tools/wasm/wasi.py') }}-${{ env.pythonLocation }}
- name: "Configure build Python"
- run: python3 Tools/wasm/wasi.py configure-build-python -- --config-cache --with-pydebug
+ run: python3 Tools/wasm/wasi configure-build-python -- --config-cache --with-pydebug
- name: "Make build Python"
- run: python3 Tools/wasm/wasi.py make-build-python
- - name: "Restore host config.cache"
- uses: actions/cache@v4
- with:
- path: ${{ env.CROSS_BUILD_WASI }}/config.cache
- # Should be kept in sync with the other config.cache step above.
- key: ${{ github.job }}-${{ env.IMAGE_OS_VERSION }}-${{ env.WASI_SDK_VERSION }}-${{ env.WASMTIME_VERSION }}-${{ inputs.config_hash }}-${{ hashFiles('Tools/wasm/wasi.py') }}-${{ env.pythonLocation }}
+ run: python3 Tools/wasm/wasi make-build-python
- name: "Configure host"
# `--with-pydebug` inferred from configure-build-python
- run: python3 Tools/wasm/wasi.py configure-host -- --config-cache
+ run: python3 Tools/wasm/wasi configure-host -- --config-cache
- name: "Make host"
- run: python3 Tools/wasm/wasi.py make-host
+ run: python3 Tools/wasm/wasi make-host
- name: "Display build info"
run: make --directory "${CROSS_BUILD_WASI}" pythoninfo
- name: "Test"
diff --git a/.gitignore b/.gitignore
index 2bf4925647d..4ea2fd96554 100644
--- a/.gitignore
+++ b/.gitignore
@@ -135,7 +135,6 @@ Tools/unicode/data/
/config.log
/config.status
/config.status.lineno
-# hendrikmuhs/ccache-action@v1
/.ccache
/cross-build/
/jit_stencils*.h
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index b0311f05279..c5767ee841e 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -2,6 +2,10 @@ repos:
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.13.2
hooks:
+ - id: ruff-check
+ name: Run Ruff (lint) on Apple/
+ args: [--exit-non-zero-on-fix, --config=Apple/.ruff.toml]
+ files: ^Apple/
- id: ruff-check
name: Run Ruff (lint) on Doc/
args: [--exit-non-zero-on-fix]
@@ -30,6 +34,10 @@ repos:
name: Run Ruff (lint) on Tools/wasm/
args: [--exit-non-zero-on-fix, --config=Tools/wasm/.ruff.toml]
files: ^Tools/wasm/
+ - id: ruff-format
+ name: Run Ruff (format) on Apple/
+ args: [--exit-non-zero-on-fix, --config=Apple/.ruff.toml]
+ files: ^Apple
- id: ruff-format
name: Run Ruff (format) on Doc/
args: [--check]
diff --git a/Apple/.ruff.toml b/Apple/.ruff.toml
new file mode 100644
index 00000000000..4cdc39ebee4
--- /dev/null
+++ b/Apple/.ruff.toml
@@ -0,0 +1,22 @@
+extend = "../.ruff.toml" # Inherit the project-wide settings
+
+[format]
+preview = true
+docstring-code-format = true
+
+[lint]
+select = [
+ "C4", # flake8-comprehensions
+ "E", # pycodestyle
+ "F", # pyflakes
+ "I", # isort
+ "ISC", # flake8-implicit-str-concat
+ "LOG", # flake8-logging
+ "PGH", # pygrep-hooks
+ "PT", # flake8-pytest-style
+ "PYI", # flake8-pyi
+ "RUF100", # Ban unused `# noqa` comments
+ "UP", # pyupgrade
+ "W", # pycodestyle
+ "YTT", # flake8-2020
+]
diff --git a/Apple/__main__.py b/Apple/__main__.py
index 34744871f68..256966e76c2 100644
--- a/Apple/__main__.py
+++ b/Apple/__main__.py
@@ -46,13 +46,12 @@
import sys
import sysconfig
import time
-from collections.abc import Sequence
+from collections.abc import Callable, Sequence
from contextlib import contextmanager
from datetime import datetime, timezone
from os.path import basename, relpath
from pathlib import Path
from subprocess import CalledProcessError
-from typing import Callable
EnvironmentT = dict[str, str]
ArgsT = Sequence[str | Path]
@@ -140,17 +139,15 @@ def print_env(env: EnvironmentT) -> None:
def apple_env(host: str) -> EnvironmentT:
"""Construct an Apple development environment for the given host."""
env = {
- "PATH": ":".join(
- [
- str(PYTHON_DIR / "Apple/iOS/Resources/bin"),
- str(subdir(host) / "prefix"),
- "/usr/bin",
- "/bin",
- "/usr/sbin",
- "/sbin",
- "/Library/Apple/usr/bin",
- ]
- ),
+ "PATH": ":".join([
+ str(PYTHON_DIR / "Apple/iOS/Resources/bin"),
+ str(subdir(host) / "prefix"),
+ "/usr/bin",
+ "/bin",
+ "/usr/sbin",
+ "/sbin",
+ "/Library/Apple/usr/bin",
+ ]),
}
return env
@@ -196,14 +193,10 @@ def clean(context: argparse.Namespace, target: str = "all") -> None:
paths.append(target)
if target in {"all", "hosts", "test"}:
- paths.extend(
- [
- path.name
- for path in CROSS_BUILD_DIR.glob(
- f"{context.platform}-testbed.*"
- )
- ]
- )
+ paths.extend([
+ path.name
+ for path in CROSS_BUILD_DIR.glob(f"{context.platform}-testbed.*")
+ ])
for path in paths:
delete_path(path)
@@ -352,18 +345,16 @@ def download(url: str, target_dir: Path) -> Path:
out_path = target_path / basename(url)
if not Path(out_path).is_file():
- run(
- [
- "curl",
- "-Lf",
- "--retry",
- "5",
- "--retry-all-errors",
- "-o",
- out_path,
- url,
- ]
- )
+ run([
+ "curl",
+ "-Lf",
+ "--retry",
+ "5",
+ "--retry-all-errors",
+ "-o",
+ out_path,
+ url,
+ ])
else:
print(f"Using cached version of {basename(url)}")
return out_path
@@ -468,8 +459,7 @@ def package_version(prefix_path: Path) -> str:
def lib_platform_files(dirname, names):
- """A file filter that ignores platform-specific files in the lib directory.
- """
+ """A file filter that ignores platform-specific files in lib."""
path = Path(dirname)
if (
path.parts[-3] == "lib"
@@ -478,7 +468,7 @@ def lib_platform_files(dirname, names):
):
return names
elif path.parts[-2] == "lib" and path.parts[-1].startswith("python"):
- ignored_names = set(
+ ignored_names = {
name
for name in names
if (
@@ -486,7 +476,13 @@ def lib_platform_files(dirname, names):
or name.startswith("_sysconfig_vars_")
or name == "build-details.json"
)
- )
+ }
+ elif path.parts[-1] == "lib":
+ ignored_names = {
+ name
+ for name in names
+ if name.startswith("libpython") and name.endswith(".dylib")
+ }
else:
ignored_names = set()
@@ -499,7 +495,9 @@ def lib_non_platform_files(dirname, names):
"""
path = Path(dirname)
if path.parts[-2] == "lib" and path.parts[-1].startswith("python"):
- return set(names) - lib_platform_files(dirname, names) - {"lib-dynload"}
+ return (
+ set(names) - lib_platform_files(dirname, names) - {"lib-dynload"}
+ )
else:
return set()
@@ -507,14 +505,15 @@ def lib_non_platform_files(dirname, names):
def create_xcframework(platform: str) -> str:
"""Build an XCframework from the component parts for the platform.
- :return: The version number of the Python verion that was packaged.
+ :return: The version number of the Python version that was packaged.
"""
package_path = CROSS_BUILD_DIR / platform
try:
package_path.mkdir()
except FileExistsError:
raise RuntimeError(
- f"{platform} XCframework already exists; do you need to run with --clean?"
+ f"{platform} XCframework already exists; do you need to run "
+ "with --clean?"
) from None
frameworks = []
@@ -607,7 +606,7 @@ def create_xcframework(platform: str) -> str:
print(f" - {slice_name} binaries")
shutil.copytree(first_path / "bin", slice_path / "bin")
- # Copy the include path (this will be a symlink to the framework headers)
+ # Copy the include path (a symlink to the framework headers)
print(f" - {slice_name} include files")
shutil.copytree(
first_path / "include",
@@ -621,6 +620,12 @@ def create_xcframework(platform: str) -> str:
slice_framework / "Headers/pyconfig.h",
)
+ print(f" - {slice_name} shared library")
+ # Create a simlink for the fat library
+ shared_lib = slice_path / f"lib/libpython{version_tag}.dylib"
+ shared_lib.parent.mkdir()
+ shared_lib.symlink_to("../Python.framework/Python")
+
print(f" - {slice_name} architecture-specific files")
for host_triple, multiarch in slice_parts.items():
print(f" - {multiarch} standard library")
@@ -632,6 +637,7 @@ def create_xcframework(platform: str) -> str:
framework_path(host_triple, multiarch) / "lib",
package_path / "Python.xcframework/lib",
ignore=lib_platform_files,
+ symlinks=True,
)
has_common_stdlib = True
@@ -639,6 +645,7 @@ def create_xcframework(platform: str) -> str:
framework_path(host_triple, multiarch) / "lib",
slice_path / f"lib-{arch}",
ignore=lib_non_platform_files,
+ symlinks=True,
)
# Copy the host's pyconfig.h to an architecture-specific name.
@@ -659,7 +666,8 @@ def create_xcframework(platform: str) -> str:
# statically link those libraries into a Framework, you become
# responsible for providing a privacy manifest for that framework.
xcprivacy_file = {
- "OpenSSL": subdir(host_triple) / "prefix/share/OpenSSL.xcprivacy"
+ "OpenSSL": subdir(host_triple)
+ / "prefix/share/OpenSSL.xcprivacy"
}
print(f" - {multiarch} xcprivacy files")
for module, lib in [
@@ -669,7 +677,8 @@ def create_xcframework(platform: str) -> str:
shutil.copy(
xcprivacy_file[lib],
slice_path
- / f"lib-{arch}/python{version_tag}/lib-dynload/{module}.xcprivacy",
+ / f"lib-{arch}/python{version_tag}"
+ / f"lib-dynload/{module}.xcprivacy",
)
print(" - build tools")
@@ -692,18 +701,16 @@ def package(context: argparse.Namespace) -> None:
# Clone testbed
print()
- run(
- [
- sys.executable,
- "Apple/testbed",
- "clone",
- "--platform",
- context.platform,
- "--framework",
- CROSS_BUILD_DIR / context.platform / "Python.xcframework",
- CROSS_BUILD_DIR / context.platform / "testbed",
- ]
- )
+ run([
+ sys.executable,
+ "Apple/testbed",
+ "clone",
+ "--platform",
+ context.platform,
+ "--framework",
+ CROSS_BUILD_DIR / context.platform / "Python.xcframework",
+ CROSS_BUILD_DIR / context.platform / "testbed",
+ ])
# Build the final archive
archive_name = (
@@ -757,7 +764,7 @@ def build(context: argparse.Namespace, host: str | None = None) -> None:
package(context)
-def test(context: argparse.Namespace, host: str | None = None) -> None:
+def test(context: argparse.Namespace, host: str | None = None) -> None: # noqa: PT028
"""The implementation of the "test" command."""
if host is None:
host = context.host
@@ -795,18 +802,16 @@ def test(context: argparse.Namespace, host: str | None = None) -> None:
/ f"Frameworks/{apple_multiarch(host)}"
)
- run(
- [
- sys.executable,
- "Apple/testbed",
- "clone",
- "--platform",
- context.platform,
- "--framework",
- framework_path,
- testbed_dir,
- ]
- )
+ run([
+ sys.executable,
+ "Apple/testbed",
+ "clone",
+ "--platform",
+ context.platform,
+ "--framework",
+ framework_path,
+ testbed_dir,
+ ])
run(
[
@@ -840,7 +845,7 @@ def apple_sim_host(platform_name: str) -> str:
"""Determine the native simulator target for this platform."""
for _, slice_parts in HOSTS[platform_name].items():
for host_triple in slice_parts:
- parts = host_triple.split('-')
+ parts = host_triple.split("-")
if parts[0] == platform.machine() and parts[-1] == "simulator":
return host_triple
@@ -968,20 +973,29 @@ def parse_args() -> argparse.Namespace:
cmd.add_argument(
"--simulator",
help=(
- "The name of the simulator to use (eg: 'iPhone 16e'). Defaults to "
- "the most recently released 'entry level' iPhone device. Device "
- "architecture and OS version can also be specified; e.g., "
- "`--simulator 'iPhone 16 Pro,arch=arm64,OS=26.0'` would run on "
- "an ARM64 iPhone 16 Pro simulator running iOS 26.0."
+ "The name of the simulator to use (eg: 'iPhone 16e'). "
+ "Defaults to the most recently released 'entry level' "
+ "iPhone device. Device architecture and OS version can also "
+ "be specified; e.g., "
+ "`--simulator 'iPhone 16 Pro,arch=arm64,OS=26.0'` would "
+ "run on an ARM64 iPhone 16 Pro simulator running iOS 26.0."
),
)
group = cmd.add_mutually_exclusive_group()
group.add_argument(
- "--fast-ci", action="store_const", dest="ci_mode", const="fast",
- help="Add test arguments for GitHub Actions")
+ "--fast-ci",
+ action="store_const",
+ dest="ci_mode",
+ const="fast",
+ help="Add test arguments for GitHub Actions",
+ )
group.add_argument(
- "--slow-ci", action="store_const", dest="ci_mode", const="slow",
- help="Add test arguments for buildbots")
+ "--slow-ci",
+ action="store_const",
+ dest="ci_mode",
+ const="slow",
+ help="Add test arguments for buildbots",
+ )
for subcommand in [configure_build, configure_host, build, ci]:
subcommand.add_argument(
diff --git a/Apple/testbed/Python.xcframework/build/utils.sh b/Apple/testbed/Python.xcframework/build/utils.sh
index 961c46d014b..e7155d8b30e 100755
--- a/Apple/testbed/Python.xcframework/build/utils.sh
+++ b/Apple/testbed/Python.xcframework/build/utils.sh
@@ -46,7 +46,8 @@ install_stdlib() {
rsync -au --delete "$PROJECT_DIR/$PYTHON_XCFRAMEWORK_PATH/lib/" "$CODESIGNING_FOLDER_PATH/python/lib/"
rsync -au "$PROJECT_DIR/$PYTHON_XCFRAMEWORK_PATH/$SLICE_FOLDER/lib-$ARCHS/" "$CODESIGNING_FOLDER_PATH/python/lib/"
else
- rsync -au --delete "$PROJECT_DIR/$PYTHON_XCFRAMEWORK_PATH/$SLICE_FOLDER/lib/" "$CODESIGNING_FOLDER_PATH/python/lib/"
+ # A single-arch framework will have a libpython symlink; that can't be included at runtime
+ rsync -au --delete "$PROJECT_DIR/$PYTHON_XCFRAMEWORK_PATH/$SLICE_FOLDER/lib/" "$CODESIGNING_FOLDER_PATH/python/lib/" --exclude 'libpython*.dylib'
fi
}
diff --git a/Apple/testbed/__main__.py b/Apple/testbed/__main__.py
index 42eb60a4c8d..0dd77ab8b82 100644
--- a/Apple/testbed/__main__.py
+++ b/Apple/testbed/__main__.py
@@ -2,6 +2,7 @@
import json
import os
import re
+import shlex
import shutil
import subprocess
import sys
@@ -31,15 +32,15 @@ def select_simulator_device(platform):
json_data = json.loads(raw_json)
if platform == "iOS":
- # Any iOS device will do; we'll look for "SE" devices - but the name isn't
- # consistent over time. Older Xcode versions will use "iPhone SE (Nth
- # generation)"; As of 2025, they've started using "iPhone 16e".
+ # Any iOS device will do; we'll look for "SE" devices - but the name
+ # isn't consistent over time. Older Xcode versions will use "iPhone SE
+ # (Nth generation)"; As of 2025, they've started using "iPhone 16e".
#
- # When Xcode is updated after a new release, new devices will be available
- # and old ones will be dropped from the set available on the latest iOS
- # version. Select the one with the highest minimum runtime version - this
- # is an indicator of the "newest" released device, which should always be
- # supported on the "most recent" iOS version.
+ # When Xcode is updated after a new release, new devices will be
+ # available and old ones will be dropped from the set available on the
+ # latest iOS version. Select the one with the highest minimum runtime
+ # version - this is an indicator of the "newest" released device, which
+ # should always be supported on the "most recent" iOS version.
se_simulators = sorted(
(devicetype["minRuntimeVersion"], devicetype["name"])
for devicetype in json_data["devicetypes"]
@@ -252,7 +253,7 @@ def update_test_plan(testbed_path, platform, args):
test_plan = json.load(f)
test_plan["defaultOptions"]["commandLineArgumentEntries"] = [
- {"argument": arg} for arg in args
+ {"argument": shlex.quote(arg)} for arg in args
]
with test_plan_path.open("w", encoding="utf-8") as f:
@@ -294,7 +295,8 @@ def main():
parser = argparse.ArgumentParser(
description=(
- "Manages the process of testing an Apple Python project through Xcode."
+ "Manages the process of testing an Apple Python project "
+ "through Xcode."
),
)
@@ -335,7 +337,10 @@ def main():
run = subcommands.add_parser(
"run",
- usage="%(prog)s [-h] [--simulator SIMULATOR] -- [ ...]",
+ usage=(
+ "%(prog)s [-h] [--simulator SIMULATOR] -- "
+ " [ ...]"
+ ),
description=(
"Run a testbed project. The arguments provided after `--` will be "
"passed to the running iOS process as if they were arguments to "
@@ -396,9 +401,9 @@ def main():
/ "bin"
).is_dir():
print(
- f"Testbed does not contain a compiled Python framework. Use "
- f"`python {sys.argv[0]} clone ...` to create a runnable "
- f"clone of this testbed."
+ "Testbed does not contain a compiled Python framework. "
+ f"Use `python {sys.argv[0]} clone ...` to create a "
+ "runnable clone of this testbed."
)
sys.exit(20)
@@ -410,7 +415,8 @@ def main():
)
else:
print(
- f"Must specify test arguments (e.g., {sys.argv[0]} run -- test)"
+ "Must specify test arguments "
+ f"(e.g., {sys.argv[0]} run -- test)"
)
print()
parser.print_help(sys.stderr)
diff --git a/Doc/Makefile b/Doc/Makefile
index f6f4c721080..f16d9cacb1b 100644
--- a/Doc/Makefile
+++ b/Doc/Makefile
@@ -241,7 +241,8 @@ dist-pdf:
# as otherwise the full latexmk process is run twice.
# ($$ is needed to escape the $; https://www.gnu.org/software/make/manual/make.html#Basics-of-Variable-References)
-sed -i 's/: all-$$(FMT)/:/' build/latex/Makefile
- (cd build/latex; $(MAKE) clean && $(MAKE) --jobs=$$((`nproc`+1)) --output-sync LATEXMKOPTS='-quiet' all-pdf && $(MAKE) FMT=pdf zip bz2)
+ if [ -n "$(filter output-sync,$(value .FEATURES))" ]; then OUTPUTSYNC=--output-sync; else OUTPUTSYNC=; fi && \
+ (cd build/latex; $(MAKE) clean && $(MAKE) --jobs=$$((`getconf _NPROCESSORS_ONLN`+1)) $$OUTPUTSYNC LATEXMKOPTS='-quiet' all-pdf && $(MAKE) FMT=pdf zip bz2)
cp build/latex/docs-pdf.zip dist/python-$(DISTVERSION)-docs-pdf-a4.zip
cp build/latex/docs-pdf.tar.bz2 dist/python-$(DISTVERSION)-docs-pdf-a4.tar.bz2
@echo "Build finished and archived!"
diff --git a/Doc/c-api/allocation.rst b/Doc/c-api/allocation.rst
index 59d913a0462..59044d2d88c 100644
--- a/Doc/c-api/allocation.rst
+++ b/Doc/c-api/allocation.rst
@@ -140,10 +140,6 @@ Allocating Objects on the Heap
* :c:member:`~PyTypeObject.tp_alloc`
-.. c:function:: void PyObject_Del(void *op)
-
- Same as :c:func:`PyObject_Free`.
-
.. c:var:: PyObject _Py_NoneStruct
Object which is visible in Python as ``None``. This should only be accessed
@@ -156,3 +152,35 @@ Allocating Objects on the Heap
:ref:`moduleobjects`
To allocate and create extension modules.
+
+Deprecated aliases
+^^^^^^^^^^^^^^^^^^
+
+These are :term:`soft deprecated` aliases to existing functions and macros.
+They exist solely for backwards compatibility.
+
+
+.. list-table::
+ :widths: auto
+ :header-rows: 1
+
+ * * Deprecated alias
+ * Function
+ * * .. c:macro:: PyObject_NEW(type, typeobj)
+ * :c:macro:`PyObject_New`
+ * * .. c:macro:: PyObject_NEW_VAR(type, typeobj, n)
+ * :c:macro:`PyObject_NewVar`
+ * * .. c:macro:: PyObject_INIT(op, typeobj)
+ * :c:func:`PyObject_Init`
+ * * .. c:macro:: PyObject_INIT_VAR(op, typeobj, n)
+ * :c:func:`PyObject_InitVar`
+ * * .. c:macro:: PyObject_MALLOC(n)
+ * :c:func:`PyObject_Malloc`
+ * * .. c:macro:: PyObject_REALLOC(p, n)
+ * :c:func:`PyObject_Realloc`
+ * * .. c:macro:: PyObject_FREE(p)
+ * :c:func:`PyObject_Free`
+ * * .. c:macro:: PyObject_DEL(p)
+ * :c:func:`PyObject_Free`
+ * * .. c:macro:: PyObject_Del(p)
+ * :c:func:`PyObject_Free`
diff --git a/Doc/c-api/buffer.rst b/Doc/c-api/buffer.rst
index d3081894ead..6bb72a2312b 100644
--- a/Doc/c-api/buffer.rst
+++ b/Doc/c-api/buffer.rst
@@ -261,6 +261,10 @@ readonly, format
MUST be consistent for all consumers. For example, :c:expr:`PyBUF_SIMPLE | PyBUF_WRITABLE`
can be used to request a simple writable buffer.
+ .. c:macro:: PyBUF_WRITEABLE
+
+ This is a :term:`soft deprecated` alias to :c:macro:`PyBUF_WRITABLE`.
+
.. c:macro:: PyBUF_FORMAT
Controls the :c:member:`~Py_buffer.format` field. If set, this field MUST
diff --git a/Doc/c-api/bytes.rst b/Doc/c-api/bytes.rst
index 865a9e5d2bf..82c25573683 100644
--- a/Doc/c-api/bytes.rst
+++ b/Doc/c-api/bytes.rst
@@ -228,6 +228,42 @@ called with a non-bytes parameter.
The function is :term:`soft deprecated`,
use the :c:type:`PyBytesWriter` API instead.
+
+.. c:function:: PyObject *PyBytes_Repr(PyObject *bytes, int smartquotes)
+
+ Get the string representation of *bytes*. This function is currently used to
+ implement :meth:`!bytes.__repr__` in Python.
+
+ This function does not do type checking; it is undefined behavior to pass
+ *bytes* as a non-bytes object or ``NULL``.
+
+ If *smartquotes* is true, the representation will use a double-quoted string
+ instead of single-quoted string when single-quotes are present in *bytes*.
+ For example, the byte string ``'Python'`` would be represented as
+ ``b"'Python'"`` when *smartquotes* is true, or ``b'\'Python\''`` when it is
+ false.
+
+ On success, this function returns a :term:`strong reference` to a
+ :class:`str` object containing the representation. On failure, this
+ returns ``NULL`` with an exception set.
+
+
+.. c:function:: PyObject *PyBytes_DecodeEscape(const char *s, Py_ssize_t len, const char *errors, Py_ssize_t unicode, const char *recode_encoding)
+
+ Unescape a backslash-escaped string *s*. *s* must not be ``NULL``.
+ *len* must be the size of *s*.
+
+ *errors* must be one of ``"strict"``, ``"replace"``, or ``"ignore"``. If
+ *errors* is ``NULL``, then ``"strict"`` is used by default.
+
+ On success, this function returns a :term:`strong reference` to a Python
+ :class:`bytes` object containing the unescaped string. On failure, this
+ function returns ``NULL`` with an exception set.
+
+ .. versionchanged:: 3.9
+ *unicode* and *recode_encoding* are now unused.
+
+
.. _pybyteswriter:
PyBytesWriter
diff --git a/Doc/c-api/capsule.rst b/Doc/c-api/capsule.rst
index 6da020efc7f..03a848d68ed 100644
--- a/Doc/c-api/capsule.rst
+++ b/Doc/c-api/capsule.rst
@@ -22,6 +22,12 @@ Refer to :ref:`using-capsules` for more information on using these objects.
loaded modules.
+.. c:var:: PyTypeObject PyCapsule_Type
+
+ The type object corresponding to capsule objects. This is the same object
+ as :class:`types.CapsuleType` in the Python layer.
+
+
.. c:type:: PyCapsule_Destructor
The type of a destructor callback for a capsule. Defined as::
diff --git a/Doc/c-api/cell.rst b/Doc/c-api/cell.rst
index 61eb994c370..2501ed9580d 100644
--- a/Doc/c-api/cell.rst
+++ b/Doc/c-api/cell.rst
@@ -7,7 +7,7 @@ Cell Objects
"Cell" objects are used to implement variables referenced by multiple scopes.
For each such variable, a cell object is created to store the value; the local
-variables of each stack frame that references the value contains a reference to
+variables of each stack frame that references the value contain a reference to
the cells from outer scopes which also use that variable. When the value is
accessed, the value contained in the cell is used instead of the cell object
itself. This de-referencing of the cell object requires support from the
diff --git a/Doc/c-api/code.rst b/Doc/c-api/code.rst
index c9741b61254..45f5e83adc4 100644
--- a/Doc/c-api/code.rst
+++ b/Doc/c-api/code.rst
@@ -211,6 +211,17 @@ bound into a function.
.. versionadded:: 3.12
+.. c:function:: PyObject *PyCode_Optimize(PyObject *code, PyObject *consts, PyObject *names, PyObject *lnotab_obj)
+
+ This is a :term:`soft deprecated` function that does nothing.
+
+ Prior to Python 3.10, this function would perform basic optimizations to a
+ code object.
+
+ .. versionchanged:: 3.10
+ This function now does nothing.
+
+
.. _c_codeobject_flags:
Code Object Flags
diff --git a/Doc/c-api/codec.rst b/Doc/c-api/codec.rst
index 08a99245ad6..35ee048bd5f 100644
--- a/Doc/c-api/codec.rst
+++ b/Doc/c-api/codec.rst
@@ -129,3 +129,13 @@ Registry API for Unicode encoding error handlers
Replace the unicode encode error with ``\N{...}`` escapes.
.. versionadded:: 3.5
+
+
+Codec utility variables
+-----------------------
+
+.. c:var:: const char *Py_hexdigits
+
+ A string constant containing the lowercase hexadecimal digits: ``"0123456789abcdef"``.
+
+ .. versionadded:: 3.3
diff --git a/Doc/c-api/complex.rst b/Doc/c-api/complex.rst
index d135637a741..629312bd771 100644
--- a/Doc/c-api/complex.rst
+++ b/Doc/c-api/complex.rst
@@ -82,7 +82,7 @@ Complex Number Objects
.. c:type:: Py_complex
- This C structure defines export format for a Python complex
+ This C structure defines an export format for a Python complex
number object.
.. c:member:: double real
diff --git a/Doc/c-api/concrete.rst b/Doc/c-api/concrete.rst
index 880f7b15ce6..1746fe95eaa 100644
--- a/Doc/c-api/concrete.rst
+++ b/Doc/c-api/concrete.rst
@@ -109,11 +109,20 @@ Other Objects
descriptor.rst
slice.rst
memoryview.rst
+ picklebuffer.rst
weakref.rst
capsule.rst
frame.rst
gen.rst
coro.rst
contextvars.rst
- datetime.rst
typehints.rst
+
+
+C API for extension modules
+===========================
+
+.. toctree::
+
+ curses.rst
+ datetime.rst
diff --git a/Doc/c-api/conversion.rst b/Doc/c-api/conversion.rst
index cc7a3d9d956..a18bbf4e0e3 100644
--- a/Doc/c-api/conversion.rst
+++ b/Doc/c-api/conversion.rst
@@ -105,7 +105,7 @@ The following functions provide locale-independent string to number conversions.
If ``s`` represents a value that is too large to store in a float
(for example, ``"1e500"`` is such a string on many platforms) then
- if ``overflow_exception`` is ``NULL`` return ``Py_INFINITY`` (with
+ if ``overflow_exception`` is ``NULL`` return :c:macro:`!INFINITY` (with
an appropriate sign) and don't set any exception. Otherwise,
``overflow_exception`` must point to a Python exception object;
raise that exception and return ``-1.0``. In both cases, set
@@ -128,18 +128,28 @@ The following functions provide locale-independent string to number conversions.
must be 0 and is ignored. The ``'r'`` format code specifies the
standard :func:`repr` format.
- *flags* can be zero or more of the values ``Py_DTSF_SIGN``,
- ``Py_DTSF_ADD_DOT_0``, or ``Py_DTSF_ALT``, or-ed together:
+ *flags* can be zero or more of the following values or-ed together:
- * ``Py_DTSF_SIGN`` means to always precede the returned string with a sign
- character, even if *val* is non-negative.
+ .. c:macro:: Py_DTSF_SIGN
- * ``Py_DTSF_ADD_DOT_0`` means to ensure that the returned string will not look
- like an integer.
+ Always precede the returned string with a sign
+ character, even if *val* is non-negative.
- * ``Py_DTSF_ALT`` means to apply "alternate" formatting rules. See the
- documentation for the :c:func:`PyOS_snprintf` ``'#'`` specifier for
- details.
+ .. c:macro:: Py_DTSF_ADD_DOT_0
+
+ Ensure that the returned string will not look like an integer.
+
+ .. c:macro:: Py_DTSF_ALT
+
+ Apply "alternate" formatting rules.
+ See the documentation for the :c:func:`PyOS_snprintf` ``'#'`` specifier for
+ details.
+
+ .. c:macro:: Py_DTSF_NO_NEG_0
+
+ Negative zero is converted to positive zero.
+
+ .. versionadded:: 3.11
If *ptype* is non-``NULL``, then the value it points to will be set to one of
``Py_DTST_FINITE``, ``Py_DTST_INFINITE``, or ``Py_DTST_NAN``, signifying that
@@ -162,3 +172,58 @@ The following functions provide locale-independent string to number conversions.
Case insensitive comparison of strings. The function works almost
identically to :c:func:`!strncmp` except that it ignores the case.
+
+
+Character classification and conversion
+=======================================
+
+The following macros provide locale-independent (unlike the C standard library
+``ctype.h``) character classification and conversion.
+The argument must be a signed or unsigned :c:expr:`char`.
+
+
+.. c:macro:: Py_ISALNUM(c)
+
+ Return true if the character *c* is an alphanumeric character.
+
+
+.. c:macro:: Py_ISALPHA(c)
+
+ Return true if the character *c* is an alphabetic character (``a-z`` and ``A-Z``).
+
+
+.. c:macro:: Py_ISDIGIT(c)
+
+ Return true if the character *c* is a decimal digit (``0-9``).
+
+
+.. c:macro:: Py_ISLOWER(c)
+
+ Return true if the character *c* is a lowercase ASCII letter (``a-z``).
+
+
+.. c:macro:: Py_ISUPPER(c)
+
+ Return true if the character *c* is an uppercase ASCII letter (``A-Z``).
+
+
+.. c:macro:: Py_ISSPACE(c)
+
+ Return true if the character *c* is a whitespace character (space, tab,
+ carriage return, newline, vertical tab, or form feed).
+
+
+.. c:macro:: Py_ISXDIGIT(c)
+
+ Return true if the character *c* is a hexadecimal digit (``0-9``, ``a-f``, and
+ ``A-F``).
+
+
+.. c:macro:: Py_TOLOWER(c)
+
+ Return the lowercase equivalent of the character *c*.
+
+
+.. c:macro:: Py_TOUPPER(c)
+
+ Return the uppercase equivalent of the character *c*.
diff --git a/Doc/c-api/curses.rst b/Doc/c-api/curses.rst
new file mode 100644
index 00000000000..5a1697c43cc
--- /dev/null
+++ b/Doc/c-api/curses.rst
@@ -0,0 +1,138 @@
+.. highlight:: c
+
+Curses C API
+------------
+
+:mod:`curses` exposes a small C interface for extension modules.
+Consumers must include the header file :file:`py_curses.h` (which is not
+included by default by :file:`Python.h`) and :c:func:`import_curses` must
+be invoked, usually as part of the module initialisation function, to populate
+:c:var:`PyCurses_API`.
+
+.. warning::
+
+ Neither the C API nor the pure Python :mod:`curses` module are compatible
+ with subinterpreters.
+
+.. c:macro:: import_curses()
+
+ Import the curses C API. The macro does not need a semi-colon to be called.
+
+ On success, populate the :c:var:`PyCurses_API` pointer.
+
+ On failure, set :c:var:`PyCurses_API` to NULL and set an exception.
+ The caller must check if an error occurred via :c:func:`PyErr_Occurred`:
+
+ .. code-block::
+
+ import_curses(); // semi-colon is optional but recommended
+ if (PyErr_Occurred()) { /* cleanup */ }
+
+
+.. c:var:: void **PyCurses_API
+
+ Dynamically allocated object containing the curses C API.
+ This variable is only available once :c:macro:`import_curses` succeeds.
+
+ ``PyCurses_API[0]`` corresponds to :c:data:`PyCursesWindow_Type`.
+
+ ``PyCurses_API[1]``, ``PyCurses_API[2]``, and ``PyCurses_API[3]``
+ are pointers to predicate functions of type ``int (*)(void)``.
+
+ When called, these predicates return whether :func:`curses.setupterm`,
+ :func:`curses.initscr`, and :func:`curses.start_color` have been called
+ respectively.
+
+ See also the convenience macros :c:macro:`PyCursesSetupTermCalled`,
+ :c:macro:`PyCursesInitialised`, and :c:macro:`PyCursesInitialisedColor`.
+
+ .. note::
+
+ The number of entries in this structure is subject to changes.
+ Consider using :c:macro:`PyCurses_API_pointers` to check if
+ new fields are available or not.
+
+
+.. c:macro:: PyCurses_API_pointers
+
+ The number of accessible fields (``4``) in :c:var:`PyCurses_API`.
+ This number is incremented whenever new fields are added.
+
+
+.. c:var:: PyTypeObject PyCursesWindow_Type
+
+ The :ref:`heap type ` corresponding to :class:`curses.window`.
+
+
+.. c:function:: int PyCursesWindow_Check(PyObject *op)
+
+ Return true if *op* is a :class:`curses.window` instance, false otherwise.
+
+
+The following macros are convenience macros expanding into C statements.
+In particular, they can only be used as ``macro;`` or ``macro``, but not
+``macro()`` or ``macro();``.
+
+.. c:macro:: PyCursesSetupTermCalled
+
+ Macro checking if :func:`curses.setupterm` has been called.
+
+ The macro expansion is roughly equivalent to:
+
+ .. code-block::
+
+ {
+ typedef int (*predicate_t)(void);
+ predicate_t was_setupterm_called = (predicate_t)PyCurses_API[1];
+ if (!was_setupterm_called()) {
+ return NULL;
+ }
+ }
+
+
+.. c:macro:: PyCursesInitialised
+
+ Macro checking if :func:`curses.initscr` has been called.
+
+ The macro expansion is roughly equivalent to:
+
+ .. code-block::
+
+ {
+ typedef int (*predicate_t)(void);
+ predicate_t was_initscr_called = (predicate_t)PyCurses_API[2];
+ if (!was_initscr_called()) {
+ return NULL;
+ }
+ }
+
+
+.. c:macro:: PyCursesInitialisedColor
+
+ Macro checking if :func:`curses.start_color` has been called.
+
+ The macro expansion is roughly equivalent to:
+
+ .. code-block::
+
+ {
+ typedef int (*predicate_t)(void);
+ predicate_t was_start_color_called = (predicate_t)PyCurses_API[3];
+ if (!was_start_color_called()) {
+ return NULL;
+ }
+ }
+
+
+Internal data
+-------------
+
+The following objects are exposed by the C API but should be considered
+internal-only.
+
+.. c:macro:: PyCurses_CAPSULE_NAME
+
+ Name of the curses capsule to pass to :c:func:`PyCapsule_Import`.
+
+ Internal usage only. Use :c:macro:`import_curses` instead.
+
diff --git a/Doc/c-api/datetime.rst b/Doc/c-api/datetime.rst
index d2d4d5309c7..127d7c9c91a 100644
--- a/Doc/c-api/datetime.rst
+++ b/Doc/c-api/datetime.rst
@@ -8,11 +8,42 @@ DateTime Objects
Various date and time objects are supplied by the :mod:`datetime` module.
Before using any of these functions, the header file :file:`datetime.h` must be
included in your source (note that this is not included by :file:`Python.h`),
-and the macro :c:macro:`!PyDateTime_IMPORT` must be invoked, usually as part of
+and the macro :c:macro:`PyDateTime_IMPORT` must be invoked, usually as part of
the module initialisation function. The macro puts a pointer to a C structure
-into a static variable, :c:data:`!PyDateTimeAPI`, that is used by the following
+into a static variable, :c:data:`PyDateTimeAPI`, that is used by the following
macros.
+.. c:macro:: PyDateTime_IMPORT()
+
+ Import the datetime C API.
+
+ On success, populate the :c:var:`PyDateTimeAPI` pointer.
+ On failure, set :c:var:`PyDateTimeAPI` to ``NULL`` and set an exception.
+ The caller must check if an error occurred via :c:func:`PyErr_Occurred`:
+
+ .. code-block::
+
+ PyDateTime_IMPORT;
+ if (PyErr_Occurred()) { /* cleanup */ }
+
+ .. warning::
+
+ This is not compatible with subinterpreters.
+
+.. c:type:: PyDateTime_CAPI
+
+ Structure containing the fields for the datetime C API.
+
+ The fields of this structure are private and subject to change.
+
+ Do not use this directly; prefer ``PyDateTime_*`` APIs instead.
+
+.. c:var:: PyDateTime_CAPI *PyDateTimeAPI
+
+ Dynamically allocated object containing the datetime C API.
+
+ This variable is only available once :c:macro:`PyDateTime_IMPORT` succeeds.
+
.. c:type:: PyDateTime_Date
This subtype of :c:type:`PyObject` represents a Python date object.
@@ -46,7 +77,7 @@ macros.
.. c:var:: PyTypeObject PyDateTime_DeltaType
- This instance of :c:type:`PyTypeObject` represents Python type for
+ This instance of :c:type:`PyTypeObject` represents the Python type for
the difference between two datetime values;
it is the same object as :class:`datetime.timedelta` in the Python layer.
@@ -325,3 +356,16 @@ Macros for the convenience of modules implementing the DB API:
Create and return a new :class:`datetime.date` object given an argument
tuple suitable for passing to :meth:`datetime.date.fromtimestamp`.
+
+
+Internal data
+-------------
+
+The following symbols are exposed by the C API but should be considered
+internal-only.
+
+.. c:macro:: PyDateTime_CAPSULE_NAME
+
+ Name of the datetime capsule to pass to :c:func:`PyCapsule_Import`.
+
+ Internal usage only. Use :c:macro:`PyDateTime_IMPORT` instead.
diff --git a/Doc/c-api/descriptor.rst b/Doc/c-api/descriptor.rst
index b32c113e5f0..22c3b790cc3 100644
--- a/Doc/c-api/descriptor.rst
+++ b/Doc/c-api/descriptor.rst
@@ -32,9 +32,51 @@ found in the dictionary of type objects.
.. c:function:: int PyDescr_IsData(PyObject *descr)
- Return non-zero if the descriptor objects *descr* describes a data attribute, or
+ Return non-zero if the descriptor object *descr* describes a data attribute, or
``0`` if it describes a method. *descr* must be a descriptor object; there is
no error checking.
.. c:function:: PyObject* PyWrapper_New(PyObject *, PyObject *)
+
+
+Built-in descriptors
+^^^^^^^^^^^^^^^^^^^^
+
+.. c:var:: PyTypeObject PySuper_Type
+
+ The type object for super objects. This is the same object as
+ :class:`super` in the Python layer.
+
+
+.. c:var:: PyTypeObject PyClassMethod_Type
+
+ The type of class method objects. This is the same object as
+ :class:`classmethod` in the Python layer.
+
+
+.. c:function:: PyObject *PyClassMethod_New(PyObject *callable)
+
+ Create a new :class:`classmethod` object wrapping *callable*.
+ *callable* must be a callable object and must not be ``NULL``.
+
+ On success, this function returns a :term:`strong reference` to a new class
+ method descriptor. On failure, this function returns ``NULL`` with an
+ exception set.
+
+
+.. c:var:: PyTypeObject PyStaticMethod_Type
+
+ The type of static method objects. This is the same object as
+ :class:`staticmethod` in the Python layer.
+
+
+.. c:function:: PyObject *PyStaticMethod_New(PyObject *callable)
+
+ Create a new :class:`staticmethod` object wrapping *callable*.
+ *callable* must be a callable object and must not be ``NULL``.
+
+ On success, this function returns a :term:`strong reference` to a new static
+ method descriptor. On failure, this function returns ``NULL`` with an
+ exception set.
+
diff --git a/Doc/c-api/dict.rst b/Doc/c-api/dict.rst
index 0abbd662dad..ede1699cfeb 100644
--- a/Doc/c-api/dict.rst
+++ b/Doc/c-api/dict.rst
@@ -245,6 +245,11 @@ Dictionary Objects
``len(p)`` on a dictionary.
+.. c:function:: Py_ssize_t PyDict_GET_SIZE(PyObject *p)
+
+ Similar to :c:func:`PyDict_Size`, but without error checking.
+
+
.. c:function:: int PyDict_Next(PyObject *p, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue)
Iterate over all key-value pairs in the dictionary *p*. The
@@ -426,3 +431,138 @@ Dictionary Objects
it before returning.
.. versionadded:: 3.12
+
+
+Dictionary View Objects
+^^^^^^^^^^^^^^^^^^^^^^^
+
+.. c:function:: int PyDictViewSet_Check(PyObject *op)
+
+ Return true if *op* is a view of a set inside a dictionary. This is currently
+ equivalent to :c:expr:`PyDictKeys_Check(op) || PyDictItems_Check(op)`. This
+ function always succeeds.
+
+
+.. c:var:: PyTypeObject PyDictKeys_Type
+
+ Type object for a view of dictionary keys. In Python, this is the type of
+ the object returned by :meth:`dict.keys`.
+
+
+.. c:function:: int PyDictKeys_Check(PyObject *op)
+
+ Return true if *op* is an instance of a dictionary keys view. This function
+ always succeeds.
+
+
+.. c:var:: PyTypeObject PyDictValues_Type
+
+ Type object for a view of dictionary values. In Python, this is the type of
+ the object returned by :meth:`dict.values`.
+
+
+.. c:function:: int PyDictValues_Check(PyObject *op)
+
+ Return true if *op* is an instance of a dictionary values view. This function
+ always succeeds.
+
+
+.. c:var:: PyTypeObject PyDictItems_Type
+
+ Type object for a view of dictionary items. In Python, this is the type of
+ the object returned by :meth:`dict.items`.
+
+
+.. c:function:: int PyDictItems_Check(PyObject *op)
+
+ Return true if *op* is an instance of a dictionary items view. This function
+ always succeeds.
+
+
+Ordered Dictionaries
+^^^^^^^^^^^^^^^^^^^^
+
+Python's C API provides interface for :class:`collections.OrderedDict` from C.
+Since Python 3.7, dictionaries are ordered by default, so there is usually
+little need for these functions; prefer ``PyDict*`` where possible.
+
+
+.. c:var:: PyTypeObject PyODict_Type
+
+ Type object for ordered dictionaries. This is the same object as
+ :class:`collections.OrderedDict` in the Python layer.
+
+
+.. c:function:: int PyODict_Check(PyObject *od)
+
+ Return true if *od* is an ordered dictionary object or an instance of a
+ subtype of the :class:`~collections.OrderedDict` type. This function
+ always succeeds.
+
+
+.. c:function:: int PyODict_CheckExact(PyObject *od)
+
+ Return true if *od* is an ordered dictionary object, but not an instance of
+ a subtype of the :class:`~collections.OrderedDict` type.
+ This function always succeeds.
+
+
+.. c:var:: PyTypeObject PyODictKeys_Type
+
+ Analogous to :c:type:`PyDictKeys_Type` for ordered dictionaries.
+
+
+.. c:var:: PyTypeObject PyODictValues_Type
+
+ Analogous to :c:type:`PyDictValues_Type` for ordered dictionaries.
+
+
+.. c:var:: PyTypeObject PyODictItems_Type
+
+ Analogous to :c:type:`PyDictItems_Type` for ordered dictionaries.
+
+
+.. c:function:: PyObject *PyODict_New(void)
+
+ Return a new empty ordered dictionary, or ``NULL`` on failure.
+
+ This is analogous to :c:func:`PyDict_New`.
+
+
+.. c:function:: int PyODict_SetItem(PyObject *od, PyObject *key, PyObject *value)
+
+ Insert *value* into the ordered dictionary *od* with a key of *key*.
+ Return ``0`` on success or ``-1`` with an exception set on failure.
+
+ This is analogous to :c:func:`PyDict_SetItem`.
+
+
+.. c:function:: int PyODict_DelItem(PyObject *od, PyObject *key)
+
+ Remove the entry in the ordered dictionary *od* with key *key*.
+ Return ``0`` on success or ``-1`` with an exception set on failure.
+
+ This is analogous to :c:func:`PyDict_DelItem`.
+
+
+These are :term:`soft deprecated` aliases to ``PyDict`` APIs:
+
+
+.. list-table::
+ :widths: auto
+ :header-rows: 1
+
+ * * ``PyODict``
+ * ``PyDict``
+ * * .. c:macro:: PyODict_GetItem(od, key)
+ * :c:func:`PyDict_GetItem`
+ * * .. c:macro:: PyODict_GetItemWithError(od, key)
+ * :c:func:`PyDict_GetItemWithError`
+ * * .. c:macro:: PyODict_GetItemString(od, key)
+ * :c:func:`PyDict_GetItemString`
+ * * .. c:macro:: PyODict_Contains(od, key)
+ * :c:func:`PyDict_Contains`
+ * * .. c:macro:: PyODict_Size(od)
+ * :c:func:`PyDict_Size`
+ * * .. c:macro:: PyODict_SIZE(od)
+ * :c:func:`PyDict_GET_SIZE`
diff --git a/Doc/c-api/exceptions.rst b/Doc/c-api/exceptions.rst
index 3ff4631a8e5..d7fe9e2c9ec 100644
--- a/Doc/c-api/exceptions.rst
+++ b/Doc/c-api/exceptions.rst
@@ -309,6 +309,14 @@ For convenience, some of these functions will always return a
.. versionadded:: 3.4
+.. c:function:: void PyErr_RangedSyntaxLocationObject(PyObject *filename, int lineno, int col_offset, int end_lineno, int end_col_offset)
+
+ Similar to :c:func:`PyErr_SyntaxLocationObject`, but also sets the
+ *end_lineno* and *end_col_offset* information for the current exception.
+
+ .. versionadded:: 3.10
+
+
.. c:function:: void PyErr_SyntaxLocationEx(const char *filename, int lineno, int col_offset)
Like :c:func:`PyErr_SyntaxLocationObject`, but *filename* is a byte string
@@ -331,6 +339,23 @@ For convenience, some of these functions will always return a
use.
+.. c:function:: PyObject *PyErr_ProgramTextObject(PyObject *filename, int lineno)
+
+ Get the source line in *filename* at line *lineno*. *filename* should be a
+ Python :class:`str` object.
+
+ On success, this function returns a Python string object with the found line.
+ On failure, this function returns ``NULL`` without an exception set.
+
+
+.. c:function:: PyObject *PyErr_ProgramText(const char *filename, int lineno)
+
+ Similar to :c:func:`PyErr_ProgramTextObject`, but *filename* is a
+ :c:expr:`const char *`, which is decoded with the
+ :term:`filesystem encoding and error handler`, instead of a
+ Python object reference.
+
+
Issuing warnings
================
@@ -394,6 +419,15 @@ an error value).
.. versionadded:: 3.2
+.. c:function:: int PyErr_WarnExplicitFormat(PyObject *category, const char *filename, int lineno, const char *module, PyObject *registry, const char *format, ...)
+
+ Similar to :c:func:`PyErr_WarnExplicit`, but uses
+ :c:func:`PyUnicode_FromFormat` to format the warning message. *format* is
+ an ASCII-encoded string.
+
+ .. versionadded:: 3.2
+
+
.. c:function:: int PyErr_ResourceWarning(PyObject *source, Py_ssize_t stack_level, const char *format, ...)
Function similar to :c:func:`PyErr_WarnFormat`, but *category* is
@@ -762,6 +796,17 @@ Exception Classes
Exception Objects
=================
+.. c:function:: int PyExceptionInstance_Check(PyObject *op)
+
+ Return true if *op* is an instance of :class:`BaseException`, false
+ otherwise. This function always succeeds.
+
+
+.. c:macro:: PyExceptionInstance_Class(op)
+
+ Equivalent to :c:func:`Py_TYPE(op) `.
+
+
.. c:function:: PyObject* PyException_GetTraceback(PyObject *ex)
Return the traceback associated with the exception as a new reference, as
@@ -939,6 +984,9 @@ because the :ref:`call protocol ` takes care of recursion handling.
be concatenated to the :exc:`RecursionError` message caused by the recursion
depth limit.
+ .. seealso::
+ The :c:func:`PyUnstable_ThreadState_SetStackProtection` function.
+
.. versionchanged:: 3.9
This function is now also available in the :ref:`limited API `.
@@ -979,6 +1027,27 @@ these are the C equivalent to :func:`reprlib.recursive_repr`.
Ends a :c:func:`Py_ReprEnter`. Must be called once for each
invocation of :c:func:`Py_ReprEnter` that returns zero.
+.. c:function:: int Py_GetRecursionLimit(void)
+
+ Get the recursion limit for the current interpreter. It can be set with
+ :c:func:`Py_SetRecursionLimit`. The recursion limit prevents the
+ Python interpreter stack from growing infinitely.
+
+ This function cannot fail, and the caller must hold an
+ :term:`attached thread state`.
+
+ .. seealso::
+ :py:func:`sys.getrecursionlimit`
+
+.. c:function:: void Py_SetRecursionLimit(int new_limit)
+
+ Set the recursion limit for the current interpreter.
+
+ This function cannot fail, and the caller must hold an
+ :term:`attached thread state`.
+
+ .. seealso::
+ :py:func:`sys.setrecursionlimit`
.. _standardexceptions:
@@ -1207,3 +1276,37 @@ Warning types
.. versionadded:: 3.10
:c:data:`PyExc_EncodingWarning`.
+
+
+Tracebacks
+==========
+
+.. c:var:: PyTypeObject PyTraceBack_Type
+
+ Type object for traceback objects. This is available as
+ :class:`types.TracebackType` in the Python layer.
+
+
+.. c:function:: int PyTraceBack_Check(PyObject *op)
+
+ Return true if *op* is a traceback object, false otherwise. This function
+ does not account for subtypes.
+
+
+.. c:function:: int PyTraceBack_Here(PyFrameObject *f)
+
+ Replace the :attr:`~BaseException.__traceback__` attribute on the current
+ exception with a new traceback prepending *f* to the existing chain.
+
+ Calling this function without an exception set is undefined behavior.
+
+ This function returns ``0`` on success, and returns ``-1`` with an
+ exception set on failure.
+
+
+.. c:function:: int PyTraceBack_Print(PyObject *tb, PyObject *f)
+
+ Write the traceback *tb* into the file *f*.
+
+ This function returns ``0`` on success, and returns ``-1`` with an
+ exception set on failure.
diff --git a/Doc/c-api/file.rst b/Doc/c-api/file.rst
index e9019a0d500..9d01254ddb2 100644
--- a/Doc/c-api/file.rst
+++ b/Doc/c-api/file.rst
@@ -93,6 +93,29 @@ the :mod:`io` APIs instead.
.. versionadded:: 3.8
+.. c:function:: PyObject *PyFile_OpenCodeObject(PyObject *path)
+
+ Open *path* with the mode ``'rb'``. *path* must be a Python :class:`str`
+ object. The behavior of this function may be overridden by
+ :c:func:`PyFile_SetOpenCodeHook` to allow for some preprocessing of the
+ text.
+
+ This is analogous to :func:`io.open_code` in Python.
+
+ On success, this function returns a :term:`strong reference` to a Python
+ file object. On failure, this function returns ``NULL`` with an exception
+ set.
+
+ .. versionadded:: 3.8
+
+
+.. c:function:: PyObject *PyFile_OpenCode(const char *path)
+
+ Similar to :c:func:`PyFile_OpenCodeObject`, but *path* is a
+ UTF-8 encoded :c:expr:`const char*`.
+
+ .. versionadded:: 3.8
+
.. c:function:: int PyFile_WriteObject(PyObject *obj, PyObject *p, int flags)
diff --git a/Doc/c-api/float.rst b/Doc/c-api/float.rst
index 489676caa3a..b0d440580b9 100644
--- a/Doc/c-api/float.rst
+++ b/Doc/c-api/float.rst
@@ -78,6 +78,111 @@ Floating-Point Objects
Return the minimum normalized positive float *DBL_MIN* as C :c:expr:`double`.
+.. c:macro:: Py_INFINITY
+
+ This macro expands a to constant expression of type :c:expr:`double`, that
+ represents the positive infinity.
+
+ It is equivalent to the :c:macro:`!INFINITY` macro from the C11 standard
+ ```` header.
+
+ .. deprecated:: 3.15
+ The macro is :term:`soft deprecated`.
+
+
+.. c:macro:: Py_NAN
+
+ This macro expands a to constant expression of type :c:expr:`double`, that
+ represents a quiet not-a-number (qNaN) value.
+
+ On most platforms, this is equivalent to the :c:macro:`!NAN` macro from
+ the C11 standard ```` header.
+
+
+.. c:macro:: Py_HUGE_VAL
+
+ Equivalent to :c:macro:`!INFINITY`.
+
+ .. deprecated:: 3.14
+ The macro is :term:`soft deprecated`.
+
+
+.. c:macro:: Py_MATH_E
+
+ The definition (accurate for a :c:expr:`double` type) of the :data:`math.e` constant.
+
+
+.. c:macro:: Py_MATH_El
+
+ High precision (long double) definition of :data:`~math.e` constant.
+
+ .. deprecated-removed:: 3.15 3.20
+
+
+.. c:macro:: Py_MATH_PI
+
+ The definition (accurate for a :c:expr:`double` type) of the :data:`math.pi` constant.
+
+
+.. c:macro:: Py_MATH_PIl
+
+ High precision (long double) definition of :data:`~math.pi` constant.
+
+ .. deprecated-removed:: 3.15 3.20
+
+
+.. c:macro:: Py_MATH_TAU
+
+ The definition (accurate for a :c:expr:`double` type) of the :data:`math.tau` constant.
+
+ .. versionadded:: 3.6
+
+
+.. c:macro:: Py_RETURN_NAN
+
+ Return :data:`math.nan` from a function.
+
+ On most platforms, this is equivalent to ``return PyFloat_FromDouble(NAN)``.
+
+
+.. c:macro:: Py_RETURN_INF(sign)
+
+ Return :data:`math.inf` or :data:`-math.inf ` from a function,
+ depending on the sign of *sign*.
+
+ On most platforms, this is equivalent to the following::
+
+ return PyFloat_FromDouble(copysign(INFINITY, sign));
+
+
+.. c:macro:: Py_IS_FINITE(X)
+
+ Return ``1`` if the given floating-point number *X* is finite,
+ that is, it is normal, subnormal or zero, but not infinite or NaN.
+ Return ``0`` otherwise.
+
+ .. deprecated:: 3.14
+ The macro is :term:`soft deprecated`. Use :c:macro:`!isfinite` instead.
+
+
+.. c:macro:: Py_IS_INFINITY(X)
+
+ Return ``1`` if the given floating-point number *X* is positive or negative
+ infinity. Return ``0`` otherwise.
+
+ .. deprecated:: 3.14
+ The macro is :term:`soft deprecated`. Use :c:macro:`!isinf` instead.
+
+
+.. c:macro:: Py_IS_NAN(X)
+
+ Return ``1`` if the given floating-point number *X* is a not-a-number (NaN)
+ value. Return ``0`` otherwise.
+
+ .. deprecated:: 3.14
+ The macro is :term:`soft deprecated`. Use :c:macro:`!isnan` instead.
+
+
Pack and Unpack functions
-------------------------
@@ -96,8 +201,8 @@ NaNs (if such things exist on the platform) isn't handled correctly, and
attempting to unpack a bytes string containing an IEEE INF or NaN will raise an
exception.
-Note that NaNs type may not be preserved on IEEE platforms (silent NaN become
-quiet), for example on x86 systems in 32-bit mode.
+Note that NaNs type may not be preserved on IEEE platforms (signaling NaN become
+quiet NaN), for example on x86 systems in 32-bit mode.
On non-IEEE platforms with more precision, or larger dynamic range, than IEEE
754 supports, not all values can be packed; on non-IEEE platforms with less
diff --git a/Doc/c-api/frame.rst b/Doc/c-api/frame.rst
index 1a52e146a69..fb17cf7f1da 100644
--- a/Doc/c-api/frame.rst
+++ b/Doc/c-api/frame.rst
@@ -29,6 +29,12 @@ See also :ref:`Reflection `.
Previously, this type was only available after including
````.
+.. c:function:: PyFrameObject *PyFrame_New(PyThreadState *tstate, PyCodeObject *code, PyObject *globals, PyObject *locals)
+
+ Create a new frame object. This function returns a :term:`strong reference`
+ to the new frame object on success, and returns ``NULL`` with an exception
+ set on failure.
+
.. c:function:: int PyFrame_Check(PyObject *obj)
Return non-zero if *obj* is a frame object.
@@ -161,6 +167,57 @@ See :pep:`667` for more information.
Return non-zero if *obj* is a frame :func:`locals` proxy.
+
+Legacy Local Variable APIs
+^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+These APIs are :term:`soft deprecated`. As of Python 3.13, they do nothing.
+They exist solely for backwards compatibility.
+
+
+.. c:function:: void PyFrame_LocalsToFast(PyFrameObject *f, int clear)
+
+ This function is :term:`soft deprecated` and does nothing.
+
+ Prior to Python 3.13, this function would copy the :attr:`~frame.f_locals`
+ attribute of *f* to the internal "fast" array of local variables, allowing
+ changes in frame objects to be visible to the interpreter. If *clear* was
+ true, this function would process variables that were unset in the locals
+ dictionary.
+
+ .. versionchanged:: 3.13
+ This function now does nothing.
+
+
+.. c:function:: void PyFrame_FastToLocals(PyFrameObject *f)
+
+ This function is :term:`soft deprecated` and does nothing.
+
+ Prior to Python 3.13, this function would copy the internal "fast" array
+ of local variables (which is used by the interpreter) to the
+ :attr:`~frame.f_locals` attribute of *f*, allowing changes in local
+ variables to be visible to frame objects.
+
+ .. versionchanged:: 3.13
+ This function now does nothing.
+
+
+.. c:function:: int PyFrame_FastToLocalsWithError(PyFrameObject *f)
+
+ This function is :term:`soft deprecated` and does nothing.
+
+ Prior to Python 3.13, this function was similar to
+ :c:func:`PyFrame_FastToLocals`, but would return ``0`` on success, and
+ ``-1`` with an exception set on failure.
+
+ .. versionchanged:: 3.13
+ This function now does nothing.
+
+
+.. seealso::
+ :pep:`667`
+
+
Internal Frames
^^^^^^^^^^^^^^^
diff --git a/Doc/c-api/function.rst b/Doc/c-api/function.rst
index 764b2ac610b..609b5e885b6 100644
--- a/Doc/c-api/function.rst
+++ b/Doc/c-api/function.rst
@@ -102,6 +102,15 @@ There are a few functions specific to Python functions.
dictionary of arguments or ``NULL``.
+.. c:function:: int PyFunction_SetKwDefaults(PyObject *op, PyObject *defaults)
+
+ Set the keyword-only argument default values of the function object *op*.
+ *defaults* must be a dictionary of keyword-only arguments or ``Py_None``.
+
+ This function returns ``0`` on success, and returns ``-1`` with an exception
+ set on failure.
+
+
.. c:function:: PyObject* PyFunction_GetClosure(PyObject *op)
Return the closure associated with the function object *op*. This can be ``NULL``
@@ -200,7 +209,7 @@ There are a few functions specific to Python functions.
runtime behavior depending on optimization decisions, it does not change
the semantics of the Python code being executed.
- If *event* is ``PyFunction_EVENT_DESTROY``, Taking a reference in the
+ If *event* is ``PyFunction_EVENT_DESTROY``, taking a reference in the
callback to the about-to-be-destroyed function will resurrect it, preventing
it from being freed at this time. When the resurrected object is destroyed
later, any watcher callbacks active at that time will be called again.
diff --git a/Doc/c-api/gen.rst b/Doc/c-api/gen.rst
index 0eb5922f6da..44f3bdbf959 100644
--- a/Doc/c-api/gen.rst
+++ b/Doc/c-api/gen.rst
@@ -44,3 +44,41 @@ than explicitly calling :c:func:`PyGen_New` or :c:func:`PyGen_NewWithQualName`.
with ``__name__`` and ``__qualname__`` set to *name* and *qualname*.
A reference to *frame* is stolen by this function. The *frame* argument
must not be ``NULL``.
+
+.. c:function:: PyCodeObject* PyGen_GetCode(PyGenObject *gen)
+
+ Return a new :term:`strong reference` to the code object wrapped by *gen*.
+ This function always succeeds.
+
+
+Asynchronous Generator Objects
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+.. seealso::
+ :pep:`525`
+
+.. c:var:: PyTypeObject PyAsyncGen_Type
+
+ The type object corresponding to asynchronous generator objects. This is
+ available as :class:`types.AsyncGeneratorType` in the Python layer.
+
+ .. versionadded:: 3.6
+
+.. c:function:: PyObject *PyAsyncGen_New(PyFrameObject *frame, PyObject *name, PyObject *qualname)
+
+ Create a new asynchronous generator wrapping *frame*, with ``__name__`` and
+ ``__qualname__`` set to *name* and *qualname*. *frame* is stolen by this
+ function and must not be ``NULL``.
+
+ On success, this function returns a :term:`strong reference` to the
+ new asynchronous generator. On failure, this function returns ``NULL``
+ with an exception set.
+
+ .. versionadded:: 3.6
+
+.. c:function:: int PyAsyncGen_CheckExact(PyObject *op)
+
+ Return true if *op* is an asynchronous generator object, false otherwise.
+ This function always succeeds.
+
+ .. versionadded:: 3.6
diff --git a/Doc/c-api/hash.rst b/Doc/c-api/hash.rst
index b5fe93573a1..1ad712b0ce4 100644
--- a/Doc/c-api/hash.rst
+++ b/Doc/c-api/hash.rst
@@ -11,42 +11,98 @@ See also the :c:member:`PyTypeObject.tp_hash` member and :ref:`numeric-hash`.
.. versionadded:: 3.2
+
.. c:type:: Py_uhash_t
Hash value type: unsigned integer.
.. versionadded:: 3.2
+
+.. c:macro:: Py_HASH_ALGORITHM
+
+ A numerical value indicating the algorithm for hashing of :class:`str`,
+ :class:`bytes`, and :class:`memoryview`.
+
+ The algorithm name is exposed by :data:`sys.hash_info.algorithm`.
+
+ .. versionadded:: 3.4
+
+
+.. c:macro:: Py_HASH_FNV
+ Py_HASH_SIPHASH24
+ Py_HASH_SIPHASH13
+
+ Numerical values to compare to :c:macro:`Py_HASH_ALGORITHM` to determine
+ which algorithm is used for hashing. The hash algorithm can be configured
+ via the configure :option:`--with-hash-algorithm` option.
+
+ .. versionadded:: 3.4
+ Add :c:macro:`!Py_HASH_FNV` and :c:macro:`!Py_HASH_SIPHASH24`.
+
+ .. versionadded:: 3.11
+ Add :c:macro:`!Py_HASH_SIPHASH13`.
+
+
+.. c:macro:: Py_HASH_CUTOFF
+
+ Buffers of length in range ``[1, Py_HASH_CUTOFF)`` are hashed using DJBX33A
+ instead of the algorithm described by :c:macro:`Py_HASH_ALGORITHM`.
+
+ - A :c:macro:`!Py_HASH_CUTOFF` of 0 disables the optimization.
+ - :c:macro:`!Py_HASH_CUTOFF` must be non-negative and less or equal than 7.
+
+ 32-bit platforms should use a cutoff smaller than 64-bit platforms because
+ it is easier to create colliding strings. A cutoff of 7 on 64-bit platforms
+ and 5 on 32-bit platforms should provide a decent safety margin.
+
+ This corresponds to the :data:`sys.hash_info.cutoff` constant.
+
+ .. versionadded:: 3.4
+
+
.. c:macro:: PyHASH_MODULUS
- The `Mersenne prime `_ ``P = 2**n -1``, used for numeric hash scheme.
+ The `Mersenne prime `_ ``P = 2**n -1``,
+ used for numeric hash scheme.
+
+ This corresponds to the :data:`sys.hash_info.modulus` constant.
.. versionadded:: 3.13
+
.. c:macro:: PyHASH_BITS
The exponent ``n`` of ``P`` in :c:macro:`PyHASH_MODULUS`.
.. versionadded:: 3.13
+
.. c:macro:: PyHASH_MULTIPLIER
Prime multiplier used in string and various other hashes.
.. versionadded:: 3.13
+
.. c:macro:: PyHASH_INF
The hash value returned for a positive infinity.
+ This corresponds to the :data:`sys.hash_info.inf` constant.
+
.. versionadded:: 3.13
+
.. c:macro:: PyHASH_IMAG
The multiplier used for the imaginary part of a complex number.
+ This corresponds to the :data:`sys.hash_info.imag` constant.
+
.. versionadded:: 3.13
+
.. c:type:: PyHash_FuncDef
Hash function definition used by :c:func:`PyHash_GetFuncDef`.
@@ -59,14 +115,20 @@ See also the :c:member:`PyTypeObject.tp_hash` member and :ref:`numeric-hash`.
Hash function name (UTF-8 encoded string).
+ This corresponds to the :data:`sys.hash_info.algorithm` constant.
+
.. c:member:: const int hash_bits
Internal size of the hash value in bits.
+ This corresponds to the :data:`sys.hash_info.hash_bits` constant.
+
.. c:member:: const int seed_bits
Size of seed input in bits.
+ This corresponds to the :data:`sys.hash_info.seed_bits` constant.
+
.. versionadded:: 3.4
diff --git a/Doc/c-api/import.rst b/Doc/c-api/import.rst
index 8eabc0406b1..971c6a69e5d 100644
--- a/Doc/c-api/import.rst
+++ b/Doc/c-api/import.rst
@@ -333,3 +333,24 @@ Importing Modules
strings instead of Python :class:`str` objects.
.. versionadded:: 3.14
+
+.. c:function:: PyObject* PyImport_CreateModuleFromInitfunc(PyObject *spec, PyObject* (*initfunc)(void))
+
+ This function is a building block that enables embedders to implement
+ the :py:meth:`~importlib.abc.Loader.create_module` step of custom
+ static extension importers (e.g. of statically-linked extensions).
+
+ *spec* must be a :class:`~importlib.machinery.ModuleSpec` object.
+
+ *initfunc* must be an :ref:`initialization function `,
+ the same as for :c:func:`PyImport_AppendInittab`.
+
+ On success, create and return a module object.
+ This module will not be initialized; call :c:func:`!PyModule_Exec`
+ to initialize it.
+ (Custom importers should do this in their
+ :py:meth:`~importlib.abc.Loader.exec_module` method.)
+
+ On error, return NULL with an exception set.
+
+ .. versionadded:: 3.15
diff --git a/Doc/c-api/init.rst b/Doc/c-api/init.rst
index 49ffeab5585..4a841c9e3c8 100644
--- a/Doc/c-api/init.rst
+++ b/Doc/c-api/init.rst
@@ -1366,6 +1366,43 @@ All of the following functions must be called after :c:func:`Py_Initialize`.
.. versionadded:: 3.11
+.. c:function:: int PyUnstable_ThreadState_SetStackProtection(PyThreadState *tstate, void *stack_start_addr, size_t stack_size)
+
+ Set the stack protection start address and stack protection size
+ of a Python thread state.
+
+ On success, return ``0``.
+ On failure, set an exception and return ``-1``.
+
+ CPython implements :ref:`recursion control ` for C code by raising
+ :py:exc:`RecursionError` when it notices that the machine execution stack is close
+ to overflow. See for example the :c:func:`Py_EnterRecursiveCall` function.
+ For this, it needs to know the location of the current thread's stack, which it
+ normally gets from the operating system.
+ When the stack is changed, for example using context switching techniques like the
+ Boost library's ``boost::context``, you must call
+ :c:func:`~PyUnstable_ThreadState_SetStackProtection` to inform CPython of the change.
+
+ Call :c:func:`~PyUnstable_ThreadState_SetStackProtection` either before
+ or after changing the stack.
+ Do not call any other Python C API between the call and the stack
+ change.
+
+ See :c:func:`PyUnstable_ThreadState_ResetStackProtection` for undoing this operation.
+
+ .. versionadded:: 3.15
+
+
+.. c:function:: void PyUnstable_ThreadState_ResetStackProtection(PyThreadState *tstate)
+
+ Reset the stack protection start address and stack protection size
+ of a Python thread state to the operating system defaults.
+
+ See :c:func:`PyUnstable_ThreadState_SetStackProtection` for an explanation.
+
+ .. versionadded:: 3.15
+
+
.. c:function:: PyInterpreterState* PyInterpreterState_Get(void)
Get the current interpreter.
@@ -1854,6 +1891,25 @@ pointer and a void pointer argument.
This function now always schedules *func* to be run in the main
interpreter.
+
+.. c:function:: int Py_MakePendingCalls(void)
+
+ Execute all pending calls. This is usually executed automatically by the
+ interpreter.
+
+ This function returns ``0`` on success, and returns ``-1`` with an exception
+ set on failure.
+
+ If this is not called in the main thread of the main
+ interpreter, this function does nothing and returns ``0``.
+ The caller must hold an :term:`attached thread state`.
+
+ .. versionadded:: 3.1
+
+ .. versionchanged:: 3.12
+ This function only runs pending calls in the main interpreter.
+
+
.. _profiling:
Profiling and Tracing
diff --git a/Doc/c-api/init_config.rst b/Doc/c-api/init_config.rst
index b20495e672d..c345029e4ac 100644
--- a/Doc/c-api/init_config.rst
+++ b/Doc/c-api/init_config.rst
@@ -102,7 +102,7 @@ Error Handling
* Set *\*err_msg* and return ``1`` if an error is set.
* Set *\*err_msg* to ``NULL`` and return ``0`` otherwise.
- An error message is an UTF-8 encoded string.
+ An error message is a UTF-8 encoded string.
If *config* has an exit code, format the exit code as an error
message.
diff --git a/Doc/c-api/intro.rst b/Doc/c-api/intro.rst
index acce3dc215d..c39e006f059 100644
--- a/Doc/c-api/intro.rst
+++ b/Doc/c-api/intro.rst
@@ -121,6 +121,10 @@ complete listing.
Return the absolute value of ``x``.
+ If the result cannot be represented (for example, if ``x`` has
+ :c:macro:`!INT_MIN` value for :c:expr:`int` type), the behavior is
+ undefined.
+
.. versionadded:: 3.3
.. c:macro:: Py_ALWAYS_INLINE
@@ -167,6 +171,17 @@ complete listing.
Like ``getenv(s)``, but returns ``NULL`` if :option:`-E` was passed on the
command line (see :c:member:`PyConfig.use_environment`).
+.. c:macro:: Py_LOCAL(type)
+
+ Declare a function returning the specified *type* using a fast-calling
+ qualifier for functions that are local to the current file.
+ Semantically, this is equivalent to ``static type``.
+
+.. c:macro:: Py_LOCAL_INLINE(type)
+
+ Equivalent to :c:macro:`Py_LOCAL` but additionally requests the function
+ be inlined.
+
.. c:macro:: Py_MAX(x, y)
Return the maximum value between ``x`` and ``y``.
@@ -179,6 +194,14 @@ complete listing.
.. versionadded:: 3.6
+.. c:macro:: Py_MEMCPY(dest, src, n)
+
+ This is a :term:`soft deprecated` alias to :c:func:`!memcpy`.
+ Use :c:func:`!memcpy` directly instead.
+
+ .. deprecated:: 3.14
+ The macro is :term:`soft deprecated`.
+
.. c:macro:: Py_MIN(x, y)
Return the minimum value between ``x`` and ``y``.
@@ -233,9 +256,32 @@ complete listing.
.. versionadded:: 3.4
+.. c:macro:: Py_BUILD_ASSERT(cond)
+
+ Asserts a compile-time condition *cond*, as a statement.
+ The build will fail if the condition is false or cannot be evaluated at compile time.
+
+ For example::
+
+ Py_BUILD_ASSERT(sizeof(PyTime_t) == sizeof(int64_t));
+
+ .. versionadded:: 3.3
+
+.. c:macro:: Py_BUILD_ASSERT_EXPR(cond)
+
+ Asserts a compile-time condition *cond*, as an expression that evaluates to ``0``.
+ The build will fail if the condition is false or cannot be evaluated at compile time.
+
+ For example::
+
+ #define foo_to_char(foo) \
+ ((char *)(foo) + Py_BUILD_ASSERT_EXPR(offsetof(struct foo, string) == 0))
+
+ .. versionadded:: 3.3
+
.. c:macro:: PyDoc_STRVAR(name, str)
- Creates a variable with name ``name`` that can be used in docstrings.
+ Creates a variable with name *name* that can be used in docstrings.
If Python is built without docstrings, the value will be empty.
Use :c:macro:`PyDoc_STRVAR` for docstrings to support building
@@ -267,6 +313,15 @@ complete listing.
{NULL, NULL}
};
+.. c:macro:: PyDoc_VAR(name)
+
+ Declares a static character array variable with the given name *name*.
+
+ For example::
+
+ PyDoc_VAR(python_doc) = PyDoc_STR("A genus of constricting snakes in the Pythonidae family native "
+ "to the tropics and subtropics of the Eastern Hemisphere.");
+
.. _api-objects:
diff --git a/Doc/c-api/iterator.rst b/Doc/c-api/iterator.rst
index 6b7ba8c9979..bfbfe3c9279 100644
--- a/Doc/c-api/iterator.rst
+++ b/Doc/c-api/iterator.rst
@@ -50,3 +50,72 @@ sentinel value is returned.
callable object that can be called with no parameters; each call to it should
return the next item in the iteration. When *callable* returns a value equal to
*sentinel*, the iteration will be terminated.
+
+
+Range Objects
+^^^^^^^^^^^^^
+
+.. c:var:: PyTypeObject PyRange_Type
+
+ The type object for :class:`range` objects.
+
+
+.. c:function:: int PyRange_Check(PyObject *o)
+
+ Return true if the object *o* is an instance of a :class:`range` object.
+ This function always succeeds.
+
+
+Builtin Iterator Types
+^^^^^^^^^^^^^^^^^^^^^^
+
+These are built-in iteration types that are included in Python's C API, but
+provide no additional functions. They are here for completeness.
+
+
+.. list-table::
+ :widths: auto
+ :header-rows: 1
+
+ * * C type
+ * Python type
+ * * .. c:var:: PyTypeObject PyEnum_Type
+ * :py:class:`enumerate`
+ * * .. c:var:: PyTypeObject PyFilter_Type
+ * :py:class:`filter`
+ * * .. c:var:: PyTypeObject PyMap_Type
+ * :py:class:`map`
+ * * .. c:var:: PyTypeObject PyReversed_Type
+ * :py:class:`reversed`
+ * * .. c:var:: PyTypeObject PyZip_Type
+ * :py:class:`zip`
+
+
+Other Iterator Objects
+^^^^^^^^^^^^^^^^^^^^^^
+
+.. c:var:: PyTypeObject PyByteArrayIter_Type
+.. c:var:: PyTypeObject PyBytesIter_Type
+.. c:var:: PyTypeObject PyListIter_Type
+.. c:var:: PyTypeObject PyListRevIter_Type
+.. c:var:: PyTypeObject PySetIter_Type
+.. c:var:: PyTypeObject PyTupleIter_Type
+.. c:var:: PyTypeObject PyRangeIter_Type
+.. c:var:: PyTypeObject PyLongRangeIter_Type
+.. c:var:: PyTypeObject PyDictIterKey_Type
+.. c:var:: PyTypeObject PyDictRevIterKey_Type
+.. c:var:: PyTypeObject PyDictIterValue_Type
+.. c:var:: PyTypeObject PyDictRevIterValue_Type
+.. c:var:: PyTypeObject PyDictIterItem_Type
+.. c:var:: PyTypeObject PyDictRevIterItem_Type
+.. c:var:: PyTypeObject PyODictIter_Type
+
+ Type objects for iterators of various built-in objects.
+
+ Do not create instances of these directly; prefer calling
+ :c:func:`PyObject_GetIter` instead.
+
+ Note that there is no guarantee that a given built-in type uses a given iterator
+ type. For example, iterating over :class:`range` will use one of two iterator
+ types depending on the size of the range. Other types may start using a
+ similar scheme in the future, without warning.
diff --git a/Doc/c-api/long.rst b/Doc/c-api/long.rst
index fcb20f7c93c..ed34efe716d 100644
--- a/Doc/c-api/long.rst
+++ b/Doc/c-api/long.rst
@@ -161,6 +161,17 @@ distinguished from a number. Use :c:func:`PyErr_Occurred` to disambiguate.
.. versionadded:: 3.13
+.. c:macro:: PyLong_FromPid(pid)
+
+ Macro for creating a Python integer from a process identifier.
+
+ This can be defined as an alias to :c:func:`PyLong_FromLong` or
+ :c:func:`PyLong_FromLongLong`, depending on the size of the system's
+ PID type.
+
+ .. versionadded:: 3.2
+
+
.. c:function:: long PyLong_AsLong(PyObject *obj)
.. index::
@@ -575,6 +586,17 @@ distinguished from a number. Use :c:func:`PyErr_Occurred` to disambiguate.
.. versionadded:: 3.13
+.. c:macro:: PyLong_AsPid(pid)
+
+ Macro for converting a Python integer into a process identifier.
+
+ This can be defined as an alias to :c:func:`PyLong_AsLong`,
+ :c:func:`PyLong_FromLongLong`, or :c:func:`PyLong_AsInt`, depending on the
+ size of the system's PID type.
+
+ .. versionadded:: 3.2
+
+
.. c:function:: int PyLong_GetSign(PyObject *obj, int *sign)
Get the sign of the integer object *obj*.
diff --git a/Doc/c-api/mapping.rst b/Doc/c-api/mapping.rst
index 1f55c0aa955..2476ebb9b69 100644
--- a/Doc/c-api/mapping.rst
+++ b/Doc/c-api/mapping.rst
@@ -102,7 +102,7 @@ See also :c:func:`PyObject_GetItem`, :c:func:`PyObject_SetItem` and
.. note::
- Exceptions which occur when this calls :meth:`~object.__getitem__`
+ Exceptions which occur when this calls the :meth:`~object.__getitem__`
method are silently ignored.
For proper error handling, use :c:func:`PyMapping_HasKeyWithError`,
:c:func:`PyMapping_GetOptionalItem` or :c:func:`PyObject_GetItem()` instead.
@@ -116,7 +116,7 @@ See also :c:func:`PyObject_GetItem`, :c:func:`PyObject_SetItem` and
.. note::
- Exceptions that occur when this calls :meth:`~object.__getitem__`
+ Exceptions that occur when this calls the :meth:`~object.__getitem__`
method or while creating the temporary :class:`str`
object are silently ignored.
For proper error handling, use :c:func:`PyMapping_HasKeyStringWithError`,
diff --git a/Doc/c-api/marshal.rst b/Doc/c-api/marshal.rst
index 61218a1bf6f..668a163b2df 100644
--- a/Doc/c-api/marshal.rst
+++ b/Doc/c-api/marshal.rst
@@ -82,7 +82,7 @@ The following functions allow marshalled values to be read back in.
assumes that no further objects will be read from the file, allowing it to
aggressively load file data into memory so that the de-serialization can
operate from data in memory rather than reading a byte at a time from the
- file. Only use these variant if you are certain that you won't be reading
+ file. Only use this variant if you are certain that you won't be reading
anything else from the file.
On error, sets the appropriate exception (:exc:`EOFError`, :exc:`ValueError`
diff --git a/Doc/c-api/memory.rst b/Doc/c-api/memory.rst
index df1bb0ce370..23958980102 100644
--- a/Doc/c-api/memory.rst
+++ b/Doc/c-api/memory.rst
@@ -102,7 +102,7 @@ All allocating functions belong to one of three different "domains" (see also
strategies and are optimized for different purposes. The specific details on
how every domain allocates memory or what internal functions each domain calls
is considered an implementation detail, but for debugging purposes a simplified
-table can be found at :ref:`here `.
+table can be found at :ref:`default-memory-allocators`.
The APIs used to allocate and free a block of memory must be from the same domain.
For example, :c:func:`PyMem_Free` must be used to free memory allocated using :c:func:`PyMem_Malloc`.
diff --git a/Doc/c-api/memoryview.rst b/Doc/c-api/memoryview.rst
index f6038032805..e4ac8b57673 100644
--- a/Doc/c-api/memoryview.rst
+++ b/Doc/c-api/memoryview.rst
@@ -13,6 +13,12 @@ A :class:`memoryview` object exposes the C level :ref:`buffer interface
any other object.
+.. c:var:: PyTypeObject PyMemoryView_Type
+
+ This instance of :c:type:`PyTypeObject` represents the Python memoryview
+ type. This is the same object as :class:`memoryview` in the Python layer.
+
+
.. c:function:: PyObject *PyMemoryView_FromObject(PyObject *obj)
Create a memoryview object from an object that provides the buffer interface.
diff --git a/Doc/c-api/module.rst b/Doc/c-api/module.rst
index 6626f628fcc..1994a3c7d01 100644
--- a/Doc/c-api/module.rst
+++ b/Doc/c-api/module.rst
@@ -13,7 +13,7 @@ Module Objects
.. index:: single: ModuleType (in module types)
This instance of :c:type:`PyTypeObject` represents the Python module type. This
- is exposed to Python programs as ``types.ModuleType``.
+ is exposed to Python programs as :py:class:`types.ModuleType`.
.. c:function:: int PyModule_Check(PyObject *p)
@@ -71,6 +71,9 @@ Module Objects
``PyObject_*`` functions rather than directly manipulate a module's
:attr:`~object.__dict__`.
+ The returned reference is borrowed from the module; it is valid until
+ the module is destroyed.
+
.. c:function:: PyObject* PyModule_GetNameObject(PyObject *module)
@@ -90,6 +93,10 @@ Module Objects
Similar to :c:func:`PyModule_GetNameObject` but return the name encoded to
``'utf-8'``.
+ The returned buffer is only valid until the module is renamed or destroyed.
+ Note that Python code may rename a module by setting its :py:attr:`~module.__name__`
+ attribute.
+
.. c:function:: void* PyModule_GetState(PyObject *module)
Return the "state" of the module, that is, a pointer to the block of memory
@@ -103,7 +110,7 @@ Module Objects
created, or ``NULL`` if the module wasn't created from a definition.
On error, return ``NULL`` with an exception set.
- Use :c:func:`PyErr_Occurred` to tell this case apart from a mising
+ Use :c:func:`PyErr_Occurred` to tell this case apart from a missing
:c:type:`!PyModuleDef`.
@@ -126,6 +133,9 @@ Module Objects
Similar to :c:func:`PyModule_GetFilenameObject` but return the filename
encoded to 'utf-8'.
+ The returned buffer is only valid until the module's :py:attr:`~module.__file__` attribute
+ is reassigned or the module is destroyed.
+
.. deprecated:: 3.2
:c:func:`PyModule_GetFilename` raises :exc:`UnicodeEncodeError` on
unencodable filenames, use :c:func:`PyModule_GetFilenameObject` instead.
@@ -671,6 +681,9 @@ or code that creates modules dynamically.
:c:type:`PyMethodDef` arrays; in that case they should call this function
directly.
+ The *functions* array must be statically allocated (or otherwise guaranteed
+ to outlive the module object).
+
.. versionadded:: 3.5
.. c:function:: int PyModule_SetDocString(PyObject *module, const char *docstring)
diff --git a/Doc/c-api/monitoring.rst b/Doc/c-api/monitoring.rst
index 7926148302a..b0227c2f4fa 100644
--- a/Doc/c-api/monitoring.rst
+++ b/Doc/c-api/monitoring.rst
@@ -136,7 +136,7 @@ Managing the Monitoring State
-----------------------------
Monitoring states can be managed with the help of monitoring scopes. A scope
-would typically correspond to a python function.
+would typically correspond to a Python function.
.. c:function:: int PyMonitoring_EnterScope(PyMonitoringState *state_array, uint64_t *version, const uint8_t *event_types, Py_ssize_t length)
diff --git a/Doc/c-api/object.rst b/Doc/c-api/object.rst
index 8629b768a29..76971c46c16 100644
--- a/Doc/c-api/object.rst
+++ b/Doc/c-api/object.rst
@@ -73,7 +73,7 @@ Object Protocol
Flag to be used with multiple functions that print the object (like
:c:func:`PyObject_Print` and :c:func:`PyFile_WriteObject`).
- If passed, these function would use the :func:`str` of the object
+ If passed, these functions use the :func:`str` of the object
instead of the :func:`repr`.
@@ -85,6 +85,35 @@ Object Protocol
instead of the :func:`repr`.
+.. c:function:: void PyUnstable_Object_Dump(PyObject *op)
+
+ Dump an object *op* to ``stderr``. This should only be used for debugging.
+
+ The output is intended to try dumping objects even after memory corruption:
+
+ * Information is written starting with fields that are the least likely to
+ crash when accessed.
+ * This function can be called without an :term:`attached thread state`, but
+ it's not recommended to do so: it can cause deadlocks.
+ * An object that does not belong to the current interpreter may be dumped,
+ but this may also cause crashes or unintended behavior.
+ * Implement a heuristic to detect if the object memory has been freed. Don't
+ display the object contents in this case, only its memory address.
+ * The output format may change at any time.
+
+ Example of output:
+
+ .. code-block:: output
+
+ object address : 0x7f80124702c0
+ object refcount : 2
+ object type : 0x9902e0
+ object type name: str
+ object repr : 'abcdef'
+
+ .. versionadded:: next
+
+
.. c:function:: int PyObject_HasAttrWithError(PyObject *o, PyObject *attr_name)
Returns ``1`` if *o* has the attribute *attr_name*, and ``0`` otherwise.
diff --git a/Doc/c-api/picklebuffer.rst b/Doc/c-api/picklebuffer.rst
new file mode 100644
index 00000000000..9e2d92341b0
--- /dev/null
+++ b/Doc/c-api/picklebuffer.rst
@@ -0,0 +1,59 @@
+.. highlight:: c
+
+.. _picklebuffer-objects:
+
+.. index::
+ pair: object; PickleBuffer
+
+Pickle buffer objects
+---------------------
+
+.. versionadded:: 3.8
+
+A :class:`pickle.PickleBuffer` object wraps a :ref:`buffer-providing object
+` for out-of-band data transfer with the :mod:`pickle` module.
+
+
+.. c:var:: PyTypeObject PyPickleBuffer_Type
+
+ This instance of :c:type:`PyTypeObject` represents the Python pickle buffer type.
+ This is the same object as :class:`pickle.PickleBuffer` in the Python layer.
+
+
+.. c:function:: int PyPickleBuffer_Check(PyObject *op)
+
+ Return true if *op* is a pickle buffer instance.
+ This function always succeeds.
+
+
+.. c:function:: PyObject *PyPickleBuffer_FromObject(PyObject *obj)
+
+ Create a pickle buffer from the object *obj*.
+
+ This function will fail if *obj* doesn't support the :ref:`buffer protocol `.
+
+ On success, return a new pickle buffer instance.
+ On failure, set an exception and return ``NULL``.
+
+ Analogous to calling :class:`pickle.PickleBuffer` with *obj* in Python.
+
+
+.. c:function:: const Py_buffer *PyPickleBuffer_GetBuffer(PyObject *picklebuf)
+
+ Get a pointer to the underlying :c:type:`Py_buffer` that the pickle buffer wraps.
+
+ The returned pointer is valid as long as *picklebuf* is alive and has not been
+ released. The caller must not modify or free the returned :c:type:`Py_buffer`.
+ If the pickle buffer has been released, raise :exc:`ValueError`.
+
+ On success, return a pointer to the buffer view.
+ On failure, set an exception and return ``NULL``.
+
+
+.. c:function:: int PyPickleBuffer_Release(PyObject *picklebuf)
+
+ Release the underlying buffer held by the pickle buffer.
+
+ Return ``0`` on success. On failure, set an exception and return ``-1``.
+
+ Analogous to calling :meth:`pickle.PickleBuffer.release` in Python.
diff --git a/Doc/c-api/stable.rst b/Doc/c-api/stable.rst
index b08a7bf1b2f..f5e6b7ad157 100644
--- a/Doc/c-api/stable.rst
+++ b/Doc/c-api/stable.rst
@@ -279,7 +279,7 @@ The full API is described below for advanced use cases.
.. c:member:: uint8_t abiinfo_minor_version
- The major version of :c:struct:`PyABIInfo`.
+ The minor version of :c:struct:`PyABIInfo`.
Must be set to ``0``; larger values are reserved for backwards-compatible
future versions of :c:struct:`!PyABIInfo`.
diff --git a/Doc/c-api/structures.rst b/Doc/c-api/structures.rst
index 58dd915e04f..b4e7cb1d77e 100644
--- a/Doc/c-api/structures.rst
+++ b/Doc/c-api/structures.rst
@@ -447,6 +447,25 @@ definition with the same method name.
slot. This is helpful because calls to PyCFunctions are optimized more
than wrapper object calls.
+
+.. c:var:: PyTypeObject PyCMethod_Type
+
+ The type object corresponding to Python C method objects. This is
+ available as :class:`types.BuiltinMethodType` in the Python layer.
+
+
+.. c:function:: int PyCMethod_Check(PyObject *op)
+
+ Return true if *op* is an instance of the :c:type:`PyCMethod_Type` type
+ or a subtype of it. This function always succeeds.
+
+
+.. c:function:: int PyCMethod_CheckExact(PyObject *op)
+
+ This is the same as :c:func:`PyCMethod_Check`, but does not account for
+ subtypes.
+
+
.. c:function:: PyObject * PyCMethod_New(PyMethodDef *ml, PyObject *self, PyObject *module, PyTypeObject *cls)
Turn *ml* into a Python :term:`callable` object.
@@ -472,6 +491,24 @@ definition with the same method name.
.. versionadded:: 3.9
+.. c:var:: PyTypeObject PyCFunction_Type
+
+ The type object corresponding to Python C function objects. This is
+ available as :class:`types.BuiltinFunctionType` in the Python layer.
+
+
+.. c:function:: int PyCFunction_Check(PyObject *op)
+
+ Return true if *op* is an instance of the :c:type:`PyCFunction_Type` type
+ or a subtype of it. This function always succeeds.
+
+
+.. c:function:: int PyCFunction_CheckExact(PyObject *op)
+
+ This is the same as :c:func:`PyCFunction_Check`, but does not account for
+ subtypes.
+
+
.. c:function:: PyObject * PyCFunction_NewEx(PyMethodDef *ml, PyObject *self, PyObject *module)
Equivalent to ``PyCMethod_New(ml, self, module, NULL)``.
@@ -482,6 +519,62 @@ definition with the same method name.
Equivalent to ``PyCMethod_New(ml, self, NULL, NULL)``.
+.. c:function:: int PyCFunction_GetFlags(PyObject *func)
+
+ Get the function's flags on *func* as they were passed to
+ :c:member:`~PyMethodDef.ml_flags`.
+
+ If *func* is not a C function object, this fails with an exception.
+ *func* must not be ``NULL``.
+
+ This function returns the function's flags on success, and ``-1`` with an
+ exception set on failure.
+
+
+.. c:function:: int PyCFunction_GET_FLAGS(PyObject *func)
+
+ This is the same as :c:func:`PyCFunction_GetFlags`, but without error
+ or type checking.
+
+
+.. c:function:: PyCFunction PyCFunction_GetFunction(PyObject *func)
+
+ Get the function pointer on *func* as it was passed to
+ :c:member:`~PyMethodDef.ml_meth`.
+
+ If *func* is not a C function object, this fails with an exception.
+ *func* must not be ``NULL``.
+
+ This function returns the function pointer on success, and ``NULL`` with an
+ exception set on failure.
+
+
+.. c:function:: int PyCFunction_GET_FUNCTION(PyObject *func)
+
+ This is the same as :c:func:`PyCFunction_GetFunction`, but without error
+ or type checking.
+
+
+.. c:function:: PyObject *PyCFunction_GetSelf(PyObject *func)
+
+ Get the "self" object on *func*. This is the object that would be passed
+ to the first argument of a :c:type:`PyCFunction`. For C function objects
+ created through a :c:type:`PyMethodDef` on a :c:type:`PyModuleDef`, this
+ is the resulting module object.
+
+ If *func* is not a C function object, this fails with an exception.
+ *func* must not be ``NULL``.
+
+ This function returns a :term:`borrowed reference` to the "self" object
+ on success, and ``NULL`` with an exception set on failure.
+
+
+.. c:function:: PyObject *PyCFunction_GET_SELF(PyObject *func)
+
+ This is the same as :c:func:`PyCFunction_GetSelf`, but without error or
+ type checking.
+
+
Accessing attributes of extension types
---------------------------------------
@@ -605,14 +698,12 @@ The following flags can be used with :c:member:`PyMemberDef.flags`:
entry indicates an offset from the subclass-specific data, rather than
from ``PyObject``.
- Can only be used as part of :c:member:`Py_tp_members `
+ Can only be used as part of the :c:data:`Py_tp_members`
:c:type:`slot ` when creating a class using negative
:c:member:`~PyType_Spec.basicsize`.
It is mandatory in that case.
-
- This flag is only used in :c:type:`PyType_Slot`.
- When setting :c:member:`~PyTypeObject.tp_members` during
- class creation, Python clears it and sets
+ When setting :c:member:`~PyTypeObject.tp_members` from the slot during
+ class creation, Python clears the flag and sets
:c:member:`PyMemberDef.offset` to the offset from the ``PyObject`` struct.
.. index::
diff --git a/Doc/c-api/sys.rst b/Doc/c-api/sys.rst
index 336e3ef9640..ee73c1c8ada 100644
--- a/Doc/c-api/sys.rst
+++ b/Doc/c-api/sys.rst
@@ -123,6 +123,24 @@ Operating System Utilities
This is a thin wrapper around either :c:func:`!sigaction` or :c:func:`!signal`. Do
not call those functions directly!
+
+.. c:function:: int PyOS_InterruptOccurred(void)
+
+ Check if a :c:macro:`!SIGINT` signal has been received.
+
+ Returns ``1`` if a :c:macro:`!SIGINT` has occurred and clears the signal flag,
+ or ``0`` otherwise.
+
+ In most cases, you should prefer :c:func:`PyErr_CheckSignals` over this function.
+ :c:func:`!PyErr_CheckSignals` invokes the appropriate signal handlers
+ for all pending signals, allowing Python code to handle the signal properly.
+ This function only detects :c:macro:`!SIGINT` and does not invoke any Python
+ signal handlers.
+
+ This function is async-signal-safe and this function cannot fail.
+ The caller must hold an :term:`attached thread state`.
+
+
.. c:function:: wchar_t* Py_DecodeLocale(const char* arg, size_t *size)
.. warning::
diff --git a/Doc/c-api/tuple.rst b/Doc/c-api/tuple.rst
index 14a7c05efea..d0add48d7e8 100644
--- a/Doc/c-api/tuple.rst
+++ b/Doc/c-api/tuple.rst
@@ -61,7 +61,7 @@ Tuple Objects
.. c:function:: Py_ssize_t PyTuple_Size(PyObject *p)
Take a pointer to a tuple object, and return the size of that tuple.
- On error, return ``-1`` and with an exception set.
+ On error, return ``-1`` with an exception set.
.. c:function:: Py_ssize_t PyTuple_GET_SIZE(PyObject *p)
diff --git a/Doc/c-api/type.rst b/Doc/c-api/type.rst
index 5bdbff4e0ad..2f2060d0582 100644
--- a/Doc/c-api/type.rst
+++ b/Doc/c-api/type.rst
@@ -116,6 +116,20 @@ Type Objects
.. versionadded:: 3.12
+.. c:function:: int PyType_Unwatch(int watcher_id, PyObject *type)
+
+ Mark *type* as not watched. This undoes a previous call to
+ :c:func:`PyType_Watch`. *type* must not be ``NULL``.
+
+ An extension should never call this function with a *watcher_id* that was
+ not returned to it by a previous call to :c:func:`PyType_AddWatcher`.
+
+ On success, this function returns ``0``. On failure, this function returns
+ ``-1`` with an exception set.
+
+ .. versionadded:: 3.12
+
+
.. c:type:: int (*PyType_WatchCallback)(PyObject *type)
Type of a type-watcher callback function.
@@ -133,6 +147,18 @@ Type Objects
Type features are denoted by single bit flags.
+.. c:function:: int PyType_FastSubclass(PyTypeObject *type, int flag)
+
+ Return non-zero if the type object *type* sets the subclass flag *flag*.
+ Subclass flags are denoted by
+ :c:macro:`Py_TPFLAGS_*_SUBCLASS `.
+ This function is used by many ``_Check`` functions for common types.
+
+ .. seealso::
+ :c:func:`PyObject_TypeCheck`, which is used as a slower alternative in
+ ``_Check`` functions for types that don't come with subclass flags.
+
+
.. c:function:: int PyType_IS_GC(PyTypeObject *o)
Return true if the type object includes support for the cycle detector; this
@@ -169,12 +195,14 @@ Type Objects
before initialization) and should be paired with :c:func:`PyObject_Free` in
:c:member:`~PyTypeObject.tp_free`.
+
.. c:function:: PyObject* PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
Generic handler for the :c:member:`~PyTypeObject.tp_new` slot of a type
object. Creates a new instance using the type's
:c:member:`~PyTypeObject.tp_alloc` slot and returns the resulting object.
+
.. c:function:: int PyType_Ready(PyTypeObject *type)
Finalize a type object. This should be called on all type objects to finish
@@ -191,6 +219,7 @@ Type Objects
GC protocol itself by at least implementing the
:c:member:`~PyTypeObject.tp_traverse` handle.
+
.. c:function:: PyObject* PyType_GetName(PyTypeObject *type)
Return the type's name. Equivalent to getting the type's
@@ -198,6 +227,7 @@ Type Objects
.. versionadded:: 3.11
+
.. c:function:: PyObject* PyType_GetQualName(PyTypeObject *type)
Return the type's qualified name. Equivalent to getting the
@@ -213,6 +243,7 @@ Type Objects
.. versionadded:: 3.13
+
.. c:function:: PyObject* PyType_GetModuleName(PyTypeObject *type)
Return the type's module name. Equivalent to getting the
@@ -220,6 +251,7 @@ Type Objects
.. versionadded:: 3.13
+
.. c:function:: void* PyType_GetSlot(PyTypeObject *type, int slot)
Return the function pointer stored in the given slot. If the
@@ -236,6 +268,7 @@ Type Objects
:c:func:`PyType_GetSlot` can now accept all types.
Previously, it was limited to :ref:`heap types `.
+
.. c:function:: PyObject* PyType_GetModule(PyTypeObject *type)
Return the module object associated with the given type when the type was
@@ -255,6 +288,7 @@ Type Objects
.. versionadded:: 3.9
+
.. c:function:: void* PyType_GetModuleState(PyTypeObject *type)
Return the state of the module object associated with the given type.
@@ -269,6 +303,7 @@ Type Objects
.. versionadded:: 3.9
+
.. c:function:: PyObject* PyType_GetModuleByDef(PyTypeObject *type, struct PyModuleDef *def)
Find the first superclass whose module was created from
@@ -288,6 +323,7 @@ Type Objects
.. versionadded:: 3.11
+
.. c:function:: int PyType_GetBaseByToken(PyTypeObject *type, void *token, PyTypeObject **result)
Find the first superclass in *type*'s :term:`method resolution order` whose
@@ -306,6 +342,7 @@ Type Objects
.. versionadded:: 3.14
+
.. c:function:: int PyUnstable_Type_AssignVersionTag(PyTypeObject *type)
Attempt to assign a version tag to the given type.
@@ -316,6 +353,16 @@ Type Objects
.. versionadded:: 3.12
+.. c:function:: int PyType_SUPPORTS_WEAKREFS(PyTypeObject *type)
+
+ Return true if instances of *type* support creating weak references, false
+ otherwise. This function always succeeds. *type* must not be ``NULL``.
+
+ .. seealso::
+ * :ref:`weakrefobjects`
+ * :py:mod:`weakref`
+
+
Creating Heap-Allocated Types
.............................
@@ -336,8 +383,8 @@ The following functions and structs are used to create
The *bases* argument can be used to specify base classes; it can either
be only one class or a tuple of classes.
- If *bases* is ``NULL``, the *Py_tp_bases* slot is used instead.
- If that also is ``NULL``, the *Py_tp_base* slot is used instead.
+ If *bases* is ``NULL``, the :c:data:`Py_tp_bases` slot is used instead.
+ If that also is ``NULL``, the :c:data:`Py_tp_base` slot is used instead.
If that also is ``NULL``, the new type derives from :class:`object`.
The *module* argument can be used to record the module in which the new
@@ -364,6 +411,7 @@ The following functions and structs are used to create
.. versionadded:: 3.12
+
.. c:function:: PyObject* PyType_FromModuleAndSpec(PyObject *module, PyType_Spec *spec, PyObject *bases)
Equivalent to ``PyType_FromMetaclass(NULL, module, spec, bases)``.
@@ -390,6 +438,7 @@ The following functions and structs are used to create
Creating classes whose metaclass overrides
:c:member:`~PyTypeObject.tp_new` is no longer allowed.
+
.. c:function:: PyObject* PyType_FromSpecWithBases(PyType_Spec *spec, PyObject *bases)
Equivalent to ``PyType_FromMetaclass(NULL, NULL, spec, bases)``.
@@ -411,6 +460,7 @@ The following functions and structs are used to create
Creating classes whose metaclass overrides
:c:member:`~PyTypeObject.tp_new` is no longer allowed.
+
.. c:function:: PyObject* PyType_FromSpec(PyType_Spec *spec)
Equivalent to ``PyType_FromMetaclass(NULL, NULL, spec, NULL)``.
@@ -431,6 +481,7 @@ The following functions and structs are used to create
Creating classes whose metaclass overrides
:c:member:`~PyTypeObject.tp_new` is no longer allowed.
+
.. c:function:: int PyType_Freeze(PyTypeObject *type)
Make a type immutable: set the :c:macro:`Py_TPFLAGS_IMMUTABLETYPE` flag.
@@ -539,9 +590,9 @@ The following functions and structs are used to create
:c:type:`PyAsyncMethods` with an added ``Py_`` prefix.
For example, use:
- * ``Py_tp_dealloc`` to set :c:member:`PyTypeObject.tp_dealloc`
- * ``Py_nb_add`` to set :c:member:`PyNumberMethods.nb_add`
- * ``Py_sq_length`` to set :c:member:`PySequenceMethods.sq_length`
+ * :c:data:`Py_tp_dealloc` to set :c:member:`PyTypeObject.tp_dealloc`
+ * :c:data:`Py_nb_add` to set :c:member:`PyNumberMethods.nb_add`
+ * :c:data:`Py_sq_length` to set :c:member:`PySequenceMethods.sq_length`
An additional slot is supported that does not correspond to a
:c:type:`!PyTypeObject` struct field:
@@ -560,7 +611,7 @@ The following functions and structs are used to create
If it is not possible to switch to a ``MANAGED`` flag (for example,
for vectorcall or to support Python older than 3.12), specify the
- offset in :c:member:`Py_tp_members `.
+ offset in :c:data:`Py_tp_members`.
See :ref:`PyMemberDef documentation `
for details.
@@ -587,8 +638,8 @@ The following functions and structs are used to create
under the :ref:`limited API `.
.. versionchanged:: 3.14
- The field :c:member:`~PyTypeObject.tp_vectorcall` can now set
- using ``Py_tp_vectorcall``. See the field's documentation
+ The field :c:member:`~PyTypeObject.tp_vectorcall` can now be set
+ using :c:data:`Py_tp_vectorcall`. See the field's documentation
for details.
.. c:member:: void *pfunc
@@ -598,10 +649,11 @@ The following functions and structs are used to create
*pfunc* values may not be ``NULL``, except for the following slots:
- * ``Py_tp_doc``
+ * :c:data:`Py_tp_doc`
* :c:data:`Py_tp_token` (for clarity, prefer :c:data:`Py_TP_USE_SPEC`
rather than ``NULL``)
+
.. c:macro:: Py_tp_token
A :c:member:`~PyType_Slot.slot` that records a static memory layout ID
diff --git a/Doc/c-api/typeobj.rst b/Doc/c-api/typeobj.rst
index 59c26a713e4..49fe02d919d 100644
--- a/Doc/c-api/typeobj.rst
+++ b/Doc/c-api/typeobj.rst
@@ -676,6 +676,8 @@ and :c:data:`PyType_Type` effectively act as defaults.)
.. c:member:: destructor PyTypeObject.tp_dealloc
+ .. corresponding-type-slot:: Py_tp_dealloc
+
A pointer to the instance destructor function. The function signature is::
void tp_dealloc(PyObject *self);
@@ -860,6 +862,8 @@ and :c:data:`PyType_Type` effectively act as defaults.)
.. c:member:: getattrfunc PyTypeObject.tp_getattr
+ .. corresponding-type-slot:: Py_tp_getattr
+
An optional pointer to the get-attribute-string function.
This field is deprecated. When it is defined, it should point to a function
@@ -877,6 +881,8 @@ and :c:data:`PyType_Type` effectively act as defaults.)
.. c:member:: setattrfunc PyTypeObject.tp_setattr
+ .. corresponding-type-slot:: Py_tp_setattr
+
An optional pointer to the function for setting and deleting attributes.
This field is deprecated. When it is defined, it should point to a function
@@ -909,6 +915,8 @@ and :c:data:`PyType_Type` effectively act as defaults.)
.. c:member:: reprfunc PyTypeObject.tp_repr
+ .. corresponding-type-slot:: Py_tp_repr
+
.. index:: pair: built-in function; repr
An optional pointer to a function that implements the built-in function
@@ -974,6 +982,8 @@ and :c:data:`PyType_Type` effectively act as defaults.)
.. c:member:: hashfunc PyTypeObject.tp_hash
+ .. corresponding-type-slot:: Py_tp_hash
+
.. index:: pair: built-in function; hash
An optional pointer to a function that implements the built-in function
@@ -1015,6 +1025,8 @@ and :c:data:`PyType_Type` effectively act as defaults.)
.. c:member:: ternaryfunc PyTypeObject.tp_call
+ .. corresponding-type-slot:: Py_tp_call
+
An optional pointer to a function that implements calling the object. This
should be ``NULL`` if the object is not callable. The signature is the same as
for :c:func:`PyObject_Call`::
@@ -1028,6 +1040,8 @@ and :c:data:`PyType_Type` effectively act as defaults.)
.. c:member:: reprfunc PyTypeObject.tp_str
+ .. corresponding-type-slot:: Py_tp_str
+
An optional pointer to a function that implements the built-in operation
:func:`str`. (Note that :class:`str` is a type now, and :func:`str` calls the
constructor for that type. This constructor calls :c:func:`PyObject_Str` to do
@@ -1053,6 +1067,8 @@ and :c:data:`PyType_Type` effectively act as defaults.)
.. c:member:: getattrofunc PyTypeObject.tp_getattro
+ .. corresponding-type-slot:: Py_tp_getattro
+
An optional pointer to the get-attribute function.
The signature is the same as for :c:func:`PyObject_GetAttr`::
@@ -1077,6 +1093,8 @@ and :c:data:`PyType_Type` effectively act as defaults.)
.. c:member:: setattrofunc PyTypeObject.tp_setattro
+ .. corresponding-type-slot:: Py_tp_setattro
+
An optional pointer to the function for setting and deleting attributes.
The signature is the same as for :c:func:`PyObject_SetAttr`::
@@ -1333,8 +1351,8 @@ and :c:data:`PyType_Type` effectively act as defaults.)
.. c:macro:: Py_TPFLAGS_BASE_EXC_SUBCLASS
.. c:macro:: Py_TPFLAGS_TYPE_SUBCLASS
- These flags are used by functions such as
- :c:func:`PyLong_Check` to quickly determine if a type is a subclass
+ Functions such as :c:func:`PyLong_Check` will call :c:func:`PyType_FastSubclass`
+ with one of these flags to quickly determine if a type is a subclass
of a built-in type; such specific checks are faster than a generic
check, like :c:func:`PyObject_IsInstance`. Custom types that inherit
from built-ins should have their :c:member:`~PyTypeObject.tp_flags`
@@ -1475,6 +1493,8 @@ and :c:data:`PyType_Type` effectively act as defaults.)
.. c:member:: const char* PyTypeObject.tp_doc
+ .. corresponding-type-slot:: Py_tp_doc
+
An optional pointer to a NUL-terminated C string giving the docstring for this
type object. This is exposed as the :attr:`~type.__doc__` attribute on the
type and instances of the type.
@@ -1486,6 +1506,8 @@ and :c:data:`PyType_Type` effectively act as defaults.)
.. c:member:: traverseproc PyTypeObject.tp_traverse
+ .. corresponding-type-slot:: Py_tp_traverse
+
An optional pointer to a traversal function for the garbage collector. This is
only used if the :c:macro:`Py_TPFLAGS_HAVE_GC` flag bit is set. The signature is::
@@ -1582,6 +1604,8 @@ and :c:data:`PyType_Type` effectively act as defaults.)
.. c:member:: inquiry PyTypeObject.tp_clear
+ .. corresponding-type-slot:: Py_tp_clear
+
An optional pointer to a clear function. The signature is::
int tp_clear(PyObject *);
@@ -1730,6 +1754,8 @@ and :c:data:`PyType_Type` effectively act as defaults.)
.. c:member:: richcmpfunc PyTypeObject.tp_richcompare
+ .. corresponding-type-slot:: Py_tp_richcompare
+
An optional pointer to the rich comparison function, whose signature is::
PyObject *tp_richcompare(PyObject *self, PyObject *other, int op);
@@ -1832,6 +1858,8 @@ and :c:data:`PyType_Type` effectively act as defaults.)
.. c:member:: getiterfunc PyTypeObject.tp_iter
+ .. corresponding-type-slot:: Py_tp_iter
+
An optional pointer to a function that returns an :term:`iterator` for the
object. Its presence normally signals that the instances of this type are
:term:`iterable` (although sequences may be iterable without this function).
@@ -1847,6 +1875,8 @@ and :c:data:`PyType_Type` effectively act as defaults.)
.. c:member:: iternextfunc PyTypeObject.tp_iternext
+ .. corresponding-type-slot:: Py_tp_iternext
+
An optional pointer to a function that returns the next item in an
:term:`iterator`. The signature is::
@@ -1870,6 +1900,8 @@ and :c:data:`PyType_Type` effectively act as defaults.)
.. c:member:: struct PyMethodDef* PyTypeObject.tp_methods
+ .. corresponding-type-slot:: Py_tp_methods
+
An optional pointer to a static ``NULL``-terminated array of :c:type:`PyMethodDef`
structures, declaring regular methods of this type.
@@ -1884,6 +1916,8 @@ and :c:data:`PyType_Type` effectively act as defaults.)
.. c:member:: struct PyMemberDef* PyTypeObject.tp_members
+ .. corresponding-type-slot:: Py_tp_members
+
An optional pointer to a static ``NULL``-terminated array of :c:type:`PyMemberDef`
structures, declaring regular data members (fields or slots) of instances of
this type.
@@ -1899,6 +1933,8 @@ and :c:data:`PyType_Type` effectively act as defaults.)
.. c:member:: struct PyGetSetDef* PyTypeObject.tp_getset
+ .. corresponding-type-slot:: Py_tp_getset
+
An optional pointer to a static ``NULL``-terminated array of :c:type:`PyGetSetDef`
structures, declaring computed attributes of instances of this type.
@@ -1913,6 +1949,8 @@ and :c:data:`PyType_Type` effectively act as defaults.)
.. c:member:: PyTypeObject* PyTypeObject.tp_base
+ .. corresponding-type-slot:: Py_tp_base
+
An optional pointer to a base type from which type properties are inherited. At
this level, only single inheritance is supported; multiple inheritance require
dynamically creating a type object by calling the metatype.
@@ -1985,6 +2023,8 @@ and :c:data:`PyType_Type` effectively act as defaults.)
.. c:member:: descrgetfunc PyTypeObject.tp_descr_get
+ .. corresponding-type-slot:: Py_tp_descr_get
+
An optional pointer to a "descriptor get" function.
The function signature is::
@@ -2000,6 +2040,8 @@ and :c:data:`PyType_Type` effectively act as defaults.)
.. c:member:: descrsetfunc PyTypeObject.tp_descr_set
+ .. corresponding-type-slot:: Py_tp_descr_set
+
An optional pointer to a function for setting and deleting
a descriptor's value.
@@ -2060,6 +2102,8 @@ and :c:data:`PyType_Type` effectively act as defaults.)
.. c:member:: initproc PyTypeObject.tp_init
+ .. corresponding-type-slot:: Py_tp_init
+
An optional pointer to an instance initialization function.
This function corresponds to the :meth:`~object.__init__` method of classes. Like
@@ -2095,6 +2139,8 @@ and :c:data:`PyType_Type` effectively act as defaults.)
.. c:member:: allocfunc PyTypeObject.tp_alloc
+ .. corresponding-type-slot:: Py_tp_alloc
+
An optional pointer to an instance allocation function.
The function signature is::
@@ -2118,6 +2164,8 @@ and :c:data:`PyType_Type` effectively act as defaults.)
.. c:member:: newfunc PyTypeObject.tp_new
+ .. corresponding-type-slot:: Py_tp_new
+
An optional pointer to an instance creation function.
The function signature is::
@@ -2157,6 +2205,8 @@ and :c:data:`PyType_Type` effectively act as defaults.)
.. c:member:: freefunc PyTypeObject.tp_free
+ .. corresponding-type-slot:: Py_tp_free
+
An optional pointer to an instance deallocation function. Its signature is::
void tp_free(void *self);
@@ -2186,6 +2236,8 @@ and :c:data:`PyType_Type` effectively act as defaults.)
.. c:member:: inquiry PyTypeObject.tp_is_gc
+ .. corresponding-type-slot:: Py_tp_is_gc
+
An optional pointer to a function called by the garbage collector.
The garbage collector needs to know whether a particular object is collectible
@@ -2214,12 +2266,14 @@ and :c:data:`PyType_Type` effectively act as defaults.)
.. c:member:: PyObject* PyTypeObject.tp_bases
+ .. corresponding-type-slot:: Py_tp_bases
+
Tuple of base types.
This field should be set to ``NULL`` and treated as read-only.
Python will fill it in when the type is :c:func:`initialized `.
- For dynamically created classes, the ``Py_tp_bases``
+ For dynamically created classes, the :c:data:`Py_tp_bases`
:c:type:`slot ` can be used instead of the *bases* argument
of :c:func:`PyType_FromSpecWithBases`.
The argument form is preferred.
@@ -2294,6 +2348,8 @@ and :c:data:`PyType_Type` effectively act as defaults.)
.. c:member:: destructor PyTypeObject.tp_del
+ .. corresponding-type-slot:: Py_tp_del
+
This field is deprecated. Use :c:member:`~PyTypeObject.tp_finalize` instead.
@@ -2308,6 +2364,8 @@ and :c:data:`PyType_Type` effectively act as defaults.)
.. c:member:: destructor PyTypeObject.tp_finalize
+ .. corresponding-type-slot:: Py_tp_finalize
+
An optional pointer to an instance finalization function. This is the C
implementation of the :meth:`~object.__del__` special method. Its signature
is::
@@ -2466,6 +2524,8 @@ and :c:data:`PyType_Type` effectively act as defaults.)
.. c:member:: vectorcallfunc PyTypeObject.tp_vectorcall
+ .. corresponding-type-slot:: Py_tp_vectorcall
+
A :ref:`vectorcall function ` to use for calls of this type
object (rather than instances).
In other words, ``tp_vectorcall`` can be used to optimize ``type.__call__``,
@@ -2631,42 +2691,148 @@ Number Object Structures
Python 3.0.1.
.. c:member:: binaryfunc PyNumberMethods.nb_add
+
+ .. corresponding-type-slot:: Py_nb_add
+
.. c:member:: binaryfunc PyNumberMethods.nb_subtract
+
+ .. corresponding-type-slot:: Py_nb_subtract
+
.. c:member:: binaryfunc PyNumberMethods.nb_multiply
+
+ .. corresponding-type-slot:: Py_nb_multiply
+
.. c:member:: binaryfunc PyNumberMethods.nb_remainder
+
+ .. corresponding-type-slot:: Py_nb_remainder
+
.. c:member:: binaryfunc PyNumberMethods.nb_divmod
+
+ .. corresponding-type-slot:: Py_nb_divmod
+
.. c:member:: ternaryfunc PyNumberMethods.nb_power
+
+ .. corresponding-type-slot:: Py_nb_power
+
.. c:member:: unaryfunc PyNumberMethods.nb_negative
+
+ .. corresponding-type-slot:: Py_nb_negative
+
.. c:member:: unaryfunc PyNumberMethods.nb_positive
+
+ .. corresponding-type-slot:: Py_nb_positive
+
.. c:member:: unaryfunc PyNumberMethods.nb_absolute
+
+ .. corresponding-type-slot:: Py_nb_absolute
+
.. c:member:: inquiry PyNumberMethods.nb_bool
+
+ .. corresponding-type-slot:: Py_nb_bool
+
.. c:member:: unaryfunc PyNumberMethods.nb_invert
+
+ .. corresponding-type-slot:: Py_nb_invert
+
.. c:member:: binaryfunc PyNumberMethods.nb_lshift
+
+ .. corresponding-type-slot:: Py_nb_lshift
+
.. c:member:: binaryfunc PyNumberMethods.nb_rshift
+
+ .. corresponding-type-slot:: Py_nb_rshift
+
.. c:member:: binaryfunc PyNumberMethods.nb_and
+
+ .. corresponding-type-slot:: Py_nb_and
+
.. c:member:: binaryfunc PyNumberMethods.nb_xor
+
+ .. corresponding-type-slot:: Py_nb_xor
+
.. c:member:: binaryfunc PyNumberMethods.nb_or
+
+ .. corresponding-type-slot:: Py_nb_or
+
.. c:member:: unaryfunc PyNumberMethods.nb_int
+
+ .. corresponding-type-slot:: Py_nb_int
+
.. c:member:: void *PyNumberMethods.nb_reserved
+
.. c:member:: unaryfunc PyNumberMethods.nb_float
+
+ .. corresponding-type-slot:: Py_nb_float
+
.. c:member:: binaryfunc PyNumberMethods.nb_inplace_add
+
+ .. corresponding-type-slot:: Py_nb_inplace_add
+
.. c:member:: binaryfunc PyNumberMethods.nb_inplace_subtract
+
+ .. corresponding-type-slot:: Py_nb_inplace_subtract
+
.. c:member:: binaryfunc PyNumberMethods.nb_inplace_multiply
+
+ .. corresponding-type-slot:: Py_nb_inplace_multiply
+
.. c:member:: binaryfunc PyNumberMethods.nb_inplace_remainder
+
+ .. corresponding-type-slot:: Py_nb_inplace_remainder
+
.. c:member:: ternaryfunc PyNumberMethods.nb_inplace_power
+
+ .. corresponding-type-slot:: Py_nb_inplace_power
+
.. c:member:: binaryfunc PyNumberMethods.nb_inplace_lshift
+
+ .. corresponding-type-slot:: Py_nb_inplace_lshift
+
.. c:member:: binaryfunc PyNumberMethods.nb_inplace_rshift
+
+ .. corresponding-type-slot:: Py_nb_inplace_rshift
+
.. c:member:: binaryfunc PyNumberMethods.nb_inplace_and
+
+ .. corresponding-type-slot:: Py_nb_inplace_and
+
.. c:member:: binaryfunc PyNumberMethods.nb_inplace_xor
+
+ .. corresponding-type-slot:: Py_nb_inplace_xor
+
.. c:member:: binaryfunc PyNumberMethods.nb_inplace_or
+
+ .. corresponding-type-slot:: Py_nb_inplace_or
+
.. c:member:: binaryfunc PyNumberMethods.nb_floor_divide
+
+ .. corresponding-type-slot:: Py_nb_floor_divide
+
.. c:member:: binaryfunc PyNumberMethods.nb_true_divide
+
+ .. corresponding-type-slot:: Py_nb_true_divide
+
.. c:member:: binaryfunc PyNumberMethods.nb_inplace_floor_divide
+
+ .. corresponding-type-slot:: Py_nb_inplace_floor_divide
+
.. c:member:: binaryfunc PyNumberMethods.nb_inplace_true_divide
+
+ .. corresponding-type-slot:: Py_nb_inplace_true_divide
+
.. c:member:: unaryfunc PyNumberMethods.nb_index
+
+ .. corresponding-type-slot:: Py_nb_index
+
.. c:member:: binaryfunc PyNumberMethods.nb_matrix_multiply
+
+ .. corresponding-type-slot:: Py_nb_matrix_multiply
+
.. c:member:: binaryfunc PyNumberMethods.nb_inplace_matrix_multiply
+ .. corresponding-type-slot:: Py_nb_inplace_matrix_multiply
+
+
.. _mapping-structs:
@@ -2683,12 +2849,16 @@ Mapping Object Structures
.. c:member:: lenfunc PyMappingMethods.mp_length
+ .. corresponding-type-slot:: Py_mp_length
+
This function is used by :c:func:`PyMapping_Size` and
:c:func:`PyObject_Size`, and has the same signature. This slot may be set to
``NULL`` if the object has no defined length.
.. c:member:: binaryfunc PyMappingMethods.mp_subscript
+ .. corresponding-type-slot:: Py_mp_subscript
+
This function is used by :c:func:`PyObject_GetItem` and
:c:func:`PySequence_GetSlice`, and has the same signature as
:c:func:`!PyObject_GetItem`. This slot must be filled for the
@@ -2697,6 +2867,8 @@ Mapping Object Structures
.. c:member:: objobjargproc PyMappingMethods.mp_ass_subscript
+ .. corresponding-type-slot:: Py_mp_ass_subscript
+
This function is used by :c:func:`PyObject_SetItem`,
:c:func:`PyObject_DelItem`, :c:func:`PySequence_SetSlice` and
:c:func:`PySequence_DelSlice`. It has the same signature as
@@ -2720,6 +2892,8 @@ Sequence Object Structures
.. c:member:: lenfunc PySequenceMethods.sq_length
+ .. corresponding-type-slot:: Py_sq_length
+
This function is used by :c:func:`PySequence_Size` and
:c:func:`PyObject_Size`, and has the same signature. It is also used for
handling negative indices via the :c:member:`~PySequenceMethods.sq_item`
@@ -2727,18 +2901,24 @@ Sequence Object Structures
.. c:member:: binaryfunc PySequenceMethods.sq_concat
+ .. corresponding-type-slot:: Py_sq_concat
+
This function is used by :c:func:`PySequence_Concat` and has the same
signature. It is also used by the ``+`` operator, after trying the numeric
addition via the :c:member:`~PyNumberMethods.nb_add` slot.
.. c:member:: ssizeargfunc PySequenceMethods.sq_repeat
+ .. corresponding-type-slot:: Py_sq_repeat
+
This function is used by :c:func:`PySequence_Repeat` and has the same
signature. It is also used by the ``*`` operator, after trying numeric
multiplication via the :c:member:`~PyNumberMethods.nb_multiply` slot.
.. c:member:: ssizeargfunc PySequenceMethods.sq_item
+ .. corresponding-type-slot:: Py_sq_item
+
This function is used by :c:func:`PySequence_GetItem` and has the same
signature. It is also used by :c:func:`PyObject_GetItem`, after trying
the subscription via the :c:member:`~PyMappingMethods.mp_subscript` slot.
@@ -2752,6 +2932,8 @@ Sequence Object Structures
.. c:member:: ssizeobjargproc PySequenceMethods.sq_ass_item
+ .. corresponding-type-slot:: Py_sq_ass_item
+
This function is used by :c:func:`PySequence_SetItem` and has the same
signature. It is also used by :c:func:`PyObject_SetItem` and
:c:func:`PyObject_DelItem`, after trying the item assignment and deletion
@@ -2761,6 +2943,8 @@ Sequence Object Structures
.. c:member:: objobjproc PySequenceMethods.sq_contains
+ .. corresponding-type-slot:: Py_sq_contains
+
This function may be used by :c:func:`PySequence_Contains` and has the same
signature. This slot may be left to ``NULL``, in this case
:c:func:`!PySequence_Contains` simply traverses the sequence until it
@@ -2768,6 +2952,8 @@ Sequence Object Structures
.. c:member:: binaryfunc PySequenceMethods.sq_inplace_concat
+ .. corresponding-type-slot:: Py_sq_inplace_concat
+
This function is used by :c:func:`PySequence_InPlaceConcat` and has the same
signature. It should modify its first operand, and return it. This slot
may be left to ``NULL``, in this case :c:func:`!PySequence_InPlaceConcat`
@@ -2777,6 +2963,8 @@ Sequence Object Structures
.. c:member:: ssizeargfunc PySequenceMethods.sq_inplace_repeat
+ .. corresponding-type-slot:: Py_sq_inplace_repeat
+
This function is used by :c:func:`PySequence_InPlaceRepeat` and has the same
signature. It should modify its first operand, and return it. This slot
may be left to ``NULL``, in this case :c:func:`!PySequence_InPlaceRepeat`
@@ -2802,6 +2990,8 @@ Buffer Object Structures
.. c:member:: getbufferproc PyBufferProcs.bf_getbuffer
+ .. corresponding-type-slot:: Py_bf_getbuffer
+
The signature of this function is::
int (PyObject *exporter, Py_buffer *view, int flags);
@@ -2851,6 +3041,8 @@ Buffer Object Structures
.. c:member:: releasebufferproc PyBufferProcs.bf_releasebuffer
+ .. corresponding-type-slot:: Py_bf_releasebuffer
+
The signature of this function is::
void (PyObject *exporter, Py_buffer *view);
@@ -2905,6 +3097,8 @@ Async Object Structures
.. c:member:: unaryfunc PyAsyncMethods.am_await
+ .. corresponding-type-slot:: Py_am_await
+
The signature of this function is::
PyObject *am_await(PyObject *self);
@@ -2916,6 +3110,8 @@ Async Object Structures
.. c:member:: unaryfunc PyAsyncMethods.am_aiter
+ .. corresponding-type-slot:: Py_am_aiter
+
The signature of this function is::
PyObject *am_aiter(PyObject *self);
@@ -2928,6 +3124,8 @@ Async Object Structures
.. c:member:: unaryfunc PyAsyncMethods.am_anext
+ .. corresponding-type-slot:: Py_am_anext
+
The signature of this function is::
PyObject *am_anext(PyObject *self);
@@ -2938,6 +3136,8 @@ Async Object Structures
.. c:member:: sendfunc PyAsyncMethods.am_send
+ .. corresponding-type-slot:: Py_am_send
+
The signature of this function is::
PySendResult am_send(PyObject *self, PyObject *arg, PyObject **result);
diff --git a/Doc/c-api/unicode.rst b/Doc/c-api/unicode.rst
index 22b0a6aff6e..ca7c8bb11a5 100644
--- a/Doc/c-api/unicode.rst
+++ b/Doc/c-api/unicode.rst
@@ -321,12 +321,22 @@ These APIs can be used to work with surrogates:
Check if *ch* is a low surrogate (``0xDC00 <= ch <= 0xDFFF``).
+.. c:function:: Py_UCS4 Py_UNICODE_HIGH_SURROGATE(Py_UCS4 ch)
+
+ Return the high UTF-16 surrogate (``0xD800`` to ``0xDBFF``) for a Unicode
+ code point in the range ``[0x10000; 0x10FFFF]``.
+
+.. c:function:: Py_UCS4 Py_UNICODE_LOW_SURROGATE(Py_UCS4 ch)
+
+ Return the low UTF-16 surrogate (``0xDC00`` to ``0xDFFF``) for a Unicode
+ code point in the range ``[0x10000; 0x10FFFF]``.
+
.. c:function:: Py_UCS4 Py_UNICODE_JOIN_SURROGATES(Py_UCS4 high, Py_UCS4 low)
Join two surrogate code points and return a single :c:type:`Py_UCS4` value.
*high* and *low* are respectively the leading and trailing surrogates in a
- surrogate pair. *high* must be in the range [0xD800; 0xDBFF] and *low* must
- be in the range [0xDC00; 0xDFFF].
+ surrogate pair. *high* must be in the range ``[0xD800; 0xDBFF]`` and *low* must
+ be in the range ``[0xDC00; 0xDFFF]``.
Creating and accessing Unicode strings
diff --git a/Doc/c-api/veryhigh.rst b/Doc/c-api/veryhigh.rst
index ee0595a9e08..3b07b5fbed5 100644
--- a/Doc/c-api/veryhigh.rst
+++ b/Doc/c-api/veryhigh.rst
@@ -13,8 +13,9 @@ the interpreter.
Several of these functions accept a start symbol from the grammar as a
parameter. The available start symbols are :c:data:`Py_eval_input`,
-:c:data:`Py_file_input`, and :c:data:`Py_single_input`. These are described
-following the functions which accept them as parameters.
+:c:data:`Py_file_input`, :c:data:`Py_single_input`, and
+:c:data:`Py_func_type_input`. These are described following the functions
+which accept them as parameters.
Note also that several of these functions take :c:expr:`FILE*` parameters. One
particular issue which needs to be handled carefully is that the :c:type:`FILE`
@@ -99,6 +100,20 @@ the same library that the Python runtime is using.
Otherwise, Python may not handle script file with LF line ending correctly.
+.. c:function:: int PyRun_InteractiveOneObject(FILE *fp, PyObject *filename, PyCompilerFlags *flags)
+
+ Read and execute a single statement from a file associated with an
+ interactive device according to the *flags* argument. The user will be
+ prompted using ``sys.ps1`` and ``sys.ps2``. *filename* must be a Python
+ :class:`str` object.
+
+ Returns ``0`` when the input was
+ executed successfully, ``-1`` if there was an exception, or an error code
+ from the :file:`errcode.h` include file distributed as part of Python if
+ there was a parse error. (Note that :file:`errcode.h` is not included by
+ :file:`Python.h`, so must be included specifically if needed.)
+
+
.. c:function:: int PyRun_InteractiveOne(FILE *fp, const char *filename)
This is a simplified interface to :c:func:`PyRun_InteractiveOneFlags` below,
@@ -107,17 +122,10 @@ the same library that the Python runtime is using.
.. c:function:: int PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
- Read and execute a single statement from a file associated with an
- interactive device according to the *flags* argument. The user will be
- prompted using ``sys.ps1`` and ``sys.ps2``. *filename* is decoded from the
+ Similar to :c:func:`PyRun_InteractiveOneObject`, but *filename* is a
+ :c:expr:`const char*`, which is decoded from the
:term:`filesystem encoding and error handler`.
- Returns ``0`` when the input was
- executed successfully, ``-1`` if there was an exception, or an error code
- from the :file:`errcode.h` include file distributed as part of Python if
- there was a parse error. (Note that :file:`errcode.h` is not included by
- :file:`Python.h`, so must be included specifically if needed.)
-
.. c:function:: int PyRun_InteractiveLoop(FILE *fp, const char *filename)
@@ -140,7 +148,7 @@ the same library that the Python runtime is using.
interpreter prompt is about to become idle and wait for user input
from the terminal. The return value is ignored. Overriding this
hook can be used to integrate the interpreter's prompt with other
- event loops, as done in the :file:`Modules/_tkinter.c` in the
+ event loops, as done in :file:`Modules/_tkinter.c` in the
Python source code.
.. versionchanged:: 3.12
@@ -183,8 +191,7 @@ the same library that the Python runtime is using.
objects *globals* and *locals* with the compiler flags specified by
*flags*. *globals* must be a dictionary; *locals* can be any object
that implements the mapping protocol. The parameter *start* specifies
- the start symbol and must one of the following:
- :c:data:`Py_eval_input`, :c:data:`Py_file_input`, or :c:data:`Py_single_input`.
+ the start symbol and must one of the :ref:`available start symbols `.
Returns the result of executing the code as a Python object, or ``NULL`` if an
exception was raised.
@@ -233,8 +240,8 @@ the same library that the Python runtime is using.
Parse and compile the Python source code in *str*, returning the resulting code
object. The start symbol is given by *start*; this can be used to constrain the
- code which can be compiled and should be :c:data:`Py_eval_input`,
- :c:data:`Py_file_input`, or :c:data:`Py_single_input`. The filename specified by
+ code which can be compiled and should be :ref:`available start symbols
+ `. The filename specified by
*filename* is used to construct the code object and may appear in tracebacks or
:exc:`SyntaxError` exception messages. This returns ``NULL`` if the code
cannot be parsed or compiled.
@@ -297,32 +304,6 @@ the same library that the Python runtime is using.
true on success, false on failure.
-.. c:var:: int Py_eval_input
-
- .. index:: single: Py_CompileString (C function)
-
- The start symbol from the Python grammar for isolated expressions; for use with
- :c:func:`Py_CompileString`.
-
-
-.. c:var:: int Py_file_input
-
- .. index:: single: Py_CompileString (C function)
-
- The start symbol from the Python grammar for sequences of statements as read
- from a file or other source; for use with :c:func:`Py_CompileString`. This is
- the symbol to use when compiling arbitrarily long Python source code.
-
-
-.. c:var:: int Py_single_input
-
- .. index:: single: Py_CompileString (C function)
-
- The start symbol from the Python grammar for a single statement; for use with
- :c:func:`Py_CompileString`. This is the symbol used for the interactive
- interpreter loop.
-
-
.. c:struct:: PyCompilerFlags
This is the structure used to hold compiler flags. In cases where code is only
@@ -366,3 +347,52 @@ the same library that the Python runtime is using.
as :c:macro:`CO_FUTURE_ANNOTATIONS` to enable features normally
selectable using :ref:`future statements `.
See :ref:`c_codeobject_flags` for a complete list.
+
+
+.. _start-symbols:
+
+Available start symbols
+^^^^^^^^^^^^^^^^^^^^^^^
+
+
+.. c:var:: int Py_eval_input
+
+ .. index:: single: Py_CompileString (C function)
+
+ The start symbol from the Python grammar for isolated expressions; for use with
+ :c:func:`Py_CompileString`.
+
+
+.. c:var:: int Py_file_input
+
+ .. index:: single: Py_CompileString (C function)
+
+ The start symbol from the Python grammar for sequences of statements as read
+ from a file or other source; for use with :c:func:`Py_CompileString`. This is
+ the symbol to use when compiling arbitrarily long Python source code.
+
+
+.. c:var:: int Py_single_input
+
+ .. index:: single: Py_CompileString (C function)
+
+ The start symbol from the Python grammar for a single statement; for use with
+ :c:func:`Py_CompileString`. This is the symbol used for the interactive
+ interpreter loop.
+
+
+.. c:var:: int Py_func_type_input
+
+ .. index:: single: Py_CompileString (C function)
+
+ The start symbol from the Python grammar for a function type; for use with
+ :c:func:`Py_CompileString`. This is used to parse "signature type comments"
+ from :pep:`484`.
+
+ This requires the :c:macro:`PyCF_ONLY_AST` flag to be set.
+
+ .. seealso::
+ * :py:class:`ast.FunctionType`
+ * :pep:`484`
+
+ .. versionadded:: 3.8
diff --git a/Doc/c-api/weakref.rst b/Doc/c-api/weakref.rst
index 14ec9d951c4..db6ae0a9d4e 100644
--- a/Doc/c-api/weakref.rst
+++ b/Doc/c-api/weakref.rst
@@ -19,7 +19,14 @@ as much as it can.
.. c:function:: int PyWeakref_CheckRef(PyObject *ob)
- Return non-zero if *ob* is a reference object. This function always succeeds.
+ Return non-zero if *ob* is a reference object or a subclass of the reference
+ type. This function always succeeds.
+
+
+.. c:function:: int PyWeakref_CheckRefExact(PyObject *ob)
+
+ Return non-zero if *ob* is a reference object, but not a subclass of the
+ reference type. This function always succeeds.
.. c:function:: int PyWeakref_CheckProxy(PyObject *ob)
@@ -38,6 +45,10 @@ as much as it can.
weakly referenceable object, or if *callback* is not callable, ``None``, or
``NULL``, this will return ``NULL`` and raise :exc:`TypeError`.
+ .. seealso::
+ :c:func:`PyType_SUPPORTS_WEAKREFS` for checking if *ob* is weakly
+ referenceable.
+
.. c:function:: PyObject* PyWeakref_NewProxy(PyObject *ob, PyObject *callback)
@@ -50,6 +61,10 @@ as much as it can.
is not a weakly referenceable object, or if *callback* is not callable,
``None``, or ``NULL``, this will return ``NULL`` and raise :exc:`TypeError`.
+ .. seealso::
+ :c:func:`PyType_SUPPORTS_WEAKREFS` for checking if *ob* is weakly
+ referenceable.
+
.. c:function:: int PyWeakref_GetRef(PyObject *ref, PyObject **pobj)
diff --git a/Doc/conf.py b/Doc/conf.py
index f1dda10052e..a4275835059 100644
--- a/Doc/conf.py
+++ b/Doc/conf.py
@@ -226,9 +226,6 @@
# Temporary undocumented names.
# In future this list must be empty.
nitpick_ignore += [
- # Undocumented public C macros
- ('c:macro', 'Py_BUILD_ASSERT'),
- ('c:macro', 'Py_BUILD_ASSERT_EXPR'),
# Do not error nit-picky mode builds when _SubParsersAction.add_parser cannot
# be resolved, as the method is currently undocumented. For context, see
# https://github.com/python/cpython/pull/103289.
@@ -364,7 +361,7 @@
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, document class [howto/manual]).
-_stdauthor = 'Guido van Rossum and the Python development team'
+_stdauthor = 'The Python development team'
latex_documents = [
('c-api/index', 'c-api.tex', 'The Python/C API', _stdauthor, 'manual'),
(
diff --git a/Doc/data/stable_abi.dat b/Doc/data/stable_abi.dat
index 7ad5f3ecfab..95e032655cf 100644
--- a/Doc/data/stable_abi.dat
+++ b/Doc/data/stable_abi.dat
@@ -1,7 +1,21 @@
role,name,added,ifdef_note,struct_abi_kind
+macro,METH_CLASS,3.2,,
+macro,METH_COEXIST,3.2,,
+macro,METH_FASTCALL,3.7,,
+macro,METH_METHOD,3.7,,
+macro,METH_NOARGS,3.2,,
+macro,METH_O,3.2,,
+macro,METH_STATIC,3.2,,
+macro,METH_VARARGS,3.2,,
macro,PY_VECTORCALL_ARGUMENTS_OFFSET,3.12,,
type,PyABIInfo,3.15,,full-abi
func,PyABIInfo_Check,3.15,,
+macro,PyABIInfo_DEFAULT_ABI_VERSION,3.15,,
+macro,PyABIInfo_DEFAULT_FLAGS,3.15,,
+macro,PyABIInfo_FREETHREADED,3.15,,
+macro,PyABIInfo_FREETHREADING_AGNOSTIC,3.15,,
+macro,PyABIInfo_GIL,3.15,,
+macro,PyABIInfo_STABLE,3.15,,
macro,PyABIInfo_VAR,3.15,,
func,PyAIter_Check,3.10,,
func,PyArg_Parse,3.2,,
@@ -11,6 +25,26 @@ func,PyArg_UnpackTuple,3.2,,
func,PyArg_VaParse,3.2,,
func,PyArg_VaParseTupleAndKeywords,3.2,,
func,PyArg_ValidateKeywordArguments,3.2,,
+macro,PyBUF_ANY_CONTIGUOUS,3.11,,
+macro,PyBUF_CONTIG,3.11,,
+macro,PyBUF_CONTIG_RO,3.11,,
+macro,PyBUF_C_CONTIGUOUS,3.11,,
+macro,PyBUF_FORMAT,3.11,,
+macro,PyBUF_FULL,3.11,,
+macro,PyBUF_FULL_RO,3.11,,
+macro,PyBUF_F_CONTIGUOUS,3.11,,
+macro,PyBUF_INDIRECT,3.11,,
+macro,PyBUF_MAX_NDIM,3.11,,
+macro,PyBUF_ND,3.11,,
+macro,PyBUF_READ,3.11,,
+macro,PyBUF_RECORDS,3.11,,
+macro,PyBUF_RECORDS_RO,3.11,,
+macro,PyBUF_SIMPLE,3.11,,
+macro,PyBUF_STRIDED,3.11,,
+macro,PyBUF_STRIDED_RO,3.11,,
+macro,PyBUF_STRIDES,3.11,,
+macro,PyBUF_WRITABLE,3.11,,
+macro,PyBUF_WRITE,3.11,,
data,PyBaseObject_Type,3.2,,
func,PyBool_FromLong,3.2,,
data,PyBool_Type,3.2,,
@@ -126,6 +160,7 @@ func,PyDict_Merge,3.2,,
func,PyDict_MergeFromSeq2,3.2,,
func,PyDict_New,3.2,,
func,PyDict_Next,3.2,,
+func,PyDict_SetDefaultRef,3.15,,
func,PyDict_SetItem,3.2,,
func,PyDict_SetItemString,3.2,,
func,PyDict_Size,3.2,,
@@ -391,6 +426,7 @@ func,PyLong_FromUnsignedNativeBytes,3.14,,
func,PyLong_FromVoidPtr,3.2,,
func,PyLong_GetInfo,3.2,,
data,PyLong_Type,3.2,,
+macro,PyMODEXPORT_FUNC,3.15,,
data,PyMap_Type,3.2,,
func,PyMapping_Check,3.2,,
func,PyMapping_GetItemString,3.2,,
@@ -437,8 +473,10 @@ func,PyModule_AddObjectRef,3.10,,
func,PyModule_AddStringConstant,3.2,,
func,PyModule_AddType,3.10,,
func,PyModule_Create2,3.2,,
+func,PyModule_Exec,3.15,,
func,PyModule_ExecDef,3.7,,
func,PyModule_FromDefAndSpec2,3.7,,
+func,PyModule_FromSlotsAndSpec,3.15,,
func,PyModule_GetDef,3.2,,
func,PyModule_GetDict,3.2,,
func,PyModule_GetFilename,3.2,,
@@ -446,6 +484,8 @@ func,PyModule_GetFilenameObject,3.2,,
func,PyModule_GetName,3.2,,
func,PyModule_GetNameObject,3.7,,
func,PyModule_GetState,3.2,,
+func,PyModule_GetStateSize,3.15,,
+func,PyModule_GetToken,3.15,,
func,PyModule_New,3.2,,
func,PyModule_NewObject,3.7,,
func,PyModule_SetDocString,3.7,,
@@ -704,6 +744,7 @@ func,PyType_GetFlags,3.2,,
func,PyType_GetFullyQualifiedName,3.13,,
func,PyType_GetModule,3.10,,
func,PyType_GetModuleByDef,3.13,,
+func,PyType_GetModuleByToken,3.15,,
func,PyType_GetModuleName,3.13,,
func,PyType_GetModuleState,3.10,,
func,PyType_GetName,3.11,,
@@ -836,6 +877,14 @@ func,PyWeakref_NewRef,3.2,,
data,PyWrapperDescr_Type,3.2,,
func,PyWrapper_New,3.2,,
data,PyZip_Type,3.2,,
+macro,Py_ASNATIVEBYTES_ALLOW_INDEX,3.14,,
+macro,Py_ASNATIVEBYTES_BIG_ENDIAN,3.14,,
+macro,Py_ASNATIVEBYTES_DEFAULTS,3.14,,
+macro,Py_ASNATIVEBYTES_LITTLE_ENDIAN,3.14,,
+macro,Py_ASNATIVEBYTES_NATIVE_ENDIAN,3.14,,
+macro,Py_ASNATIVEBYTES_REJECT_NEGATIVE,3.14,,
+macro,Py_ASNATIVEBYTES_UNSIGNED_BUFFER,3.14,,
+macro,Py_AUDIT_READ,3.12,,
func,Py_AddPendingCall,3.2,,
func,Py_AtExit,3.2,,
macro,Py_BEGIN_ALLOW_THREADS,3.2,,
@@ -882,22 +931,141 @@ func,Py_NewInterpreter,3.2,,
func,Py_NewRef,3.10,,
func,Py_PACK_FULL_VERSION,3.14,,
func,Py_PACK_VERSION,3.14,,
+macro,Py_READONLY,3.12,,
func,Py_REFCNT,3.14,,
+macro,Py_RELATIVE_OFFSET,3.12,,
func,Py_ReprEnter,3.2,,
func,Py_ReprLeave,3.2,,
func,Py_SetProgramName,3.2,,
func,Py_SetPythonHome,3.2,,
func,Py_SetRecursionLimit,3.2,,
+macro,Py_TPFLAGS_BASETYPE,3.2,,
+macro,Py_TPFLAGS_DEFAULT,3.2,,
+macro,Py_TPFLAGS_HAVE_GC,3.2,,
+macro,Py_TPFLAGS_HAVE_VECTORCALL,3.12,,
+macro,Py_TPFLAGS_ITEMS_AT_END,3.12,,
+macro,Py_TPFLAGS_METHOD_DESCRIPTOR,3.8,,
+macro,Py_TP_USE_SPEC,3.14,,
func,Py_TYPE,3.14,,
+macro,Py_T_BOOL,3.12,,
+macro,Py_T_BYTE,3.12,,
+macro,Py_T_CHAR,3.12,,
+macro,Py_T_DOUBLE,3.12,,
+macro,Py_T_FLOAT,3.12,,
+macro,Py_T_INT,3.12,,
+macro,Py_T_LONG,3.12,,
+macro,Py_T_LONGLONG,3.12,,
+macro,Py_T_OBJECT_EX,3.12,,
+macro,Py_T_PYSSIZET,3.12,,
+macro,Py_T_SHORT,3.12,,
+macro,Py_T_STRING,3.12,,
+macro,Py_T_STRING_INPLACE,3.12,,
+macro,Py_T_UBYTE,3.12,,
+macro,Py_T_UINT,3.12,,
+macro,Py_T_ULONG,3.12,,
+macro,Py_T_ULONGLONG,3.12,,
+macro,Py_T_USHORT,3.12,,
type,Py_UCS4,3.2,,
macro,Py_UNBLOCK_THREADS,3.2,,
data,Py_UTF8Mode,3.8,,
func,Py_VaBuildValue,3.2,,
data,Py_Version,3.11,,
func,Py_XNewRef,3.10,,
+macro,Py_am_aiter,3.5,,
+macro,Py_am_anext,3.5,,
+macro,Py_am_await,3.5,,
+macro,Py_am_send,3.10,,
+macro,Py_bf_getbuffer,3.11,,
+macro,Py_bf_releasebuffer,3.11,,
type,Py_buffer,3.11,,full-abi
type,Py_intptr_t,3.2,,
+macro,Py_mod_abi,3.15,,
+macro,Py_mod_doc,3.15,,
+macro,Py_mod_methods,3.15,,
+macro,Py_mod_name,3.15,,
+macro,Py_mod_state_clear,3.15,,
+macro,Py_mod_state_free,3.15,,
+macro,Py_mod_state_size,3.15,,
+macro,Py_mod_state_traverse,3.15,,
+macro,Py_mod_token,3.15,,
+macro,Py_mp_ass_subscript,3.2,,
+macro,Py_mp_length,3.2,,
+macro,Py_mp_subscript,3.2,,
+macro,Py_nb_absolute,3.2,,
+macro,Py_nb_add,3.2,,
+macro,Py_nb_and,3.2,,
+macro,Py_nb_bool,3.2,,
+macro,Py_nb_divmod,3.2,,
+macro,Py_nb_float,3.2,,
+macro,Py_nb_floor_divide,3.2,,
+macro,Py_nb_index,3.2,,
+macro,Py_nb_inplace_add,3.2,,
+macro,Py_nb_inplace_and,3.2,,
+macro,Py_nb_inplace_floor_divide,3.2,,
+macro,Py_nb_inplace_lshift,3.2,,
+macro,Py_nb_inplace_matrix_multiply,3.5,,
+macro,Py_nb_inplace_multiply,3.2,,
+macro,Py_nb_inplace_or,3.2,,
+macro,Py_nb_inplace_power,3.2,,
+macro,Py_nb_inplace_remainder,3.2,,
+macro,Py_nb_inplace_rshift,3.2,,
+macro,Py_nb_inplace_subtract,3.2,,
+macro,Py_nb_inplace_true_divide,3.2,,
+macro,Py_nb_inplace_xor,3.2,,
+macro,Py_nb_int,3.2,,
+macro,Py_nb_invert,3.2,,
+macro,Py_nb_lshift,3.2,,
+macro,Py_nb_matrix_multiply,3.5,,
+macro,Py_nb_multiply,3.2,,
+macro,Py_nb_negative,3.2,,
+macro,Py_nb_or,3.2,,
+macro,Py_nb_positive,3.2,,
+macro,Py_nb_power,3.2,,
+macro,Py_nb_remainder,3.2,,
+macro,Py_nb_rshift,3.2,,
+macro,Py_nb_subtract,3.2,,
+macro,Py_nb_true_divide,3.2,,
+macro,Py_nb_xor,3.2,,
+macro,Py_sq_ass_item,3.2,,
+macro,Py_sq_concat,3.2,,
+macro,Py_sq_contains,3.2,,
+macro,Py_sq_inplace_concat,3.2,,
+macro,Py_sq_inplace_repeat,3.2,,
+macro,Py_sq_item,3.2,,
+macro,Py_sq_length,3.2,,
+macro,Py_sq_repeat,3.2,,
type,Py_ssize_t,3.2,,
+macro,Py_tp_alloc,3.2,,
+macro,Py_tp_base,3.2,,
+macro,Py_tp_bases,3.2,,
+macro,Py_tp_call,3.2,,
+macro,Py_tp_clear,3.2,,
+macro,Py_tp_dealloc,3.2,,
+macro,Py_tp_del,3.2,,
+macro,Py_tp_descr_get,3.2,,
+macro,Py_tp_descr_set,3.2,,
+macro,Py_tp_doc,3.2,,
+macro,Py_tp_finalize,3.5,,
+macro,Py_tp_free,3.2,,
+macro,Py_tp_getattr,3.2,,
+macro,Py_tp_getattro,3.2,,
+macro,Py_tp_getset,3.2,,
+macro,Py_tp_hash,3.2,,
+macro,Py_tp_init,3.2,,
+macro,Py_tp_is_gc,3.2,,
+macro,Py_tp_iter,3.2,,
+macro,Py_tp_iternext,3.2,,
+macro,Py_tp_members,3.2,,
+macro,Py_tp_methods,3.2,,
+macro,Py_tp_new,3.2,,
+macro,Py_tp_repr,3.2,,
+macro,Py_tp_richcompare,3.2,,
+macro,Py_tp_setattr,3.2,,
+macro,Py_tp_setattro,3.2,,
+macro,Py_tp_str,3.2,,
+macro,Py_tp_token,3.14,,
+macro,Py_tp_traverse,3.2,,
+macro,Py_tp_vectorcall,3.14,,
type,Py_uintptr_t,3.2,,
type,allocfunc,3.2,,
type,binaryfunc,3.2,,
diff --git a/Doc/deprecations/c-api-pending-removal-in-3.20.rst b/Doc/deprecations/c-api-pending-removal-in-3.20.rst
index 82f975d6ed4..18623b19a2a 100644
--- a/Doc/deprecations/c-api-pending-removal-in-3.20.rst
+++ b/Doc/deprecations/c-api-pending-removal-in-3.20.rst
@@ -5,3 +5,5 @@ Pending removal in Python 3.20
Use :c:func:`PyComplex_AsCComplex` and :c:func:`PyComplex_FromCComplex`
to convert a Python complex number to/from the C :c:type:`Py_complex`
representation.
+
+* Macros :c:macro:`!Py_MATH_PIl` and :c:macro:`!Py_MATH_El`.
diff --git a/Doc/deprecations/pending-removal-in-3.13.rst b/Doc/deprecations/pending-removal-in-3.13.rst
index 2fd2f12cc6a..d5b8c80e8f9 100644
--- a/Doc/deprecations/pending-removal-in-3.13.rst
+++ b/Doc/deprecations/pending-removal-in-3.13.rst
@@ -38,15 +38,3 @@ APIs:
* :meth:`!unittest.TestProgram.usageExit` (:gh:`67048`)
* :class:`!webbrowser.MacOSX` (:gh:`86421`)
* :class:`classmethod` descriptor chaining (:gh:`89519`)
-* :mod:`importlib.resources` deprecated methods:
-
- * ``contents()``
- * ``is_resource()``
- * ``open_binary()``
- * ``open_text()``
- * ``path()``
- * ``read_binary()``
- * ``read_text()``
-
- Use :func:`importlib.resources.files` instead. Refer to `importlib-resources: Migrating from Legacy
- `_ (:gh:`106531`)
diff --git a/Doc/deprecations/pending-removal-in-3.16.rst b/Doc/deprecations/pending-removal-in-3.16.rst
index cdd76ee693f..b00c7002b03 100644
--- a/Doc/deprecations/pending-removal-in-3.16.rst
+++ b/Doc/deprecations/pending-removal-in-3.16.rst
@@ -63,9 +63,9 @@ Pending removal in Python 3.16
* :mod:`logging`:
- Support for custom logging handlers with the *strm* argument is deprecated
- and scheduled for removal in Python 3.16. Define handlers with the *stream*
- argument instead. (Contributed by Mariusz Felisiak in :gh:`115032`.)
+ * Support for custom logging handlers with the *strm* argument is deprecated
+ and scheduled for removal in Python 3.16. Define handlers with the *stream*
+ argument instead. (Contributed by Mariusz Felisiak in :gh:`115032`.)
* :mod:`mimetypes`:
diff --git a/Doc/deprecations/pending-removal-in-3.17.rst b/Doc/deprecations/pending-removal-in-3.17.rst
index 0a1c2f08cab..e769c9d371e 100644
--- a/Doc/deprecations/pending-removal-in-3.17.rst
+++ b/Doc/deprecations/pending-removal-in-3.17.rst
@@ -23,6 +23,12 @@ Pending removal in Python 3.17
(Contributed by Shantanu Jain in :gh:`91896`.)
+* :mod:`encodings`:
+
+ - Passing non-ascii *encoding* names to :func:`encodings.normalize_encoding`
+ is deprecated and scheduled for removal in Python 3.17.
+ (Contributed by Stan Ulbrych in :gh:`136702`)
+
* :mod:`typing`:
- Before Python 3.14, old-style unions were implemented using the private class
diff --git a/Doc/deprecations/pending-removal-in-future.rst b/Doc/deprecations/pending-removal-in-future.rst
index 7ed430625f3..30186741670 100644
--- a/Doc/deprecations/pending-removal-in-future.rst
+++ b/Doc/deprecations/pending-removal-in-future.rst
@@ -76,7 +76,7 @@ although there is currently no date scheduled for their removal.
* :mod:`mailbox`: Use of StringIO input and text mode is deprecated, use
BytesIO and binary mode instead.
-* :mod:`os`: Calling :func:`os.register_at_fork` in multi-threaded process.
+* :mod:`os`: Calling :func:`os.register_at_fork` in a multi-threaded process.
* :class:`!pydoc.ErrorDuringImport`: A tuple value for *exc_info* parameter is
deprecated, use an exception instance.
diff --git a/Doc/glossary.rst b/Doc/glossary.rst
index c0ca0be304e..a4066d42927 100644
--- a/Doc/glossary.rst
+++ b/Doc/glossary.rst
@@ -1025,6 +1025,15 @@ Glossary
applied to all scopes, only those relying on a known set of local
and nonlocal variable names are restricted to optimized scopes.
+ optional module
+ An :term:`extension module` that is part of the :term:`standard library`,
+ but may be absent in some builds of :term:`CPython`,
+ usually due to missing third-party libraries or because the module
+ is not available for a given platform.
+
+ See :ref:`optional-module-requirements` for a list of optional modules
+ that require third-party libraries.
+
package
A Python :term:`module` which can contain submodules or recursively,
subpackages. Technically, a package is a Python module with a
diff --git a/Doc/howto/a-conceptual-overview-of-asyncio.rst b/Doc/howto/a-conceptual-overview-of-asyncio.rst
index af1e39480cc..6800a24bc95 100644
--- a/Doc/howto/a-conceptual-overview-of-asyncio.rst
+++ b/Doc/howto/a-conceptual-overview-of-asyncio.rst
@@ -1,7 +1,7 @@
.. _a-conceptual-overview-of-asyncio:
****************************************
-A Conceptual Overview of :mod:`!asyncio`
+A conceptual overview of :mod:`!asyncio`
****************************************
This :ref:`HOWTO ` article seeks to help you build a sturdy mental
@@ -37,15 +37,15 @@ In part 1, we'll cover the main, high-level building blocks of :mod:`!asyncio`:
the event loop, coroutine functions, coroutine objects, tasks, and ``await``.
==========
-Event Loop
+Event loop
==========
Everything in :mod:`!asyncio` happens relative to the event loop.
-It's the star of the show.
+It's the star of the show, but prefers to work behind the scenes, managing
+and coordinating resources.
It's like an orchestra conductor.
-It's behind the scenes managing resources.
Some power is explicitly granted to it, but a lot of its ability to get things
-done comes from the respect and cooperation of its worker bees.
+done comes from the respect and cooperation of its band members.
In more technical terms, the event loop contains a collection of jobs to be run.
Some jobs are added directly by you, and some indirectly by :mod:`!asyncio`.
@@ -59,7 +59,7 @@ This process repeats indefinitely, with the event loop cycling endlessly
onwards.
If there are no more jobs pending execution, the event loop is smart enough to
rest and avoid needlessly wasting CPU cycles, and will come back when there's
-more work to be done.
+more work to be done, such as when I/O operations complete or timers expire.
Effective execution relies on jobs sharing well and cooperating; a greedy job
could hog control and leave the other jobs to starve, rendering the overall
@@ -170,14 +170,14 @@ Roughly speaking, :ref:`tasks ` are coroutines (not coroutine
functions) tied to an event loop.
A task also maintains a list of callback functions whose importance will become
clear in a moment when we discuss :keyword:`await`.
-The recommended way to create tasks is via :func:`asyncio.create_task`.
Creating a task automatically schedules it for execution (by adding a
callback to run it in the event loop's to-do list, that is, collection of jobs).
+The recommended way to create tasks is via :func:`asyncio.create_task`.
-Since there's only one event loop (in each thread), :mod:`!asyncio` takes care of
-associating the task with the event loop for you. As such, there's no need
-to specify the event loop.
+Since there's only one event loop (in each thread), :mod:`!asyncio` takes
+care of associating the task with the event loop for you.
+As such, there's no need to specify the event loop.
::
@@ -250,6 +250,10 @@ different ways::
In a crucial way, the behavior of ``await`` depends on the type of object
being awaited.
+^^^^^^^^^^^^^^
+Awaiting tasks
+^^^^^^^^^^^^^^
+
Awaiting a task will cede control from the current task or coroutine to
the event loop.
In the process of relinquishing control, a few important things happen.
@@ -281,6 +285,10 @@ This is a basic, yet reliable mental model.
In practice, the control handoffs are slightly more complex, but not by much.
In part 2, we'll walk through the details that make this possible.
+^^^^^^^^^^^^^^^^^^^
+Awaiting coroutines
+^^^^^^^^^^^^^^^^^^^
+
**Unlike tasks, awaiting a coroutine does not hand control back to the event
loop!**
Wrapping a coroutine in a task first, then awaiting that would cede
@@ -347,8 +355,10 @@ The design intentionally trades off some conceptual clarity around usage of
``await`` for improved performance.
Each time a task is awaited, control needs to be passed all the way up the
call stack to the event loop.
-That might sound minor, but in a large program with many ``await`` statements and a deep
-call stack, that overhead can add up to a meaningful performance drag.
+Then, the event loop needs to manage its internal state and work through
+its processing logic to resume the next job.
+That might sound minor, but in a large program with many ``await``\ s, that
+overhead can add up to a non-negligible performance drag.
------------------------------------------------
A conceptual overview part 2: the nuts and bolts
@@ -364,7 +374,8 @@ and how to make your own asynchronous operators.
The inner workings of coroutines
================================
-:mod:`!asyncio` leverages four components to pass around control.
+:mod:`!asyncio` leverages four components of Python to pass
+around control.
:meth:`coroutine.send(arg) ` is the method used to start or
resume a coroutine.
@@ -448,9 +459,9 @@ That might sound odd to you. You might be thinking:
That causes the error: ``SyntaxError: yield from not allowed in a coroutine.``
This was intentionally designed for the sake of simplicity -- mandating only
one way of using coroutines.
+ Despite that, ``yield from`` and ``await`` effectively do the same thing.
Initially ``yield`` was barred as well, but was re-accepted to allow for
async generators.
- Despite that, ``yield from`` and ``await`` effectively do the same thing.
=======
Futures
diff --git a/Doc/howto/free-threading-extensions.rst b/Doc/howto/free-threading-extensions.rst
index 3776132c685..5647ab2d87c 100644
--- a/Doc/howto/free-threading-extensions.rst
+++ b/Doc/howto/free-threading-extensions.rst
@@ -203,7 +203,7 @@ Memory Allocation APIs
Python's memory management C API provides functions in three different
:ref:`allocation domains `: "raw", "mem", and "object".
For thread-safety, the free-threaded build requires that only Python objects
-are allocated using the object domain, and that all Python object are
+are allocated using the object domain, and that all Python objects are
allocated using that domain. This differs from the prior Python versions,
where this was only a best practice and not a hard requirement.
@@ -344,12 +344,12 @@ This means you cannot rely on nested critical sections to lock multiple objects
at once, as the inner critical section may suspend the outer ones. Instead, use
:c:macro:`Py_BEGIN_CRITICAL_SECTION2` to lock two objects simultaneously.
-Note that the locks described above are only :c:type:`!PyMutex` based locks.
+Note that the locks described above are only :c:type:`PyMutex` based locks.
The critical section implementation does not know about or affect other locking
mechanisms that might be in use, like POSIX mutexes. Also note that while
-blocking on any :c:type:`!PyMutex` causes the critical sections to be
+blocking on any :c:type:`PyMutex` causes the critical sections to be
suspended, only the mutexes that are part of the critical sections are
-released. If :c:type:`!PyMutex` is used without a critical section, it will
+released. If :c:type:`PyMutex` is used without a critical section, it will
not be released and therefore does not get the same deadlock avoidance.
Important Considerations
@@ -397,7 +397,8 @@ The wheels, shared libraries, and binaries are indicated by a ``t`` suffix.
* `pypa/manylinux `_ supports the
free-threaded build, with the ``t`` suffix, such as ``python3.13t``.
* `pypa/cibuildwheel `_ supports the
- free-threaded build if you set
+ free-threaded build on Python 3.13 and 3.14. On Python 3.14, free-threaded
+ wheels will be built by default. On Python 3.13, you will need to set
`CIBW_ENABLE to cpython-freethreading `_.
Limited C API and Stable ABI
diff --git a/Doc/howto/free-threading-python.rst b/Doc/howto/free-threading-python.rst
index 24069617c47..e4df7a787a2 100644
--- a/Doc/howto/free-threading-python.rst
+++ b/Doc/howto/free-threading-python.rst
@@ -116,12 +116,14 @@ after the main thread is running. The following objects are immortalized:
* :ref:`classes ` (type objects)
Because immortal objects are never deallocated, applications that create many
-objects of these types may see increased memory usage. This is expected to be
-addressed in the 3.14 release.
+objects of these types may see increased memory usage under Python 3.13. This
+has been addressed in the 3.14 release, where the aforementioned objects use
+deferred reference counting to avoid reference count contention.
Additionally, numeric and string literals in the code as well as strings
-returned by :func:`sys.intern` are also immortalized. This behavior is
-expected to remain in the 3.14 free-threaded build.
+returned by :func:`sys.intern` are also immortalized in the 3.13 release. This
+behavior is part of the 3.14 release as well and it is expected to remain in
+future free-threaded builds.
Frame objects
@@ -150,11 +152,12 @@ compared to the default GIL-enabled build. In 3.13, this overhead is about
40% on the `pyperformance `_ suite.
Programs that spend most of their time in C extensions or I/O will see
less of an impact. The largest impact is because the specializing adaptive
-interpreter (:pep:`659`) is disabled in the free-threaded build. We expect
-to re-enable it in a thread-safe way in the 3.14 release. This overhead is
-expected to be reduced in upcoming Python release. We are aiming for an
-overhead of 10% or less on the pyperformance suite compared to the default
-GIL-enabled build.
+interpreter (:pep:`659`) is disabled in the free-threaded build.
+
+The specializing adaptive interpreter has been re-enabled in a thread-safe way
+in the 3.14 release. The performance penalty on single-threaded code in
+free-threaded mode is now roughly 5-10%, depending on the platform and C
+compiler used.
Behavioral changes
diff --git a/Doc/howto/isolating-extensions.rst b/Doc/howto/isolating-extensions.rst
index 7da6dc8a397..6092c75f48f 100644
--- a/Doc/howto/isolating-extensions.rst
+++ b/Doc/howto/isolating-extensions.rst
@@ -353,7 +353,7 @@ garbage collection protocol.
That is, heap types should:
- Have the :c:macro:`Py_TPFLAGS_HAVE_GC` flag.
-- Define a traverse function using ``Py_tp_traverse``, which
+- Define a traverse function using :c:data:`Py_tp_traverse`, which
visits the type (e.g. using ``Py_VISIT(Py_TYPE(self))``).
Please refer to the documentation of
diff --git a/Doc/includes/optional-module.rst b/Doc/includes/optional-module.rst
new file mode 100644
index 00000000000..262e73f2eaa
--- /dev/null
+++ b/Doc/includes/optional-module.rst
@@ -0,0 +1,9 @@
+This is an :term:`optional module`.
+If it is missing from your copy of CPython,
+look for documentation from your distributor (that is,
+whoever provided Python to you).
+If you are the distributor, see :ref:`optional-module-requirements`.
+
+.. Similar notes appear in the docs of the modules:
+ - zipfile
+ - tarfile
diff --git a/Doc/library/argparse.rst b/Doc/library/argparse.rst
index 418f514995d..2a39f248651 100644
--- a/Doc/library/argparse.rst
+++ b/Doc/library/argparse.rst
@@ -638,6 +638,11 @@ by setting ``color`` to ``False``::
... help='an integer for the accumulator')
>>> parser.parse_args(['--help'])
+Note that when ``color=True``, colored output depends on both environment
+variables and terminal capabilities. However, if ``color=False``, colored
+output is always disabled, even if environment variables like ``FORCE_COLOR``
+are set.
+
.. versionadded:: 3.14
@@ -1317,8 +1322,12 @@ attribute is determined by the ``dest`` keyword argument of
For optional argument actions, the value of ``dest`` is normally inferred from
the option strings. :class:`ArgumentParser` generates the value of ``dest`` by
-taking the first long option string and stripping away the initial ``--``
-string. If no long option strings were supplied, ``dest`` will be derived from
+taking the first double-dash long option string and stripping away the initial
+``-`` characters.
+If no double-dash long option strings were supplied, ``dest`` will be derived
+from the first single-dash long option string by stripping the initial ``-``
+character.
+If no long option strings were supplied, ``dest`` will be derived from
the first short option string by stripping the initial ``-`` character. Any
internal ``-`` characters will be converted to ``_`` characters to make sure
the string is a valid attribute name. The examples below illustrate this
@@ -1326,11 +1335,12 @@ behavior::
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('-f', '--foo-bar', '--foo')
+ >>> parser.add_argument('-q', '-quz')
>>> parser.add_argument('-x', '-y')
- >>> parser.parse_args('-f 1 -x 2'.split())
- Namespace(foo_bar='1', x='2')
- >>> parser.parse_args('--foo 1 -y 2'.split())
- Namespace(foo_bar='1', x='2')
+ >>> parser.parse_args('-f 1 -q 2 -x 3'.split())
+ Namespace(foo_bar='1', quz='2', x='3')
+ >>> parser.parse_args('--foo 1 -quz 2 -y 3'.split())
+ Namespace(foo_bar='1', quz='2', x='2')
``dest`` allows a custom attribute name to be provided::
@@ -1339,6 +1349,9 @@ behavior::
>>> parser.parse_args('--foo XXX'.split())
Namespace(bar='XXX')
+.. versionchanged:: next
+ Single-dash long option now takes precedence over short options.
+
.. _deprecated:
@@ -1432,8 +1445,18 @@ this API may be passed as the ``action`` parameter to
>>> parser.parse_args(['--no-foo'])
Namespace(foo=False)
+ Single-dash long options are also supported.
+ For example, negative option ``-nofoo`` is automatically added for
+ positive option ``-foo``.
+ But no additional options are added for short options such as ``-f``.
+
.. versionadded:: 3.9
+ .. versionchanged:: next
+ Added support for single-dash options.
+
+ Added support for alternate prefix_chars_.
+
The parse_args() method
-----------------------
@@ -2065,7 +2088,9 @@ Parser defaults
>>> parser.parse_args(['736'])
Namespace(bar=42, baz='badger', foo=736)
- Note that parser-level defaults always override argument-level defaults::
+ Note that defaults can be set at both the parser level using :meth:`set_defaults`
+ and at the argument level using :meth:`add_argument`. If both are called for the
+ same argument, the last default set for an argument is used::
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', default='bar')
diff --git a/Doc/library/ast.rst b/Doc/library/ast.rst
index 49462167217..2e7d0dbc26e 100644
--- a/Doc/library/ast.rst
+++ b/Doc/library/ast.rst
@@ -2205,10 +2205,10 @@ Async and await
Apart from the node classes, the :mod:`ast` module defines these utility functions
and classes for traversing abstract syntax trees:
-.. function:: parse(source, filename='', mode='exec', *, type_comments=False, feature_version=None, optimize=-1)
+.. function:: parse(source, filename='', mode='exec', *, type_comments=False, feature_version=None, optimize=-1, module=None)
Parse the source into an AST node. Equivalent to ``compile(source,
- filename, mode, flags=FLAGS_VALUE, optimize=optimize)``,
+ filename, mode, flags=FLAGS_VALUE, optimize=optimize, module=module)``,
where ``FLAGS_VALUE`` is ``ast.PyCF_ONLY_AST`` if ``optimize <= 0``
and ``ast.PyCF_OPTIMIZED_AST`` otherwise.
@@ -2261,6 +2261,9 @@ and classes for traversing abstract syntax trees:
The minimum supported version for ``feature_version`` is now ``(3, 7)``.
The ``optimize`` argument was added.
+ .. versionadded:: 3.15
+ Added the *module* parameter.
+
.. function:: unparse(ast_obj)
diff --git a/Doc/library/asyncio-eventloop.rst b/Doc/library/asyncio-eventloop.rst
index 0ccc7a2b448..72f484fd1cb 100644
--- a/Doc/library/asyncio-eventloop.rst
+++ b/Doc/library/asyncio-eventloop.rst
@@ -1631,6 +1631,9 @@ async/await code consider using the high-level
conforms to the :class:`asyncio.SubprocessTransport` base class and
*protocol* is an object instantiated by the *protocol_factory*.
+ If the transport is closed or is garbage collected, the child process
+ is killed if it is still running.
+
.. method:: loop.subprocess_shell(protocol_factory, cmd, *, \
stdin=subprocess.PIPE, stdout=subprocess.PIPE, \
stderr=subprocess.PIPE, **kwargs)
@@ -1654,6 +1657,9 @@ async/await code consider using the high-level
conforms to the :class:`SubprocessTransport` base class and
*protocol* is an object instantiated by the *protocol_factory*.
+ If the transport is closed or is garbage collected, the child process
+ is killed if it is still running.
+
.. note::
It is the application's responsibility to ensure that all whitespace
and special characters are quoted appropriately to avoid `shell injection
diff --git a/Doc/library/asyncio-subprocess.rst b/Doc/library/asyncio-subprocess.rst
index 03e76bc8689..9416c758e51 100644
--- a/Doc/library/asyncio-subprocess.rst
+++ b/Doc/library/asyncio-subprocess.rst
@@ -76,6 +76,9 @@ Creating Subprocesses
See the documentation of :meth:`loop.subprocess_exec` for other
parameters.
+ If the process object is garbage collected while the process is still
+ running, the child process will be killed.
+
.. versionchanged:: 3.10
Removed the *loop* parameter.
@@ -95,6 +98,9 @@ Creating Subprocesses
See the documentation of :meth:`loop.subprocess_shell` for other
parameters.
+ If the process object is garbage collected while the process is still
+ running, the child process will be killed.
+
.. important::
It is the application's responsibility to ensure that all whitespace and
diff --git a/Doc/library/asyncio-task.rst b/Doc/library/asyncio-task.rst
index f825ae92ec7..863b3e33657 100644
--- a/Doc/library/asyncio-task.rst
+++ b/Doc/library/asyncio-task.rst
@@ -1221,8 +1221,8 @@ Task Object
To cancel a running Task use the :meth:`cancel` method. Calling it
will cause the Task to throw a :exc:`CancelledError` exception into
- the wrapped coroutine. If a coroutine is awaiting on a Future
- object during cancellation, the Future object will be cancelled.
+ the wrapped coroutine. If a coroutine is awaiting on a future-like
+ object during cancellation, the awaited object will be cancelled.
:meth:`cancelled` can be used to check if the Task was cancelled.
The method returns ``True`` if the wrapped coroutine did not
@@ -1411,6 +1411,10 @@ Task Object
the cancellation, it needs to call :meth:`Task.uncancel` in addition
to catching the exception.
+ If the Task being cancelled is currently awaiting on a future-like
+ object, that awaited object will also be cancelled. This cancellation
+ propagates down the entire chain of awaited objects.
+
.. versionchanged:: 3.9
Added the *msg* parameter.
diff --git a/Doc/library/asyncio.rst b/Doc/library/asyncio.rst
index 444db01390d..0f72e31dee5 100644
--- a/Doc/library/asyncio.rst
+++ b/Doc/library/asyncio.rst
@@ -79,6 +79,10 @@ You can experiment with an ``asyncio`` concurrent context in the :term:`REPL`:
>>> await asyncio.sleep(10, result='hello')
'hello'
+This REPL provides limited compatibility with :envvar:`PYTHON_BASIC_REPL`.
+It is recommended that the default REPL is used
+for full functionality and the latest features.
+
.. audit-event:: cpython.run_stdin "" ""
.. versionchanged:: 3.12.5 (also 3.11.10, 3.10.15, 3.9.20, and 3.8.20)
diff --git a/Doc/library/bdb.rst b/Doc/library/bdb.rst
index c7a3e0c596b..a3c6da7a6d6 100644
--- a/Doc/library/bdb.rst
+++ b/Doc/library/bdb.rst
@@ -236,7 +236,7 @@ The :mod:`bdb` module also defines two classes:
Normally derived classes don't override the following methods, but they may
if they want to redefine the definition of stopping and breakpoints.
- .. method:: is_skipped_line(module_name)
+ .. method:: is_skipped_module(module_name)
Return ``True`` if *module_name* matches any skip pattern.
diff --git a/Doc/library/bz2.rst b/Doc/library/bz2.rst
index ebe2e43feba..12650861c0f 100644
--- a/Doc/library/bz2.rst
+++ b/Doc/library/bz2.rst
@@ -25,6 +25,8 @@ The :mod:`bz2` module contains:
* The :func:`compress` and :func:`decompress` functions for one-shot
(de)compression.
+.. include:: ../includes/optional-module.rst
+
(De)compression of files
------------------------
diff --git a/Doc/library/cmdline.rst b/Doc/library/cmdline.rst
index 16c67ddbf7c..c43b10157f9 100644
--- a/Doc/library/cmdline.rst
+++ b/Doc/library/cmdline.rst
@@ -16,17 +16,17 @@ The following modules have a command-line interface.
* :ref:`dis `
* :ref:`doctest `
* :mod:`!encodings.rot_13`
-* :mod:`ensurepip`
+* :ref:`ensurepip `
* :mod:`filecmp`
* :mod:`fileinput`
* :mod:`ftplib`
* :ref:`gzip `
* :ref:`http.server `
-* :mod:`!idlelib`
+* :ref:`idlelib `
* :ref:`inspect `
* :ref:`json `
* :ref:`mimetypes `
-* :mod:`pdb`
+* :ref:`pdb `
* :ref:`pickle `
* :ref:`pickletools `
* :ref:`platform `
@@ -52,8 +52,8 @@ The following modules have a command-line interface.
* :mod:`turtledemo`
* :ref:`unittest `
* :ref:`uuid `
-* :mod:`venv`
-* :mod:`webbrowser`
+* :ref:`venv `
+* :ref:`webbrowser `
* :ref:`zipapp `
* :ref:`zipfile `
diff --git a/Doc/library/codecs.rst b/Doc/library/codecs.rst
index 2a5994b11d8..305e5d07a35 100644
--- a/Doc/library/codecs.rst
+++ b/Doc/library/codecs.rst
@@ -1088,7 +1088,7 @@ alias for the ``'utf_8'`` codec.
refer to the source :source:`aliases.py ` file.
On Windows, ``cpXXX`` codecs are available for all code pages.
-But only codecs listed in the following table are guarantead to exist on
+But only codecs listed in the following table are guaranteed to exist on
other platforms.
.. impl-detail::
diff --git a/Doc/library/collections.rst b/Doc/library/collections.rst
index 9a8108d882e..4e0db485e06 100644
--- a/Doc/library/collections.rst
+++ b/Doc/library/collections.rst
@@ -1209,7 +1209,7 @@ If a new entry overwrites an existing entry, the
original insertion position is changed and moved to the end::
class LastUpdatedOrderedDict(OrderedDict):
- 'Store items in the order the keys were last added'
+ 'Store items in the order that the keys were last updated.'
def __setitem__(self, key, value):
super().__setitem__(key, value)
diff --git a/Doc/library/compression.zstd.rst b/Doc/library/compression.zstd.rst
index a901403621b..89b6fe540f5 100644
--- a/Doc/library/compression.zstd.rst
+++ b/Doc/library/compression.zstd.rst
@@ -33,6 +33,8 @@ The :mod:`!compression.zstd` module contains:
* The :class:`CompressionParameter`, :class:`DecompressionParameter`, and
:class:`Strategy` classes for setting advanced (de)compression parameters.
+.. include:: ../includes/optional-module.rst
+
Exceptions
----------
diff --git a/Doc/library/concurrent.interpreters.rst b/Doc/library/concurrent.interpreters.rst
index 41ea6af3b22..55036090e8d 100644
--- a/Doc/library/concurrent.interpreters.rst
+++ b/Doc/library/concurrent.interpreters.rst
@@ -29,12 +29,12 @@ Actual concurrency is available separately through
.. seealso::
:class:`~concurrent.futures.InterpreterPoolExecutor`
- combines threads with interpreters in a familiar interface.
+ Combines threads with interpreters in a familiar interface.
- .. XXX Add references to the upcoming HOWTO docs in the seealso block.
+ .. XXX Add references to the upcoming HOWTO docs in the seealso block.
:ref:`isolating-extensions-howto`
- how to update an extension module to support multiple interpreters
+ How to update an extension module to support multiple interpreters.
:pep:`554`
diff --git a/Doc/library/contextvars.rst b/Doc/library/contextvars.rst
index 57580ce026e..b218468a084 100644
--- a/Doc/library/contextvars.rst
+++ b/Doc/library/contextvars.rst
@@ -313,7 +313,7 @@ client::
addr = writer.transport.get_extra_info('socket').getpeername()
client_addr_var.set(addr)
- # In any code that we call is now possible to get
+ # In any code that we call, it is now possible to get the
# client's address by calling 'client_addr_var.get()'.
while True:
diff --git a/Doc/library/csv.rst b/Doc/library/csv.rst
index 3ea7cd210f7..4a033d823e6 100644
--- a/Doc/library/csv.rst
+++ b/Doc/library/csv.rst
@@ -295,8 +295,8 @@ The :mod:`csv` module defines the following classes:
- the second through n-th rows contain strings where at least one value's
length differs from that of the putative header of that column.
- Twenty rows after the first row are sampled; if more than half of columns +
- rows meet the criteria, :const:`True` is returned.
+ Twenty-one rows after the header are sampled; if more than half of the
+ columns + rows meet the criteria, :const:`True` is returned.
.. note::
diff --git a/Doc/library/ctypes.rst b/Doc/library/ctypes.rst
index d8dac24c8ab..9c0b246c095 100644
--- a/Doc/library/ctypes.rst
+++ b/Doc/library/ctypes.rst
@@ -14,6 +14,8 @@
data types, and allows calling functions in DLLs or shared libraries. It can be
used to wrap these libraries in pure Python.
+.. include:: ../includes/optional-module.rst
+
.. _ctypes-ctypes-tutorial:
diff --git a/Doc/library/curses.rst b/Doc/library/curses.rst
index fb84cf32246..057d338edda 100644
--- a/Doc/library/curses.rst
+++ b/Doc/library/curses.rst
@@ -23,6 +23,8 @@ Linux and the BSD variants of Unix.
.. include:: ../includes/wasm-mobile-notavail.rst
+.. include:: ../includes/optional-module.rst
+
.. note::
Whenever the documentation mentions a *character* it can be specified
@@ -1349,7 +1351,6 @@ The :mod:`curses` module defines the following data members:
.. data:: version
-.. data:: __version__
A bytes object representing the current version of the module.
diff --git a/Doc/library/decimal.rst b/Doc/library/decimal.rst
index 985153b5443..05937775699 100644
--- a/Doc/library/decimal.rst
+++ b/Doc/library/decimal.rst
@@ -264,7 +264,7 @@ allows the settings to be changed. This approach meets the needs of most
applications.
For more advanced work, it may be useful to create alternate contexts using the
-Context() constructor. To make an alternate active, use the :func:`setcontext`
+:meth:`Context` constructor. To make an alternate active, use the :func:`setcontext`
function.
In accordance with the standard, the :mod:`decimal` module provides two ready to
@@ -1575,7 +1575,7 @@ Constants
Specification that this implementation complies with.
See https://speleotrove.com/decimal/decarith.html for the specification.
- .. versionadded:: next
+ .. versionadded:: 3.15
The following constants are only relevant for the C module. They
diff --git a/Doc/library/dis.rst b/Doc/library/dis.rst
index 284eeff5e4d..a24589fd0a5 100644
--- a/Doc/library/dis.rst
+++ b/Doc/library/dis.rst
@@ -1673,9 +1673,13 @@ iterations of the loop.
* ``0x02`` a dictionary of keyword-only parameters' default values
* ``0x04`` a tuple of strings containing parameters' annotations
* ``0x08`` a tuple containing cells for free variables, making a closure
+ * ``0x10`` the :term:`annotate function` for the function object
.. versionadded:: 3.13
+ .. versionchanged:: 3.14
+ Added ``0x10`` to indicate the annotate function for the function object.
+
.. opcode:: BUILD_SLICE (argc)
diff --git a/Doc/library/email.headerregistry.rst b/Doc/library/email.headerregistry.rst
index 7f8044932fa..ff8b601fe3d 100644
--- a/Doc/library/email.headerregistry.rst
+++ b/Doc/library/email.headerregistry.rst
@@ -294,7 +294,7 @@ variant, :attr:`~.BaseHeader.max_count` is set to 1.
``inline`` and ``attachment`` are the only valid values in common use.
-.. class:: ContentTransferEncoding
+.. class:: ContentTransferEncodingHeader
Handles the :mailheader:`Content-Transfer-Encoding` header.
diff --git a/Doc/library/ensurepip.rst b/Doc/library/ensurepip.rst
index fa102c4a080..32b92c01570 100644
--- a/Doc/library/ensurepip.rst
+++ b/Doc/library/ensurepip.rst
@@ -30,6 +30,8 @@ when creating a virtual environment) or after explicitly uninstalling
needed to bootstrap ``pip`` are included as internal parts of the
package.
+.. include:: ../includes/optional-module.rst
+
.. seealso::
:ref:`installing-index`
@@ -40,7 +42,9 @@ when creating a virtual environment) or after explicitly uninstalling
.. include:: ../includes/wasm-mobile-notavail.rst
-Command line interface
+.. _ensurepip-cli:
+
+Command-line interface
----------------------
.. program:: ensurepip
diff --git a/Doc/library/functions.rst b/Doc/library/functions.rst
index 61799e303a1..8314fed80fa 100644
--- a/Doc/library/functions.rst
+++ b/Doc/library/functions.rst
@@ -292,7 +292,9 @@ are always available. They are listed here in alphabetical order.
:func:`property`.
-.. function:: compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)
+.. function:: compile(source, filename, mode, flags=0, \
+ dont_inherit=False, optimize=-1, \
+ *, module=None)
Compile the *source* into a code or AST object. Code objects can be executed
by :func:`exec` or :func:`eval`. *source* can either be a normal string, a
@@ -334,6 +336,10 @@ are always available. They are listed here in alphabetical order.
``__debug__`` is true), ``1`` (asserts are removed, ``__debug__`` is false)
or ``2`` (docstrings are removed too).
+ The optional argument *module* specifies the module name.
+ It is needed to unambiguous :ref:`filter ` syntax warnings
+ by module name.
+
This function raises :exc:`SyntaxError` if the compiled source is invalid,
and :exc:`ValueError` if the source contains null bytes.
@@ -371,6 +377,9 @@ are always available. They are listed here in alphabetical order.
``ast.PyCF_ALLOW_TOP_LEVEL_AWAIT`` can now be passed in flags to enable
support for top-level ``await``, ``async for``, and ``async with``.
+ .. versionadded:: 3.15
+ Added the *module* parameter.
+
.. class:: complex(number=0, /)
complex(string, /)
@@ -1859,7 +1868,7 @@ are always available. They are listed here in alphabetical order.
the same data with other ordering tools such as :func:`max` that rely
on a different underlying method. Implementing all six comparisons
also helps avoid confusion for mixed type comparisons which can call
- reflected the :meth:`~object.__gt__` method.
+ the reflected :meth:`~object.__gt__` method.
For sorting examples and a brief sorting tutorial, see :ref:`sortinghowto`.
diff --git a/Doc/library/functools.rst b/Doc/library/functools.rst
index 37d9f87e779..97136b23408 100644
--- a/Doc/library/functools.rst
+++ b/Doc/library/functools.rst
@@ -42,11 +42,11 @@ The :mod:`functools` module defines the following functions:
def factorial(n):
return n * factorial(n-1) if n else 1
- >>> factorial(10) # no previously cached result, makes 11 recursive calls
+ >>> factorial(10) # no previously cached result, makes 11 recursive calls
3628800
- >>> factorial(5) # just looks up cached value result
+ >>> factorial(5) # no new calls, just returns the cached result
120
- >>> factorial(12) # makes two new recursive calls, the other 10 are cached
+ >>> factorial(12) # two new recursive calls, factorial(10) is cached
479001600
The cache is threadsafe so that the wrapped function can be used in
@@ -672,7 +672,7 @@ The :mod:`functools` module defines the following functions:
dispatch>` :term:`generic function`.
To define a generic method, decorate it with the ``@singledispatchmethod``
- decorator. When defining a function using ``@singledispatchmethod``, note
+ decorator. When defining a method using ``@singledispatchmethod``, note
that the dispatch happens on the type of the first non-*self* or non-*cls*
argument::
@@ -716,6 +716,9 @@ The :mod:`functools` module defines the following functions:
.. versionadded:: 3.8
+ .. versionchanged:: 3.15
+ Added support of non-:term:`descriptor` callables.
+
.. function:: update_wrapper(wrapper, wrapped, assigned=WRAPPER_ASSIGNMENTS, updated=WRAPPER_UPDATES)
diff --git a/Doc/library/gc.rst b/Doc/library/gc.rst
index 2ef5c4b35a2..79a8c38626f 100644
--- a/Doc/library/gc.rst
+++ b/Doc/library/gc.rst
@@ -108,10 +108,19 @@ The :mod:`gc` module provides the following functions:
* ``uncollectable`` is the total number of objects which were found
to be uncollectable (and were therefore moved to the :data:`garbage`
- list) inside this generation.
+ list) inside this generation;
+
+ * ``candidates`` is the total number of objects in this generation which were
+ considered for collection and traversed;
+
+ * ``duration`` is the total time in seconds spent in collections for this
+ generation.
.. versionadded:: 3.4
+ .. versionchanged:: next
+ Add ``duration`` and ``candidates``.
+
.. function:: set_threshold(threshold0, [threshold1, [threshold2]])
@@ -313,6 +322,12 @@ values but should not rebind them):
"uncollectable": When *phase* is "stop", the number of objects
that could not be collected and were put in :data:`garbage`.
+ "candidates": When *phase* is "stop", the total number of objects in this
+ generation which were considered for collection and traversed.
+
+ "duration": When *phase* is "stop", the time in seconds spent in the
+ collection.
+
Applications can add their own callbacks to this list. The primary
use cases are:
@@ -325,6 +340,9 @@ values but should not rebind them):
.. versionadded:: 3.3
+ .. versionchanged:: next
+ Add "duration" and "candidates".
+
The following constants are provided for use with :func:`set_debug`:
diff --git a/Doc/library/gzip.rst b/Doc/library/gzip.rst
index 4bdcec66088..d23c0741ddb 100644
--- a/Doc/library/gzip.rst
+++ b/Doc/library/gzip.rst
@@ -11,6 +11,8 @@
This module provides a simple interface to compress and decompress files just
like the GNU programs :program:`gzip` and :program:`gunzip` would.
+.. include:: ../includes/optional-module.rst
+
The data compression is provided by the :mod:`zlib` module.
The :mod:`gzip` module provides the :class:`GzipFile` class, as well as the
@@ -281,7 +283,7 @@ Example of how to GZIP compress a binary string::
.. _gzip-cli:
-Command Line Interface
+Command-line interface
----------------------
The :mod:`gzip` module provides a simple command line interface to compress or
@@ -294,7 +296,7 @@ Once executed the :mod:`gzip` module keeps the input file(s).
Add a new command line interface with a usage.
By default, when you will execute the CLI, the default compression level is 6.
-Command line options
+Command-line options
^^^^^^^^^^^^^^^^^^^^
.. option:: file
diff --git a/Doc/library/heapq.rst b/Doc/library/heapq.rst
index 95ef72469b1..5049262306a 100644
--- a/Doc/library/heapq.rst
+++ b/Doc/library/heapq.rst
@@ -58,6 +58,11 @@ functions, respectively.
The following functions are provided for min-heaps:
+.. function:: heapify(x)
+
+ Transform list *x* into a min-heap, in-place, in linear time.
+
+
.. function:: heappush(heap, item)
Push the value *item* onto the *heap*, maintaining the min-heap invariant.
@@ -77,11 +82,6 @@ The following functions are provided for min-heaps:
followed by a separate call to :func:`heappop`.
-.. function:: heapify(x)
-
- Transform list *x* into a min-heap, in-place, in linear time.
-
-
.. function:: heapreplace(heap, item)
Pop and return the smallest item from the *heap*, and also push the new *item*.
diff --git a/Doc/library/http.client.rst b/Doc/library/http.client.rst
index 589152f2968..7c258b324d9 100644
--- a/Doc/library/http.client.rst
+++ b/Doc/library/http.client.rst
@@ -133,7 +133,7 @@ This module provides the following function:
Parse the headers from a file pointer *fp* representing a HTTP
request/response. The file has to be a :class:`~io.BufferedIOBase` reader
- (i.e. not text) and must provide a valid :rfc:`2822` style header.
+ (i.e. not text) and must provide a valid :rfc:`5322` style header.
This function returns an instance of :class:`http.client.HTTPMessage`
that holds the header fields, but no payload
diff --git a/Doc/library/http.cookiejar.rst b/Doc/library/http.cookiejar.rst
index 251aea891c3..fcb0069b760 100644
--- a/Doc/library/http.cookiejar.rst
+++ b/Doc/library/http.cookiejar.rst
@@ -12,7 +12,7 @@
--------------
The :mod:`http.cookiejar` module defines classes for automatic handling of HTTP
-cookies. It is useful for accessing web sites that require small pieces of data
+cookies. It is useful for accessing websites that require small pieces of data
-- :dfn:`cookies` -- to be set on the client machine by an HTTP response from a
web server, and then returned to the server in later HTTP requests.
diff --git a/Doc/library/http.server.rst b/Doc/library/http.server.rst
index 063344e0284..58f09634f95 100644
--- a/Doc/library/http.server.rst
+++ b/Doc/library/http.server.rst
@@ -154,7 +154,7 @@ instantiation, of which this module provides three different variants:
variable. This instance parses and manages the headers in the HTTP
request. The :func:`~http.client.parse_headers` function from
:mod:`http.client` is used to parse the headers and it requires that the
- HTTP request provide a valid :rfc:`2822` style header.
+ HTTP request provide a valid :rfc:`5322` style header.
.. attribute:: rfile
diff --git a/Doc/library/idle.rst b/Doc/library/idle.rst
index fabea611e0e..a16f46ef812 100644
--- a/Doc/library/idle.rst
+++ b/Doc/library/idle.rst
@@ -13,7 +13,7 @@ IDLE --- Python editor and shell
single: Integrated Development Environment
..
- Remember to update Lib/idlelib/help.html with idlelib.help.copy_source() when modifying this file.
+ Remember to update Lib/idlelib/help.html with idlelib.help.copy_strip() when modifying this file.
--------------
@@ -37,6 +37,10 @@ IDLE has the following features:
* configuration, browsers, and other dialogs
+The IDLE application is implemented in the :mod:`idlelib` package.
+
+.. include:: ../includes/optional-module.rst
+
Menus
-----
@@ -88,7 +92,7 @@ Save
Save As...
Save the current window with a Save As dialog. The file saved becomes the
- new associated file for the window. (If your file namager is set to hide
+ new associated file for the window. (If your file manager is set to hide
extensions, the current extension will be omitted in the file name box.
If the new filename has no '.', '.py' and '.txt' will be added for Python
and text files, except that on macOS Aqua,'.py' is added for all files.)
@@ -204,9 +208,9 @@ New Indent Width
Open a dialog to change indent width. The accepted default by the Python
community is 4 spaces.
-Strip Trailing Chitespace
+Strip Trailing Whitespace
Remove trailing space and other whitespace characters after the last
- non-whitespace character of a line by applying str.rstrip to each line,
+ non-whitespace character of a line by applying :meth:`str.rstrip` to each line,
including lines within multiline strings. Except for Shell windows,
remove extra newlines at the end of the file.
@@ -657,7 +661,9 @@ looked for in the user's home directory. Statements in this file will be
executed in the Tk namespace, so this file is not useful for importing
functions to be used from IDLE's Python shell.
-Command line usage
+.. _idlelib-cli:
+
+Command-line usage
^^^^^^^^^^^^^^^^^^
.. program:: idle
diff --git a/Doc/library/importlib.rst b/Doc/library/importlib.rst
index 602a7100a12..3f0a54ac535 100644
--- a/Doc/library/importlib.rst
+++ b/Doc/library/importlib.rst
@@ -459,7 +459,7 @@ ABC hierarchy::
.. versionchanged:: 3.4
Raises :exc:`ImportError` instead of :exc:`NotImplementedError`.
- .. staticmethod:: source_to_code(data, path='')
+ .. staticmethod:: source_to_code(data, path='', fullname=None)
Create a code object from Python source.
@@ -471,11 +471,19 @@ ABC hierarchy::
With the subsequent code object one can execute it in a module by
running ``exec(code, module.__dict__)``.
+ The optional argument *fullname* specifies the module name.
+ It is needed to unambiguous :ref:`filter ` syntax
+ warnings by module name.
+
.. versionadded:: 3.4
.. versionchanged:: 3.5
Made the method static.
+ .. versionadded:: 3.15
+ Added the *fullname* parameter.
+
+
.. method:: exec_module(module)
Implementation of :meth:`Loader.exec_module`.
@@ -1040,7 +1048,7 @@ find and load modules.
:meth:`PathFinder.invalidate_caches` invalidates :class:`NamespacePath`,
forcing the path value to be recomputed next time it is accessed.
- .. versionadded:: next
+ .. versionadded:: 3.15
.. class:: SourceFileLoader(fullname, path)
diff --git a/Doc/library/inspect.rst b/Doc/library/inspect.rst
index 2b3b294ff33..5220c559d3d 100644
--- a/Doc/library/inspect.rst
+++ b/Doc/library/inspect.rst
@@ -619,17 +619,29 @@ attributes (see :ref:`import-mod-attrs` for module attributes):
Retrieving source code
----------------------
-.. function:: getdoc(object)
+.. function:: getdoc(object, *, inherit_class_doc=True, fallback_to_class_doc=True)
Get the documentation string for an object, cleaned up with :func:`cleandoc`.
- If the documentation string for an object is not provided and the object is
- a class, a method, a property or a descriptor, retrieve the documentation
- string from the inheritance hierarchy.
+ If the documentation string for an object is not provided:
+
+ * if the object is a class and *inherit_class_doc* is true (by default),
+ retrieve the documentation string from the inheritance hierarchy;
+ * if the object is a method, a property or a descriptor, retrieve
+ the documentation string from the inheritance hierarchy;
+ * otherwise, if *fallback_to_class_doc* is true (by default), retrieve
+ the documentation string from the class of the object.
+
Return ``None`` if the documentation string is invalid or missing.
.. versionchanged:: 3.5
Documentation strings are now inherited if not overridden.
+ .. versionchanged:: 3.15
+ Added parameters *inherit_class_doc* and *fallback_to_class_doc*.
+
+ Documentation strings on :class:`~functools.cached_property`
+ objects are now inherited if not overriden.
+
.. function:: getcomments(object)
@@ -1776,7 +1788,7 @@ Buffer flags
.. _inspect-module-cli:
-Command Line Interface
+Command-line interface
----------------------
The :mod:`inspect` module also provides a basic introspection capability
diff --git a/Doc/library/json.rst b/Doc/library/json.rst
index 12a5a96a3c5..8b4217c210d 100644
--- a/Doc/library/json.rst
+++ b/Doc/library/json.rst
@@ -183,8 +183,10 @@ Basic Usage
:param bool ensure_ascii:
If ``True`` (the default), the output is guaranteed to
- have all incoming non-ASCII characters escaped.
- If ``False``, these characters will be outputted as-is.
+ have all incoming non-ASCII and non-printable characters escaped.
+ If ``False``, all characters will be outputted as-is, except for
+ the characters that must be escaped: quotation mark, reverse solidus,
+ and the control characters U+0000 through U+001F.
:param bool check_circular:
If ``False``, the circular reference check for container types is skipped
@@ -495,8 +497,10 @@ Encoders and Decoders
:class:`bool` or ``None``. If *skipkeys* is true, such items are simply skipped.
If *ensure_ascii* is true (the default), the output is guaranteed to
- have all incoming non-ASCII characters escaped. If *ensure_ascii* is
- false, these characters will be output as-is.
+ have all incoming non-ASCII and non-printable characters escaped.
+ If *ensure_ascii* is false, all characters will be output as-is, except for
+ the characters that must be escaped: quotation mark, reverse solidus,
+ and the control characters U+0000 through U+001F.
If *check_circular* is true (the default), then lists, dicts, and custom
encoded objects will be checked for circular references during encoding to
@@ -636,7 +640,7 @@ UTF-32, with UTF-8 being the recommended default for maximum interoperability.
As permitted, though not required, by the RFC, this module's serializer sets
*ensure_ascii=True* by default, thus escaping the output so that the resulting
-strings only contain ASCII characters.
+strings only contain printable ASCII characters.
Other than the *ensure_ascii* parameter, this module is defined strictly in
terms of conversion between Python objects and
diff --git a/Doc/library/locale.rst b/Doc/library/locale.rst
index 4824391e597..94fc046d3f3 100644
--- a/Doc/library/locale.rst
+++ b/Doc/library/locale.rst
@@ -524,8 +524,8 @@ The :mod:`locale` module defines the following exception and functions:
SSH connections.
Python doesn't internally use locale-dependent character transformation functions
- from ``ctype.h``. Instead, an internal ``pyctype.h`` provides locale-independent
- equivalents like :c:macro:`!Py_TOLOWER`.
+ from ``ctype.h``. Instead, ``pyctype.h`` provides locale-independent
+ equivalents like :c:macro:`Py_TOLOWER`.
.. data:: LC_COLLATE
diff --git a/Doc/library/logging.handlers.rst b/Doc/library/logging.handlers.rst
index d74ef73ee28..c9cfbdb4126 100644
--- a/Doc/library/logging.handlers.rst
+++ b/Doc/library/logging.handlers.rst
@@ -463,6 +463,7 @@ timed intervals.
.. method:: getFilesToDelete()
Returns a list of filenames which should be deleted as part of rollover. These
+ are the absolute paths of the oldest backup log files written by the handler.
.. method:: shouldRollover(record)
diff --git a/Doc/library/lzma.rst b/Doc/library/lzma.rst
index 69f7cb8d48d..8a4f68f3502 100644
--- a/Doc/library/lzma.rst
+++ b/Doc/library/lzma.rst
@@ -23,6 +23,8 @@ module. Note that :class:`LZMAFile` and :class:`bz2.BZ2File` are *not*
thread-safe, so if you need to use a single :class:`LZMAFile` instance
from multiple threads, it is necessary to protect it with a lock.
+.. include:: ../includes/optional-module.rst
+
.. exception:: LZMAError
diff --git a/Doc/library/mailbox.rst b/Doc/library/mailbox.rst
index e8a96f29ea1..62e289573c0 100644
--- a/Doc/library/mailbox.rst
+++ b/Doc/library/mailbox.rst
@@ -917,7 +917,7 @@ Supported mailbox formats are Maildir, mbox, MH, Babyl, and MMDF.
copied; furthermore, any format-specific information is converted insofar as
possible if *message* is a :class:`!Message` instance. If *message* is a string,
a byte string,
- or a file, it should contain an :rfc:`2822`\ -compliant message, which is read
+ or a file, it should contain an :rfc:`5322`\ -compliant message, which is read
and parsed. Files should be open in binary mode, but text mode files
are accepted for backward compatibility.
diff --git a/Doc/library/math.integer.rst b/Doc/library/math.integer.rst
index 6a9fe74c5e8..0068ae2bdd5 100644
--- a/Doc/library/math.integer.rst
+++ b/Doc/library/math.integer.rst
@@ -4,7 +4,7 @@
.. module:: math.integer
:synopsis: Integer-specific mathematics functions.
-.. versionadded:: next
+.. versionadded:: 3.15
--------------
diff --git a/Doc/library/math.rst b/Doc/library/math.rst
index 54c98346b27..d2ff74822f9 100644
--- a/Doc/library/math.rst
+++ b/Doc/library/math.rst
@@ -506,7 +506,7 @@ Summation and product functions
Roughly equivalent to::
- sqrt(sum((px - qx) ** 2.0 for px, qx in zip(p, q)))
+ sqrt(sum((px - qx) ** 2.0 for px, qx in zip(p, q, strict=True)))
.. versionadded:: 3.8
@@ -781,7 +781,7 @@ the following functions from the :mod:`math.integer` module:
Floats with integral values (like ``5.0``) are no longer accepted in the
:func:`factorial` function.
-.. deprecated:: next
+.. deprecated:: 3.15
These aliases are :term:`soft deprecated` in favor of the
:mod:`math.integer` functions.
diff --git a/Doc/library/msvcrt.rst b/Doc/library/msvcrt.rst
index 327cc3602b1..a2c5e375d2c 100644
--- a/Doc/library/msvcrt.rst
+++ b/Doc/library/msvcrt.rst
@@ -22,6 +22,8 @@ api. The normal API deals only with ASCII characters and is of limited use
for internationalized applications. The wide char API should be used where
ever possible.
+.. availability:: Windows.
+
.. versionchanged:: 3.3
Operations in this module now raise :exc:`OSError` where :exc:`IOError`
was raised.
diff --git a/Doc/library/multiprocessing.rst b/Doc/library/multiprocessing.rst
index d18ada3511d..714207cb0ae 100644
--- a/Doc/library/multiprocessing.rst
+++ b/Doc/library/multiprocessing.rst
@@ -22,8 +22,7 @@ to this, the :mod:`multiprocessing` module allows the programmer to fully
leverage multiple processors on a given machine. It runs on both POSIX and
Windows.
-The :mod:`multiprocessing` module also introduces APIs which do not have
-analogs in the :mod:`threading` module. A prime example of this is the
+The :mod:`multiprocessing` module also introduces the
:class:`~multiprocessing.pool.Pool` object which offers a convenient means of
parallelizing the execution of a function across multiple input values,
distributing the input data across processes (data parallelism). The following
@@ -44,6 +43,10 @@ will print to standard output ::
[1, 4, 9]
+The :mod:`multiprocessing` module also introduces APIs which do not have
+analogs in the :mod:`threading` module, like the ability to :meth:`terminate
+`, :meth:`interrupt ` or :meth:`kill
+` a running process.
.. seealso::
diff --git a/Doc/library/os.rst b/Doc/library/os.rst
index d31d0ce9c85..671270d6112 100644
--- a/Doc/library/os.rst
+++ b/Doc/library/os.rst
@@ -558,7 +558,7 @@ process and user.
.. function:: initgroups(username, gid, /)
- Call the system initgroups() to initialize the group access list with all of
+ Call the system ``initgroups()`` to initialize the group access list with all of
the groups of which the specified username is a member, plus the specified
group id.
@@ -3404,7 +3404,7 @@ features:
.. availability:: Linux >= 4.11 with glibc >= 2.28.
- .. versionadded:: next
+ .. versionadded:: 3.15
.. class:: statx_result
@@ -3661,7 +3661,7 @@ features:
.. availability:: Linux >= 4.11 with glibc >= 2.28.
- .. versionadded:: next
+ .. versionadded:: 3.15
.. data:: STATX_TYPE
@@ -3690,7 +3690,7 @@ features:
.. availability:: Linux >= 4.11 with glibc >= 2.28.
- .. versionadded:: next
+ .. versionadded:: 3.15
.. data:: AT_STATX_FORCE_SYNC
@@ -3700,7 +3700,7 @@ features:
.. availability:: Linux >= 4.11 with glibc >= 2.28.
- .. versionadded:: next
+ .. versionadded:: 3.15
.. data:: AT_STATX_DONT_SYNC
@@ -3709,7 +3709,7 @@ features:
.. availability:: Linux >= 4.11 with glibc >= 2.28.
- .. versionadded:: next
+ .. versionadded:: 3.15
.. data:: AT_STATX_SYNC_AS_STAT
@@ -3721,7 +3721,7 @@ features:
.. availability:: Linux >= 4.11 with glibc >= 2.28.
- .. versionadded:: next
+ .. versionadded:: 3.15
.. data:: AT_NO_AUTOMOUNT
@@ -3733,7 +3733,7 @@ features:
.. availability:: Linux.
- .. versionadded:: next
+ .. versionadded:: 3.15
.. function:: statvfs(path)
@@ -3873,6 +3873,9 @@ features:
Create a symbolic link pointing to *src* named *dst*.
+ The *src* parameter refers to the target of the link (the file or directory being linked to),
+ and *dst* is the name of the link being created.
+
On Windows, a symlink represents either a file or a directory, and does not
morph to the target dynamically. If the target is present, the type of the
symlink will be created to match. Otherwise, the symlink will be created
diff --git a/Doc/library/pdb.rst b/Doc/library/pdb.rst
index 90dc6648045..0bbdc425352 100644
--- a/Doc/library/pdb.rst
+++ b/Doc/library/pdb.rst
@@ -76,6 +76,10 @@ The debugger's prompt is ``(Pdb)``, which is the indicator that you are in debug
.. _pdb-cli:
+
+Command-line interface
+----------------------
+
.. program:: pdb
You can also invoke :mod:`pdb` from the command line to debug other scripts. For
@@ -334,7 +338,7 @@ access further features, you have to do this yourself:
.. _debugger-commands:
-Debugger Commands
+Debugger commands
-----------------
The commands recognized by the debugger are listed below. Most commands can be
diff --git a/Doc/library/profile.rst b/Doc/library/profile.rst
index faf8079db3d..5bf36b13c6d 100644
--- a/Doc/library/profile.rst
+++ b/Doc/library/profile.rst
@@ -265,6 +265,14 @@ Profile with real-time sampling statistics::
Sample all threads in the process instead of just the main thread
+.. option:: --native
+
+ Include artificial ```` frames to denote calls to non-Python code.
+
+.. option:: --no-gc
+
+ Don't include artificial ```` frames to denote active garbage collection.
+
.. option:: --realtime-stats
Print real-time sampling statistics during profiling
@@ -349,7 +357,7 @@ This section documents the programmatic interface for the :mod:`!profiling.sampl
For command-line usage, see :ref:`sampling-profiler-cli`. For conceptual information
about statistical profiling, see :ref:`statistical-profiling`
-.. function:: sample(pid, *, sort=2, sample_interval_usec=100, duration_sec=10, filename=None, all_threads=False, limit=None, show_summary=True, output_format="pstats", realtime_stats=False)
+.. function:: sample(pid, *, sort=2, sample_interval_usec=100, duration_sec=10, filename=None, all_threads=False, limit=None, show_summary=True, output_format="pstats", realtime_stats=False, native=False, gc=True)
Sample a Python process and generate profiling data.
@@ -367,6 +375,8 @@ about statistical profiling, see :ref:`statistical-profiling`
:param bool show_summary: Whether to show summary statistics (default: True)
:param str output_format: Output format - 'pstats' or 'collapsed' (default: 'pstats')
:param bool realtime_stats: Whether to display real-time statistics (default: False)
+ :param bool native: Whether to include ```` frames (default: False)
+ :param bool gc: Whether to include ```` frames (default: True)
:raises ValueError: If output_format is not 'pstats' or 'collapsed'
diff --git a/Doc/library/pyexpat.rst b/Doc/library/pyexpat.rst
index f533850c0ca..2f5db81955c 100644
--- a/Doc/library/pyexpat.rst
+++ b/Doc/library/pyexpat.rst
@@ -634,6 +634,15 @@ otherwise stated.
.. method:: xmlparser.ExternalEntityRefHandler(context, base, systemId, publicId)
+ .. warning::
+
+ Implementing a handler that accesses local files and/or the network
+ may create a vulnerability to
+ `external entity attacks `_
+ if :class:`xmlparser` is used with user-provided XML content.
+ Please reflect on your `threat model `_
+ before implementing this handler.
+
Called for references to external entities. *base* is the current base, as set
by a previous call to :meth:`SetBase`. The public and system identifiers,
*systemId* and *publicId*, are strings if given; if the public identifier is not
diff --git a/Doc/library/readline.rst b/Doc/library/readline.rst
index f649fce5efc..75db832c546 100644
--- a/Doc/library/readline.rst
+++ b/Doc/library/readline.rst
@@ -26,6 +26,8 @@ Readline library in general.
.. include:: ../includes/wasm-mobile-notavail.rst
+.. include:: ../includes/optional-module.rst
+
.. note::
The underlying Readline library API may be implemented by
diff --git a/Doc/library/site.rst b/Doc/library/site.rst
index e98dd83b60e..d93e4dc7c75 100644
--- a/Doc/library/site.rst
+++ b/Doc/library/site.rst
@@ -270,7 +270,7 @@ Module contents
.. _site-commandline:
-Command Line Interface
+Command-line interface
----------------------
.. program:: site
diff --git a/Doc/library/smtplib.rst b/Doc/library/smtplib.rst
index c5a3de52090..3ee8b82a188 100644
--- a/Doc/library/smtplib.rst
+++ b/Doc/library/smtplib.rst
@@ -24,10 +24,13 @@ Protocol) and :rfc:`1869` (SMTP Service Extensions).
.. class:: SMTP(host='', port=0, local_hostname=None[, timeout], source_address=None)
An :class:`SMTP` instance encapsulates an SMTP connection. It has methods
- that support a full repertoire of SMTP and ESMTP operations. If the optional
- *host* and *port* parameters are given, the SMTP :meth:`connect` method is
- called with those parameters during initialization. If specified,
- *local_hostname* is used as the FQDN of the local host in the HELO/EHLO
+ that support a full repertoire of SMTP and ESMTP operations.
+
+ If the host parameter is set to a truthy value, :meth:`SMTP.connect` is called with
+ host and port automatically when the object is created; otherwise, :meth:`!connect` must
+ be called manually.
+
+ If specified, *local_hostname* is used as the FQDN of the local host in the HELO/EHLO
command. Otherwise, the local hostname is found using
:func:`socket.getfqdn`. If the :meth:`connect` call returns anything other
than a success code, an :exc:`SMTPConnectError` is raised. The optional
@@ -62,6 +65,10 @@ Protocol) and :rfc:`1869` (SMTP Service Extensions).
``smtplib.SMTP.send`` with arguments ``self`` and ``data``,
where ``data`` is the bytes about to be sent to the remote host.
+ .. attribute:: SMTP.default_port
+
+ The default port used for SMTP connections (25).
+
.. versionchanged:: 3.3
Support for the :keyword:`with` statement was added.
@@ -80,15 +87,23 @@ Protocol) and :rfc:`1869` (SMTP Service Extensions).
An :class:`SMTP_SSL` instance behaves exactly the same as instances of
:class:`SMTP`. :class:`SMTP_SSL` should be used for situations where SSL is
- required from the beginning of the connection and using :meth:`~SMTP.starttls`
- is not appropriate. If *host* is not specified, the local host is used. If
- *port* is zero, the standard SMTP-over-SSL port (465) is used. The optional
- arguments *local_hostname*, *timeout* and *source_address* have the same
+ required from the beginning of the connection and using :meth:`SMTP.starttls` is
+ not appropriate.
+
+ If the host parameter is set to a truthy value, :meth:`SMTP.connect` is called with host
+ and port automatically when the object is created; otherwise, :meth:`!SMTP.connect` must
+ be called manually.
+
+ The optional arguments *local_hostname*, *timeout* and *source_address* have the same
meaning as they do in the :class:`SMTP` class. *context*, also optional,
can contain a :class:`~ssl.SSLContext` and allows configuring various
aspects of the secure connection. Please read :ref:`ssl-security` for
best practices.
+ .. attribute:: SMTP_SSL.default_port
+
+ The default port used for SMTP-over-SSL connections (465).
+
.. versionchanged:: 3.3
*context* was added.
@@ -259,6 +274,9 @@ An :class:`SMTP` instance has the following methods:
2-tuple of the response code and message sent by the server in its
connection response.
+ If port is not changed from its default value of 0, the value of the :attr:`default_port`
+ attribute is used.
+
.. audit-event:: smtplib.connect self,host,port smtplib.SMTP.connect
diff --git a/Doc/library/socket.rst b/Doc/library/socket.rst
index 89bca9b5b20..976136885ea 100644
--- a/Doc/library/socket.rst
+++ b/Doc/library/socket.rst
@@ -482,6 +482,9 @@ The AF_* and SOCK_* constants are now :class:`AddressFamily` and
.. versionchanged:: 3.14
Added support for ``TCP_QUICKACK`` on Windows platforms when available.
+ .. versionchanged:: next
+ ``IPV6_HDRINCL`` was added.
+
.. data:: AF_CAN
PF_CAN
diff --git a/Doc/library/socketserver.rst b/Doc/library/socketserver.rst
index 7bc2f7afbbb..491b8769f44 100644
--- a/Doc/library/socketserver.rst
+++ b/Doc/library/socketserver.rst
@@ -546,7 +546,7 @@ The difference is that the ``readline()`` call in the second handler will call
first handler had to use a ``recv()`` loop to accumulate data until a
newline itself. If it had just used a single ``recv()`` without the loop it
would just have returned what has been received so far from the client.
-TCP is stream based: data arrives in the order it was sent, but there no
+TCP is stream based: data arrives in the order it was sent, but there is no
correlation between client ``send()`` or ``sendall()`` calls and the number
of ``recv()`` calls on the server required to receive it.
diff --git a/Doc/library/sqlite3.rst b/Doc/library/sqlite3.rst
index 9d56e81dee1..3b1a9c2f6ee 100644
--- a/Doc/library/sqlite3.rst
+++ b/Doc/library/sqlite3.rst
@@ -31,7 +31,9 @@ PostgreSQL or Oracle.
The :mod:`!sqlite3` module was written by Gerhard Häring. It provides an SQL interface
compliant with the DB-API 2.0 specification described by :pep:`249`, and
-requires SQLite 3.15.2 or newer.
+requires the third-party `SQLite `_ library.
+
+.. include:: ../includes/optional-module.rst
This document includes four main sections:
diff --git a/Doc/library/ssl.rst b/Doc/library/ssl.rst
index e0d85c852fa..fa0a5234720 100644
--- a/Doc/library/ssl.rst
+++ b/Doc/library/ssl.rst
@@ -18,8 +18,9 @@
This module provides access to Transport Layer Security (often known as "Secure
Sockets Layer") encryption and peer authentication facilities for network
sockets, both client-side and server-side. This module uses the OpenSSL
-library. It is available on all modern Unix systems, Windows, macOS, and
-probably additional platforms, as long as OpenSSL is installed on that platform.
+library.
+
+.. include:: ../includes/optional-module.rst
.. note::
diff --git a/Doc/library/stat.rst b/Doc/library/stat.rst
index 1cbec3ab847..82012b31a00 100644
--- a/Doc/library/stat.rst
+++ b/Doc/library/stat.rst
@@ -511,4 +511,4 @@ meaning of these constants.
STATX_ATTR_DAX
STATX_ATTR_WRITE_ATOMIC
- .. versionadded:: next
+ .. versionadded:: 3.15
diff --git a/Doc/library/stdtypes.rst b/Doc/library/stdtypes.rst
index 97e7e08364e..f3a99c4448b 100644
--- a/Doc/library/stdtypes.rst
+++ b/Doc/library/stdtypes.rst
@@ -3173,6 +3173,30 @@ objects.
.. versionadded:: 3.14
+ .. method:: take_bytes(n=None, /)
+
+ Remove the first *n* bytes from the bytearray and return them as an immutable
+ :class:`bytes`.
+ By default (if *n* is ``None``), return all bytes and clear the bytearray.
+
+ If *n* is negative, index from the end and take the first :func:`len`
+ plus *n* bytes. If *n* is out of bounds, raise :exc:`IndexError`.
+
+ Taking less than the full length will leave remaining bytes in the
+ :class:`bytearray`, which requires a copy. If the remaining bytes should be
+ discarded, use :func:`~bytearray.resize` or :keyword:`del` to truncate
+ then :func:`~bytearray.take_bytes` without a size.
+
+ .. impl-detail::
+
+ Taking all bytes is a zero-copy operation.
+
+ .. versionadded:: 3.15
+
+ See the :ref:`What's New ` entry for
+ common code patterns which can be optimized with
+ :func:`bytearray.take_bytes`.
+
Since bytearray objects are sequences of integers (akin to a list), for a
bytearray object *b*, ``b[0]`` will be an integer, while ``b[0:1]`` will be
a bytearray object of length 1. (This contrasts with text strings, where
@@ -4731,11 +4755,12 @@ other sequence-like behavior.
There are currently two built-in set types, :class:`set` and :class:`frozenset`.
The :class:`set` type is mutable --- the contents can be changed using methods
-like :meth:`~set.add` and :meth:`~set.remove`. Since it is mutable, it has no
-hash value and cannot be used as either a dictionary key or as an element of
-another set. The :class:`frozenset` type is immutable and :term:`hashable` ---
-its contents cannot be altered after it is created; it can therefore be used as
-a dictionary key or as an element of another set.
+like :meth:`add ` and :meth:`remove `.
+Since it is mutable, it has no hash value and cannot be used as
+either a dictionary key or as an element of another set.
+The :class:`frozenset` type is immutable and :term:`hashable` ---
+its contents cannot be altered after it is created;
+it can therefore be used as a dictionary key or as an element of another set.
Non-empty sets (not frozensets) can be created by placing a comma-separated list
of elements within braces, for example: ``{'jack', 'sjoerd'}``, in addition to the
diff --git a/Doc/library/string.rst b/Doc/library/string.rst
index 6336a0ec47b..58c836c7382 100644
--- a/Doc/library/string.rst
+++ b/Doc/library/string.rst
@@ -4,7 +4,7 @@
.. module:: string
:synopsis: Common string operations.
-**Source code:** :source:`Lib/string.py`
+**Source code:** :source:`Lib/string/__init__.py`
--------------
diff --git a/Doc/library/symtable.rst b/Doc/library/symtable.rst
index 54e19af4bd6..f5e6f9f8acf 100644
--- a/Doc/library/symtable.rst
+++ b/Doc/library/symtable.rst
@@ -21,11 +21,17 @@ tables.
Generating Symbol Tables
------------------------
-.. function:: symtable(code, filename, compile_type)
+.. function:: symtable(code, filename, compile_type, *, module=None)
Return the toplevel :class:`SymbolTable` for the Python source *code*.
*filename* is the name of the file containing the code. *compile_type* is
like the *mode* argument to :func:`compile`.
+ The optional argument *module* specifies the module name.
+ It is needed to unambiguous :ref:`filter ` syntax warnings
+ by module name.
+
+ .. versionadded:: 3.15
+ Added the *module* parameter.
Examining Symbol Tables
diff --git a/Doc/library/sys.monitoring.rst b/Doc/library/sys.monitoring.rst
index 0f986aa580b..303655fb128 100644
--- a/Doc/library/sys.monitoring.rst
+++ b/Doc/library/sys.monitoring.rst
@@ -216,14 +216,17 @@ by another event:
The :monitoring-event:`C_RETURN` and :monitoring-event:`C_RAISE` events
are controlled by the :monitoring-event:`CALL` event.
-:monitoring-event:`C_RETURN` and :monitoring-event:`C_RAISE` events will only be seen if the
-corresponding :monitoring-event:`CALL` event is being monitored.
+:monitoring-event:`C_RETURN` and :monitoring-event:`C_RAISE` events will only be
+seen if the corresponding :monitoring-event:`CALL` event is being monitored.
+
+
+.. _monitoring-event-global:
Other events
''''''''''''
Other events are not necessarily tied to a specific location in the
-program and cannot be individually disabled.
+program and cannot be individually disabled via :data:`DISABLE`.
The other events that can be monitored are:
@@ -289,12 +292,13 @@ in Python (see :ref:`c-api-monitoring`).
.. function:: get_local_events(tool_id: int, code: CodeType, /) -> int
- Returns all the local events for *code*
+ Returns all the :ref:`local events ` for *code*
.. function:: set_local_events(tool_id: int, code: CodeType, event_set: int, /) -> None
- Activates all the local events for *code* which are set in *event_set*.
- Raises a :exc:`ValueError` if *tool_id* is not in use.
+ Activates all the :ref:`local events ` for *code*
+ which are set in *event_set*. Raises a :exc:`ValueError` if *tool_id* is not
+ in use.
Disabling events
@@ -305,15 +309,21 @@ Disabling events
A special value that can be returned from a callback function to disable
events for the current code location.
-Local events can be disabled for a specific code location by returning
-:data:`sys.monitoring.DISABLE` from a callback function. This does not change
-which events are set, or any other code locations for the same event.
+:ref:`Local events ` can be disabled for a specific code
+location by returning :data:`sys.monitoring.DISABLE` from a callback function.
+This does not change which events are set, or any other code locations for the
+same event.
Disabling events for specific locations is very important for high
performance monitoring. For example, a program can be run under a
debugger with no overhead if the debugger disables all monitoring
except for a few breakpoints.
+If :data:`DISABLE` is returned by a callback for a
+:ref:`global event `, :exc:`ValueError` will be raised
+by the interpreter in a non-specific location (that is, no traceback will be
+provided).
+
.. function:: restart_events() -> None
Enable all the events that were disabled by :data:`sys.monitoring.DISABLE`
diff --git a/Doc/library/sys.rst b/Doc/library/sys.rst
index 698a9d0689d..a0621d4b0db 100644
--- a/Doc/library/sys.rst
+++ b/Doc/library/sys.rst
@@ -1176,10 +1176,14 @@ always available. Unless explicitly noted otherwise, all variables are read-only
The size of the seed key of the hash algorithm
+ .. attribute:: hash_info.cutoff
+
+ Cutoff for small string DJBX33A optimization in range ``[1, cutoff)``.
+
.. versionadded:: 3.2
.. versionchanged:: 3.4
- Added *algorithm*, *hash_bits* and *seed_bits*
+ Added *algorithm*, *hash_bits*, *seed_bits*, and *cutoff*.
.. data:: hexversion
diff --git a/Doc/library/tarfile.rst b/Doc/library/tarfile.rst
index c4614bf28a4..5ff8502bbe2 100644
--- a/Doc/library/tarfile.rst
+++ b/Doc/library/tarfile.rst
@@ -21,6 +21,14 @@ Some facts and figures:
* reads and writes :mod:`gzip`, :mod:`bz2`, :mod:`compression.zstd`, and
:mod:`lzma` compressed archives if the respective modules are available.
+ ..
+ The following paragraph should be similar to ../includes/optional-module.rst
+
+ If any of these :term:`optional modules ` are missing from
+ your copy of CPython, look for documentation from your distributor (that is,
+ whoever provided Python to you).
+ If you are the distributor, see :ref:`optional-module-requirements`.
+
* read/write support for the POSIX.1-1988 (ustar) format.
* read/write support for the GNU tar format including *longname* and *longlink*
diff --git a/Doc/library/time.rst b/Doc/library/time.rst
index 350ffade7af..a931134331f 100644
--- a/Doc/library/time.rst
+++ b/Doc/library/time.rst
@@ -407,9 +407,9 @@ Functions
On Windows, if *secs* is zero, the thread relinquishes the remainder of its
time slice to any other thread that is ready to run. If there are no other
threads ready to run, the function returns immediately, and the thread
- continues execution. On Windows 8.1 and newer the implementation uses
+ continues execution. On Windows 10 and newer the implementation uses
a `high-resolution timer
- `_
+ `_
which provides resolution of 100 nanoseconds. If *secs* is zero, ``Sleep(0)`` is used.
.. rubric:: Unix implementation
@@ -584,7 +584,7 @@ Functions
calculations when the day of the week and the year are specified.
Here is an example, a format for dates compatible with that specified in the
- :rfc:`2822` Internet email standard. [1]_ ::
+ :rfc:`5322` Internet email standard. [1]_ ::
>>> from time import gmtime, strftime
>>> strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime())
@@ -1066,4 +1066,5 @@ Timezone Constants
strict reading of the original 1982 :rfc:`822` standard calls for a two-digit
year (``%y`` rather than ``%Y``), but practice moved to 4-digit years long before the
year 2000. After that, :rfc:`822` became obsolete and the 4-digit year has
- been first recommended by :rfc:`1123` and then mandated by :rfc:`2822`.
+ been first recommended by :rfc:`1123` and then mandated by :rfc:`2822`,
+ with :rfc:`5322` continuing this requirement.
diff --git a/Doc/library/tkinter.rst b/Doc/library/tkinter.rst
index 22e08c45d01..81177533be8 100644
--- a/Doc/library/tkinter.rst
+++ b/Doc/library/tkinter.rst
@@ -36,6 +36,8 @@ details that are unchanged.
Most documentation you will find online still uses the old API and
can be woefully outdated.
+.. include:: ../includes/optional-module.rst
+
.. seealso::
* `TkDocs `_
diff --git a/Doc/library/turtle.rst b/Doc/library/turtle.rst
index b687231bd48..95a57c57e71 100644
--- a/Doc/library/turtle.rst
+++ b/Doc/library/turtle.rst
@@ -29,6 +29,8 @@ introduced in Logo `_, developed by Wally Feurzeig, Seymour Papert and Cynthia Solomon
in 1967.
+.. include:: ../includes/optional-module.rst
+
Get started
===========
@@ -2799,68 +2801,68 @@ The demo scripts are:
.. tabularcolumns:: |l|L|L|
-+----------------+------------------------------+-----------------------+
-| Name | Description | Features |
-+================+==============================+=======================+
-| bytedesign | complex classical | :func:`tracer`, delay,|
-| | turtle graphics pattern | :func:`update` |
-+----------------+------------------------------+-----------------------+
-| chaos | graphs Verhulst dynamics, | world coordinates |
-| | shows that computer's | |
-| | computations can generate | |
-| | results sometimes against the| |
-| | common sense expectations | |
-+----------------+------------------------------+-----------------------+
-| clock | analog clock showing time | turtles as clock's |
-| | of your computer | hands, ontimer |
-+----------------+------------------------------+-----------------------+
-| colormixer | experiment with r, g, b | :func:`ondrag` |
-+----------------+------------------------------+-----------------------+
-| forest | 3 breadth-first trees | randomization |
-+----------------+------------------------------+-----------------------+
-| fractalcurves | Hilbert & Koch curves | recursion |
-+----------------+------------------------------+-----------------------+
-| lindenmayer | ethnomathematics | L-System |
-| | (indian kolams) | |
-+----------------+------------------------------+-----------------------+
-| minimal_hanoi | Towers of Hanoi | Rectangular Turtles |
-| | | as Hanoi discs |
-| | | (shape, shapesize) |
-+----------------+------------------------------+-----------------------+
-| nim | play the classical nim game | turtles as nimsticks, |
-| | with three heaps of sticks | event driven (mouse, |
-| | against the computer. | keyboard) |
-+----------------+------------------------------+-----------------------+
-| paint | super minimalistic | :func:`onclick` |
-| | drawing program | |
-+----------------+------------------------------+-----------------------+
-| peace | elementary | turtle: appearance |
-| | | and animation |
-+----------------+------------------------------+-----------------------+
-| penrose | aperiodic tiling with | :func:`stamp` |
-| | kites and darts | |
-+----------------+------------------------------+-----------------------+
-| planet_and_moon| simulation of | compound shapes, |
-| | gravitational system | :class:`Vec2D` |
-+----------------+------------------------------+-----------------------+
-| rosette | a pattern from the wikipedia | :func:`clone`, |
-| | article on turtle graphics | :func:`undo` |
-+----------------+------------------------------+-----------------------+
-| round_dance | dancing turtles rotating | compound shapes, clone|
-| | pairwise in opposite | shapesize, tilt, |
-| | direction | get_shapepoly, update |
-+----------------+------------------------------+-----------------------+
-| sorting_animate| visual demonstration of | simple alignment, |
-| | different sorting methods | randomization |
-+----------------+------------------------------+-----------------------+
-| tree | a (graphical) breadth | :func:`clone` |
-| | first tree (using generators)| |
-+----------------+------------------------------+-----------------------+
-| two_canvases | simple design | turtles on two |
-| | | canvases |
-+----------------+------------------------------+-----------------------+
-| yinyang | another elementary example | :func:`circle` |
-+----------------+------------------------------+-----------------------+
++------------------------+------------------------------+--------------------------------------+
+| Name | Description | Features |
++========================+==============================+======================================+
+| ``bytedesign`` | complex classical | :func:`tracer`, :func:`delay`, |
+| | turtle graphics pattern | :func:`update` |
++------------------------+------------------------------+--------------------------------------+
+| ``chaos`` | graphs Verhulst dynamics, | world coordinates |
+| | shows that computer's | |
+| | computations can generate | |
+| | results sometimes against the| |
+| | common sense expectations | |
++------------------------+------------------------------+--------------------------------------+
+| ``clock`` | analog clock showing time | turtles as clock's |
+| | of your computer | hands, :func:`ontimer` |
++------------------------+------------------------------+--------------------------------------+
+| ``colormixer`` | experiment with r, g, b | :func:`ondrag` |
++------------------------+------------------------------+--------------------------------------+
+| ``forest`` | 3 breadth-first trees | randomization |
++------------------------+------------------------------+--------------------------------------+
+| ``fractalcurves`` | Hilbert & Koch curves | recursion |
++------------------------+------------------------------+--------------------------------------+
+| ``lindenmayer`` | ethnomathematics | L-System |
+| | (indian kolams) | |
++------------------------+------------------------------+--------------------------------------+
+| ``minimal_hanoi`` | Towers of Hanoi | Rectangular Turtles |
+| | | as Hanoi discs |
+| | | (:func:`shape`, :func:`shapesize`) |
++------------------------+------------------------------+--------------------------------------+
+| ``nim`` | play the classical nim game | turtles as nimsticks, |
+| | with three heaps of sticks | event driven (mouse, |
+| | against the computer. | keyboard) |
++------------------------+------------------------------+--------------------------------------+
+| ``paint`` | super minimalistic | :func:`onclick` |
+| | drawing program | |
++------------------------+------------------------------+--------------------------------------+
+| ``peace`` | elementary | turtle: appearance |
+| | | and animation |
++------------------------+------------------------------+--------------------------------------+
+| ``penrose`` | aperiodic tiling with | :func:`stamp` |
+| | kites and darts | |
++------------------------+------------------------------+--------------------------------------+
+| ``planet_and_moon`` | simulation of | compound shapes, |
+| | gravitational system | :class:`Vec2D` |
++------------------------+------------------------------+--------------------------------------+
+| ``rosette`` | a pattern from the wikipedia | :func:`clone`, |
+| | article on turtle graphics | :func:`undo` |
++------------------------+------------------------------+--------------------------------------+
+| ``round_dance`` | dancing turtles rotating | compound shapes, :func:`clone` |
+| | pairwise in opposite | :func:`shapesize`, :func:`tilt`, |
+| | direction | :func:`get_shapepoly`, :func:`update`|
++------------------------+------------------------------+--------------------------------------+
+| ``sorting_animate`` | visual demonstration of | simple alignment, |
+| | different sorting methods | randomization |
++------------------------+------------------------------+--------------------------------------+
+| ``tree`` | a (graphical) breadth | :func:`clone` |
+| | first tree (using generators)| |
++------------------------+------------------------------+--------------------------------------+
+| ``two_canvases`` | simple design | turtles on two |
+| | | canvases |
++------------------------+------------------------------+--------------------------------------+
+| ``yinyang`` | another elementary example | :func:`circle` |
++------------------------+------------------------------+--------------------------------------+
Have fun!
diff --git a/Doc/library/unicodedata.rst b/Doc/library/unicodedata.rst
index fd5f56bd7ea..34f21f49b4b 100644
--- a/Doc/library/unicodedata.rst
+++ b/Doc/library/unicodedata.rst
@@ -156,7 +156,7 @@ following functions:
>>> unicodedata.isxidstart('0')
False
- .. versionadded:: next
+ .. versionadded:: 3.15
.. function:: isxidcontinue(chr, /)
@@ -171,7 +171,7 @@ following functions:
>>> unicodedata.isxidcontinue(' ')
False
- .. versionadded:: next
+ .. versionadded:: 3.15
.. function:: decomposition(chr, /)
diff --git a/Doc/library/unittest.mock-examples.rst b/Doc/library/unittest.mock-examples.rst
index 00cc9bfc0a5..61c75b5a03b 100644
--- a/Doc/library/unittest.mock-examples.rst
+++ b/Doc/library/unittest.mock-examples.rst
@@ -600,13 +600,13 @@ this list of calls for us::
Partial mocking
~~~~~~~~~~~~~~~
-In some tests I wanted to mock out a call to :meth:`datetime.date.today`
-to return a known date, but I didn't want to prevent the code under test from
-creating new date objects. Unfortunately :class:`datetime.date` is written in C, and
-so I couldn't just monkey-patch out the static :meth:`datetime.date.today` method.
+For some tests, you may want to mock out a call to :meth:`datetime.date.today`
+to return a known date, but don't want to prevent the code under test from
+creating new date objects. Unfortunately :class:`datetime.date` is written in C,
+so you cannot just monkey-patch out the static :meth:`datetime.date.today` method.
-I found a simple way of doing this that involved effectively wrapping the date
-class with a mock, but passing through calls to the constructor to the real
+Instead, you can effectively wrap the date
+class with a mock, while passing through calls to the constructor to the real
class (and returning real instances).
The :func:`patch decorator ` is used here to
@@ -743,16 +743,15 @@ exception is raised in the setUp then tearDown is not called.
Mocking Unbound Methods
~~~~~~~~~~~~~~~~~~~~~~~
-Whilst writing tests today I needed to patch an *unbound method* (patching the
-method on the class rather than on the instance). I needed self to be passed
-in as the first argument because I want to make asserts about which objects
-were calling this particular method. The issue is that you can't patch with a
-mock for this, because if you replace an unbound method with a mock it doesn't
-become a bound method when fetched from the instance, and so it doesn't get
-self passed in. The workaround is to patch the unbound method with a real
-function instead. The :func:`patch` decorator makes it so simple to
-patch out methods with a mock that having to create a real function becomes a
-nuisance.
+Sometimes a test needs to patch an *unbound method*, which means patching the
+method on the class rather than on the instance. In order to make assertions
+about which objects were calling this particular method, you need to pass
+``self`` as the first argument. The issue is that you can't patch with a mock for
+this, because if you replace an unbound method with a mock it doesn't become
+a bound method when fetched from the instance, and so it doesn't get ``self``
+passed in. The workaround is to patch the unbound method with a real function
+instead. The :func:`patch` decorator makes it so simple to patch out methods
+with a mock that having to create a real function becomes a nuisance.
If you pass ``autospec=True`` to patch then it does the patching with a
*real* function object. This function object has the same signature as the one
@@ -760,8 +759,8 @@ it is replacing, but delegates to a mock under the hood. You still get your
mock auto-created in exactly the same way as before. What it means though, is
that if you use it to patch out an unbound method on a class the mocked
function will be turned into a bound method if it is fetched from an instance.
-It will have ``self`` passed in as the first argument, which is exactly what I
-wanted:
+It will have ``self`` passed in as the first argument, which is exactly what
+was needed:
>>> class Foo:
... def foo(self):
@@ -864,9 +863,9 @@ Here's one solution that uses the :attr:`~Mock.side_effect`
functionality. If you provide a ``side_effect`` function for a mock then
``side_effect`` will be called with the same args as the mock. This gives us an
opportunity to copy the arguments and store them for later assertions. In this
-example I'm using *another* mock to store the arguments so that I can use the
+example we're using *another* mock to store the arguments so that we can use the
mock methods for doing the assertion. Again a helper function sets this up for
-me. ::
+us. ::
>>> from copy import deepcopy
>>> from unittest.mock import Mock, patch, DEFAULT
diff --git a/Doc/library/unittest.rst b/Doc/library/unittest.rst
index fe45becce2e..0bc0a953fd9 100644
--- a/Doc/library/unittest.rst
+++ b/Doc/library/unittest.rst
@@ -438,7 +438,7 @@ run whether the test method succeeded or not.
Such a working environment for the testing code is called a
:dfn:`test fixture`. A new TestCase instance is created as a unique
test fixture used to execute each individual test method. Thus
-:meth:`~TestCase.setUp`, :meth:`~TestCase.tearDown`, and :meth:`~TestCase.__init__`
+:meth:`~TestCase.setUp`, :meth:`~TestCase.tearDown`, and :meth:`!TestCase.__init__`
will be called once per test.
It is recommended that you use TestCase implementations to group tests together
@@ -518,7 +518,7 @@ set-up and tear-down methods::
subclasses will make future test refactorings infinitely easier.
In some cases, the existing tests may have been written using the :mod:`doctest`
-module. If so, :mod:`doctest` provides a :class:`DocTestSuite` class that can
+module. If so, :mod:`doctest` provides a :class:`~doctest.DocTestSuite` class that can
automatically build :class:`unittest.TestSuite` instances from the existing
:mod:`doctest`\ -based tests.
@@ -1023,7 +1023,7 @@ Test cases
additional keyword argument *msg*.
The context manager will store the caught exception object in its
- :attr:`exception` attribute. This can be useful if the intention
+ :attr:`!exception` attribute. This can be useful if the intention
is to perform additional checks on the exception raised::
with self.assertRaises(SomeException) as cm:
@@ -1036,7 +1036,7 @@ Test cases
Added the ability to use :meth:`assertRaises` as a context manager.
.. versionchanged:: 3.2
- Added the :attr:`exception` attribute.
+ Added the :attr:`!exception` attribute.
.. versionchanged:: 3.3
Added the *msg* keyword argument when used as a context manager.
@@ -1089,8 +1089,8 @@ Test cases
additional keyword argument *msg*.
The context manager will store the caught warning object in its
- :attr:`warning` attribute, and the source line which triggered the
- warnings in the :attr:`filename` and :attr:`lineno` attributes.
+ :attr:`!warning` attribute, and the source line which triggered the
+ warnings in the :attr:`!filename` and :attr:`!lineno` attributes.
This can be useful if the intention is to perform additional checks
on the warning caught::
@@ -1437,7 +1437,7 @@ Test cases
that lists the differences between the sets. This method is used by
default when comparing sets or frozensets with :meth:`assertEqual`.
- Fails if either of *first* or *second* does not have a :meth:`set.difference`
+ Fails if either of *first* or *second* does not have a :meth:`~frozenset.difference`
method.
.. versionadded:: 3.1
@@ -1645,7 +1645,7 @@ Test cases
.. method:: asyncSetUp()
:async:
- Method called to prepare the test fixture. This is called after :meth:`setUp`.
+ Method called to prepare the test fixture. This is called after :meth:`TestCase.setUp`.
This is called immediately before calling the test method; other than
:exc:`AssertionError` or :exc:`SkipTest`, any exception raised by this method
will be considered an error rather than a test failure. The default implementation
@@ -1655,7 +1655,7 @@ Test cases
:async:
Method called immediately after the test method has been called and the
- result recorded. This is called before :meth:`tearDown`. This is called even if
+ result recorded. This is called before :meth:`~TestCase.tearDown`. This is called even if
the test method raised an exception, so the implementation in subclasses may need
to be particularly careful about checking internal state. Any exception, other than
:exc:`AssertionError` or :exc:`SkipTest`, raised by this method will be
@@ -1684,7 +1684,7 @@ Test cases
Sets up a new event loop to run the test, collecting the result into
the :class:`TestResult` object passed as *result*. If *result* is
omitted or ``None``, a temporary result object is created (by calling
- the :meth:`defaultTestResult` method) and used. The result object is
+ the :meth:`~TestCase.defaultTestResult` method) and used. The result object is
returned to :meth:`run`'s caller. At the end of the test all the tasks
in the event loop are cancelled.
@@ -1805,7 +1805,7 @@ Grouping tests
returned by repeated iterations before :meth:`TestSuite.run` must be the
same for each call iteration. After :meth:`TestSuite.run`, callers should
not rely on the tests returned by this method unless the caller uses a
- subclass that overrides :meth:`TestSuite._removeTestAtIndex` to preserve
+ subclass that overrides :meth:`!TestSuite._removeTestAtIndex` to preserve
test references.
.. versionchanged:: 3.2
@@ -1816,10 +1816,10 @@ Grouping tests
.. versionchanged:: 3.4
In earlier versions the :class:`TestSuite` held references to each
:class:`TestCase` after :meth:`TestSuite.run`. Subclasses can restore
- that behavior by overriding :meth:`TestSuite._removeTestAtIndex`.
+ that behavior by overriding :meth:`!TestSuite._removeTestAtIndex`.
In the typical usage of a :class:`TestSuite` object, the :meth:`run` method
- is invoked by a :class:`TestRunner` rather than by the end-user test harness.
+ is invoked by a :class:`!TestRunner` rather than by the end-user test harness.
Loading and running tests
@@ -1853,12 +1853,12 @@ Loading and running tests
.. method:: loadTestsFromTestCase(testCaseClass)
Return a suite of all test cases contained in the :class:`TestCase`\ -derived
- :class:`testCaseClass`.
+ :class:`!testCaseClass`.
A test case instance is created for each method named by
:meth:`getTestCaseNames`. By default these are the method names
beginning with ``test``. If :meth:`getTestCaseNames` returns no
- methods, but the :meth:`runTest` method is implemented, a single test
+ methods, but the :meth:`!runTest` method is implemented, a single test
case is created for that method instead.
@@ -1905,13 +1905,13 @@ Loading and running tests
case class will be picked up as "a test method within a test case class",
rather than "a callable object".
- For example, if you have a module :mod:`SampleTests` containing a
- :class:`TestCase`\ -derived class :class:`SampleTestCase` with three test
- methods (:meth:`test_one`, :meth:`test_two`, and :meth:`test_three`), the
+ For example, if you have a module :mod:`!SampleTests` containing a
+ :class:`TestCase`\ -derived class :class:`!SampleTestCase` with three test
+ methods (:meth:`!test_one`, :meth:`!test_two`, and :meth:`!test_three`), the
specifier ``'SampleTests.SampleTestCase'`` would cause this method to
return a suite which will run all three test methods. Using the specifier
``'SampleTests.SampleTestCase.test_two'`` would cause it to return a test
- suite which will run only the :meth:`test_two` test method. The specifier
+ suite which will run only the :meth:`!test_two` test method. The specifier
can refer to modules and packages which have not been imported; they will
be imported as a side-effect.
@@ -2058,7 +2058,7 @@ Loading and running tests
Testing frameworks built on top of :mod:`unittest` may want access to the
:class:`TestResult` object generated by running a set of tests for reporting
purposes; a :class:`TestResult` instance is returned by the
- :meth:`TestRunner.run` method for this purpose.
+ :meth:`!TestRunner.run` method for this purpose.
:class:`TestResult` instances have the following attributes that will be of
interest when inspecting the results of running a set of tests:
@@ -2144,12 +2144,12 @@ Loading and running tests
This method can be called to signal that the set of tests being run should
be aborted by setting the :attr:`shouldStop` attribute to ``True``.
- :class:`TestRunner` objects should respect this flag and return without
+ :class:`!TestRunner` objects should respect this flag and return without
running any additional tests.
For example, this feature is used by the :class:`TextTestRunner` class to
stop the test framework when the user signals an interrupt from the
- keyboard. Interactive tools which provide :class:`TestRunner`
+ keyboard. Interactive tools which provide :class:`!TestRunner`
implementations can use this in a similar manner.
The following methods of the :class:`TestResult` class are used to maintain
@@ -2469,9 +2469,9 @@ Class and Module Fixtures
-------------------------
Class and module level fixtures are implemented in :class:`TestSuite`. When
-the test suite encounters a test from a new class then :meth:`tearDownClass`
-from the previous class (if there is one) is called, followed by
-:meth:`setUpClass` from the new class.
+the test suite encounters a test from a new class then
+:meth:`~TestCase.tearDownClass` from the previous class (if there is one)
+is called, followed by :meth:`~TestCase.setUpClass` from the new class.
Similarly if a test is from a different module from the previous test then
``tearDownModule`` from the previous module is run, followed by
diff --git a/Doc/library/urllib.robotparser.rst b/Doc/library/urllib.robotparser.rst
index 016fcdc75da..674f646c633 100644
--- a/Doc/library/urllib.robotparser.rst
+++ b/Doc/library/urllib.robotparser.rst
@@ -19,7 +19,7 @@
This module provides a single class, :class:`RobotFileParser`, which answers
questions about whether or not a particular user agent can fetch a URL on the
-web site that published the :file:`robots.txt` file. For more details on the
+website that published the :file:`robots.txt` file. For more details on the
structure of :file:`robots.txt` files, see http://www.robotstxt.org/orig.html.
diff --git a/Doc/library/warnings.rst b/Doc/library/warnings.rst
index 2f3cf6008f5..0de7a90bfcb 100644
--- a/Doc/library/warnings.rst
+++ b/Doc/library/warnings.rst
@@ -513,7 +513,7 @@ Available Functions
.. versionchanged:: 3.6
Add the *source* parameter.
- .. versionchanged:: next
+ .. versionchanged:: 3.15
If no module is passed, test the filter regular expression against
module names created from the path, not only the path itself.
diff --git a/Doc/library/wave.rst b/Doc/library/wave.rst
index a3f5bfd5e2f..7ff2c97992c 100644
--- a/Doc/library/wave.rst
+++ b/Doc/library/wave.rst
@@ -25,8 +25,9 @@ The :mod:`wave` module defines the following function and exception:
.. function:: open(file, mode=None)
- If *file* is a string, open the file by that name, otherwise treat it as a
- file-like object. *mode* can be:
+ If *file* is a string, a :term:`path-like object` or a
+ :term:`bytes-like object` open the file by that name, otherwise treat it as
+ a file-like object. *mode* can be:
``'rb'``
Read only mode.
@@ -52,6 +53,10 @@ The :mod:`wave` module defines the following function and exception:
.. versionchanged:: 3.4
Added support for unseekable files.
+ .. versionchanged:: 3.15
+ Added support for :term:`path-like objects `
+ and :term:`bytes-like objects `.
+
.. exception:: Error
An error raised when something is impossible because it violates the WAV
diff --git a/Doc/library/webbrowser.rst b/Doc/library/webbrowser.rst
index fd6abc70261..a2103d8fdd8 100644
--- a/Doc/library/webbrowser.rst
+++ b/Doc/library/webbrowser.rst
@@ -49,6 +49,11 @@ a new tab, with the browser being brought to the foreground. The use of the
:mod:`webbrowser` module on iOS requires the :mod:`ctypes` module. If
:mod:`ctypes` isn't available, calls to :func:`.open` will fail.
+.. _webbrowser-cli:
+
+Command-line interface
+----------------------
+
.. program:: webbrowser
The script :program:`webbrowser` can be used as a command-line interface for the
@@ -232,7 +237,7 @@ Here are some simple examples::
.. _browser-controllers:
-Browser Controller Objects
+Browser controller objects
--------------------------
Browser controllers provide the :attr:`~controller.name` attribute,
diff --git a/Doc/library/winreg.rst b/Doc/library/winreg.rst
index 83c49876d26..89def6e2afe 100644
--- a/Doc/library/winreg.rst
+++ b/Doc/library/winreg.rst
@@ -14,6 +14,8 @@ integer as the registry handle, a :ref:`handle object ` is used
to ensure that the handles are closed correctly, even if the programmer neglects
to explicitly close them.
+.. availability:: Windows.
+
.. _exception-changed:
.. versionchanged:: 3.3
@@ -771,8 +773,9 @@ Handle objects provide semantics for :meth:`~object.__bool__` -- thus ::
will print ``Yes`` if the handle is currently valid (has not been closed or
detached).
-The object also support comparison semantics, so handle objects will compare
-true if they both reference the same underlying Windows handle value.
+The object also support equality comparison semantics, so handle objects will
+compare equal if they both reference the same underlying Windows handle value.
+Closed handle objects (those with a handle value of zero) always compare equal.
Handle objects can be converted to an integer (e.g., using the built-in
:func:`int` function), in which case the underlying Windows handle value is
@@ -815,3 +818,6 @@ integer handle, and also disconnect the Windows handle from the handle object.
will automatically close *key* when control leaves the :keyword:`with` block.
+.. versionchanged:: 3.15
+ Handle objects are now compared by their underlying Windows handle value
+ instead of object identity for equality comparisons.
diff --git a/Doc/library/winsound.rst b/Doc/library/winsound.rst
index 925984c3cdb..93c0c025982 100644
--- a/Doc/library/winsound.rst
+++ b/Doc/library/winsound.rst
@@ -13,6 +13,8 @@
The :mod:`winsound` module provides access to the basic sound-playing machinery
provided by Windows platforms. It includes functions and several constants.
+.. availability:: Windows.
+
.. function:: Beep(frequency, duration)
diff --git a/Doc/library/xml.dom.pulldom.rst b/Doc/library/xml.dom.pulldom.rst
index 8bceeecd463..a21cfaa4645 100644
--- a/Doc/library/xml.dom.pulldom.rst
+++ b/Doc/library/xml.dom.pulldom.rst
@@ -74,7 +74,7 @@ given point) or to make use of the :func:`DOMEventStream.expandNode` method
and switch to DOM-related processing.
-.. class:: PullDom(documentFactory=None)
+.. class:: PullDOM(documentFactory=None)
Subclass of :class:`xml.sax.handler.ContentHandler`.
diff --git a/Doc/library/xml.etree.elementtree.rst b/Doc/library/xml.etree.elementtree.rst
index 881708a4dd7..e59759683a6 100644
--- a/Doc/library/xml.etree.elementtree.rst
+++ b/Doc/library/xml.etree.elementtree.rst
@@ -656,6 +656,10 @@ Functions
.. versionchanged:: 3.13
Added the :meth:`!close` method.
+ .. versionchanged:: 3.15
+ A :exc:`ResourceWarning` is now emitted if the iterator opened a file
+ and is not explicitly closed.
+
.. function:: parse(source, parser=None)
diff --git a/Doc/library/xml.rst b/Doc/library/xml.rst
index 3f745573474..acd8d399fe3 100644
--- a/Doc/library/xml.rst
+++ b/Doc/library/xml.rst
@@ -53,11 +53,22 @@ XML security
An attacker can abuse XML features to carry out denial of service attacks,
access local files, generate network connections to other machines, or
-circumvent firewalls.
+circumvent firewalls when attacker-controlled XML is being parsed,
+in Python or elsewhere.
-Expat versions lower than 2.6.0 may be vulnerable to "billion laughs",
-"quadratic blowup" and "large tokens". Python may be vulnerable if it uses such
-older versions of Expat as a system-provided library.
+The built-in XML parsers of Python rely on the library `libexpat`_, commonly
+called Expat, for parsing XML.
+
+By default, Expat itself does not access local files or create network
+connections.
+
+Expat versions lower than 2.7.2 may be vulnerable to the "billion laughs",
+"quadratic blowup" and "large tokens" vulnerabilities, or to disproportional
+use of dynamic memory.
+Python bundles a copy of Expat, and whether Python uses the bundled or a
+system-wide Expat, depends on how the Python interpreter
+:option:`has been configured <--with-system-expat>` in your environment.
+Python may be vulnerable if it uses such older versions of Expat.
Check :const:`!pyexpat.EXPAT_VERSION`.
:mod:`xmlrpc` is **vulnerable** to the "decompression bomb" attack.
@@ -90,5 +101,6 @@ large tokens
be used to cause denial of service in the application parsing XML.
The issue is known as :cve:`2023-52425`.
+.. _libexpat: https://github.com/libexpat/libexpat
.. _Billion Laughs: https://en.wikipedia.org/wiki/Billion_laughs
.. _ZIP bomb: https://en.wikipedia.org/wiki/Zip_bomb
diff --git a/Doc/library/xml.sax.utils.rst b/Doc/library/xml.sax.utils.rst
index 5ee11d58c3d..7731f03d875 100644
--- a/Doc/library/xml.sax.utils.rst
+++ b/Doc/library/xml.sax.utils.rst
@@ -37,7 +37,7 @@ or as base classes.
You can unescape other strings of data by passing a dictionary as the optional
*entities* parameter. The keys and values must all be strings; each key will be
- replaced with its corresponding value. ``'&'``, ``'<'``, and ``'>'``
+ replaced with its corresponding value. ``'&'``, ``'<'``, and ``'>'``
are always unescaped, even if *entities* is provided.
diff --git a/Doc/library/xmlrpc.client.rst b/Doc/library/xmlrpc.client.rst
index a21c7d3e4e3..e4912629aac 100644
--- a/Doc/library/xmlrpc.client.rst
+++ b/Doc/library/xmlrpc.client.rst
@@ -179,9 +179,9 @@ ServerProxy Objects
A :class:`ServerProxy` instance has a method corresponding to each remote
procedure call accepted by the XML-RPC server. Calling the method performs an
RPC, dispatched by both name and argument signature (e.g. the same method name
-can be overloaded with multiple argument signatures). The RPC finishes by
-returning a value, which may be either returned data in a conformant type or a
-:class:`Fault` or :class:`ProtocolError` object indicating an error.
+can be overloaded with multiple argument signatures). The RPC finishes either
+by returning data in a conformant type or by raising a :class:`Fault` or
+:class:`ProtocolError` exception indicating an error.
Servers that support the XML introspection API support some common methods
grouped under the reserved :attr:`~ServerProxy.system` attribute:
diff --git a/Doc/library/zipfile.rst b/Doc/library/zipfile.rst
index f6ec33640b6..5a8bbc8c1ae 100644
--- a/Doc/library/zipfile.rst
+++ b/Doc/library/zipfile.rst
@@ -23,6 +23,16 @@ decryption of encrypted files in ZIP archives, but it currently cannot
create an encrypted file. Decryption is extremely slow as it is
implemented in native Python rather than C.
+..
+ The following paragraph should be similar to ../includes/optional-module.rst
+
+Handling compressed archives requires :term:`optional modules `
+such as :mod:`zlib`, :mod:`bz2`, :mod:`lzma`, and :mod:`compression.zstd`.
+If any of them are missing from your copy of CPython,
+look for documentation from your distributor (that is,
+whoever provided Python to you).
+If you are the distributor, see :ref:`optional-module-requirements`.
+
The module defines the following items:
.. exception:: BadZipFile
diff --git a/Doc/library/zlib.rst b/Doc/library/zlib.rst
index b961f7113d3..ce0a22b9456 100644
--- a/Doc/library/zlib.rst
+++ b/Doc/library/zlib.rst
@@ -8,9 +8,9 @@
--------------
For applications that require data compression, the functions in this module
-allow compression and decompression, using the zlib library. The zlib library
-has its own home page at https://www.zlib.net. zlib 1.2.2.1 is the minium
-supported version.
+allow compression and decompression, using the `zlib library `_.
+
+.. include:: ../includes/optional-module.rst
zlib's functions have many options and often need to be used in a particular
order. This documentation doesn't attempt to cover all of the permutations;
diff --git a/Doc/reference/datamodel.rst b/Doc/reference/datamodel.rst
index 882b05e8731..ebadbc215a0 100644
--- a/Doc/reference/datamodel.rst
+++ b/Doc/reference/datamodel.rst
@@ -2630,8 +2630,8 @@ Notes on using *__slots__*:
descriptor directly from the base class). This renders the meaning of the
program undefined. In the future, a check may be added to prevent this.
-* :exc:`TypeError` will be raised if nonempty *__slots__* are defined for a
- class derived from a
+* :exc:`TypeError` will be raised if *__slots__* other than *__dict__* and
+ *__weakref__* are defined for a class derived from a
:c:member:`"variable-length" built-in type ` such as
:class:`int`, :class:`bytes`, and :class:`tuple`.
@@ -2656,6 +2656,10 @@ Notes on using *__slots__*:
of the iterator's values. However, the *__slots__* attribute will be an empty
iterator.
+.. versionchanged:: next
+ Allowed defining the *__dict__* and *__weakref__* *__slots__* for any class.
+
+
.. _class-customization:
Customizing class creation
diff --git a/Doc/tools/.nitignore b/Doc/tools/.nitignore
index 6fee1c192c3..520e64f5fe1 100644
--- a/Doc/tools/.nitignore
+++ b/Doc/tools/.nitignore
@@ -8,7 +8,6 @@ Doc/c-api/init_config.rst
Doc/c-api/intro.rst
Doc/c-api/module.rst
Doc/c-api/stable.rst
-Doc/c-api/type.rst
Doc/c-api/typeobj.rst
Doc/library/ast.rst
Doc/library/asyncio-extending.rst
@@ -30,14 +29,12 @@ Doc/library/pyexpat.rst
Doc/library/select.rst
Doc/library/socket.rst
Doc/library/ssl.rst
-Doc/library/stdtypes.rst
Doc/library/termios.rst
Doc/library/test.rst
Doc/library/tkinter.rst
Doc/library/tkinter.scrolledtext.rst
Doc/library/tkinter.ttk.rst
Doc/library/unittest.mock.rst
-Doc/library/unittest.rst
Doc/library/urllib.parse.rst
Doc/library/urllib.request.rst
Doc/library/wsgiref.rst
diff --git a/Doc/tools/extensions/c_annotations.py b/Doc/tools/extensions/c_annotations.py
index 089614a1f6c..e04a5f144c4 100644
--- a/Doc/tools/extensions/c_annotations.py
+++ b/Doc/tools/extensions/c_annotations.py
@@ -154,7 +154,10 @@ def add_annotations(app: Sphinx, doctree: nodes.document) -> None:
node.insert(0, annotation)
-def _stable_abi_annotation(record: StableABIEntry) -> nodes.emphasis:
+def _stable_abi_annotation(
+ record: StableABIEntry,
+ is_corresponding_slot: bool = False,
+) -> nodes.emphasis:
"""Create the Stable ABI annotation.
These have two forms:
@@ -168,9 +171,28 @@ def _stable_abi_annotation(record: StableABIEntry) -> nodes.emphasis:
... all of which can have "since version X.Y" appended.
"""
stable_added = record.added
- message = sphinx_gettext("Part of the")
- message = message.center(len(message) + 2)
- emph_node = nodes.emphasis(message, message, classes=["stableabi"])
+ emph_node = nodes.emphasis('', '', classes=["stableabi"])
+ if is_corresponding_slot:
+ # See "Type slot annotations" in add_annotations
+ ref_node = addnodes.pending_xref(
+ "slot ID",
+ refdomain="c",
+ reftarget="PyType_Slot",
+ reftype="type",
+ refexplicit="True",
+ )
+ ref_node += nodes.Text(sphinx_gettext("slot ID"))
+
+ message = sphinx_gettext("The corresponding")
+ emph_node += nodes.Text(" " + message + " ")
+ emph_node += ref_node
+ emph_node += nodes.Text(" ")
+ emph_node += nodes.literal(record.name, record.name)
+ message = sphinx_gettext("is part of the")
+ emph_node += nodes.Text(" " + message + " ")
+ else:
+ message = sphinx_gettext("Part of the")
+ emph_node += nodes.Text(" " + message + " ")
ref_node = addnodes.pending_xref(
"Stable ABI",
refdomain="std",
@@ -265,6 +287,51 @@ def run(self) -> list[nodes.Node]:
return [node]
+class CorrespondingTypeSlot(SphinxDirective):
+ """Type slot annotations
+
+ Docs for these are with the corresponding field, for example,
+ "Py_tp_repr" is documented under "PyTypeObject.tp_repr", with
+ only a stable ABI note mentioning "Py_tp_repr" (and linking to
+ docs on how this works).
+
+ If there is no corresponding field, these should be documented as normal
+ macros.
+ """
+
+ has_content = False
+
+ required_arguments = 1
+ optional_arguments = 0
+
+ def run(self) -> list[nodes.Node]:
+ name = self.arguments[0]
+ state = self.env.domaindata["c_annotations"]
+ stable_abi_data = state["stable_abi_data"]
+
+ try:
+ record = stable_abi_data[name]
+ except LookupError as err:
+ raise LookupError(
+ f"{name} is not part of stable ABI. "
+ + "Document it as `c:macro::` rather than "
+ + "`corresponding-type-slot::`."
+ ) from err
+
+ annotation = _stable_abi_annotation(record, is_corresponding_slot=True)
+
+ node = nodes.paragraph()
+ content = [
+ ".. c:namespace:: NULL",
+ "",
+ ".. c:macro:: " + name,
+ " :no-typesetting:",
+ ]
+ self.state.nested_parse(StringList(content), 0, node)
+ node.insert(0, annotation)
+ return [node]
+
+
def init_annotations(app: Sphinx) -> None:
# Using domaindata is a bit hack-ish,
# but allows storing state without a global variable or closure.
@@ -281,6 +348,7 @@ def setup(app: Sphinx) -> ExtensionMetadata:
app.add_config_value("refcount_file", "", "env", types={str})
app.add_config_value("stable_abi_file", "", "env", types={str})
app.add_directive("limited-api-list", LimitedAPIList)
+ app.add_directive("corresponding-type-slot", CorrespondingTypeSlot)
app.connect("builder-inited", init_annotations)
app.connect("doctree-read", add_annotations)
diff --git a/Doc/tools/templates/download.html b/Doc/tools/templates/download.html
index f914ad86211..c78c650b1cb 100644
--- a/Doc/tools/templates/download.html
+++ b/Doc/tools/templates/download.html
@@ -31,8 +31,7 @@
{% trans %}Download Python {{ dl_version }} documentation{% endtrans %}
{% if last_updated %}
{% trans %}Last updated on: {{ last_updated }}.{% endtrans %}
{% endif %}
-
{% trans %}To download an archive containing all the documents for this version of
-Python in one of various formats, follow one of links in this table.{% endtrans %}
+
{% trans %}Download an archive containing all the documentation for this version of Python:{% endtrans %}
@@ -62,8 +61,6 @@
{% trans %}Download Python {{ dl_version }} documentation{% endtrans %}
-
{% trans %}These archives contain all the content in the documentation.{% endtrans %}
-
{% trans %}
We no longer provide pre-built PDFs of the documentation.
To build a PDF archive, follow the instructions in the
@@ -75,7 +72,6 @@
{% trans %}Download Python {{ dl_version }} documentation{% endtrans %}
{% trans bugs = bugs %}Open an issue
diff --git a/Doc/tools/templates/dummy.html b/Doc/tools/templates/dummy.html
index 0fdbe2a5801..75f6607d8f3 100644
--- a/Doc/tools/templates/dummy.html
+++ b/Doc/tools/templates/dummy.html
@@ -27,8 +27,8 @@
In extensions/changes.py:
-{% trans %}Deprecated since version {deprecated}, will be removed in version {removed}{% endtrans %}
-{% trans %}Deprecated since version {deprecated}, removed in version {removed}{% endtrans %}
+{% trans %}Deprecated since version %s, will be removed in version %s{% endtrans %}
+{% trans %}Deprecated since version %s, removed in version %s{% endtrans %}
In docsbuild-scripts, when rewriting indexsidebar.html with actual versions:
diff --git a/Doc/tutorial/datastructures.rst b/Doc/tutorial/datastructures.rst
index 1332c53f396..7e02e74177c 100644
--- a/Doc/tutorial/datastructures.rst
+++ b/Doc/tutorial/datastructures.rst
@@ -12,9 +12,8 @@ and adds some new things as well.
More on Lists
=============
-The list data type has some more methods. Here are all of the methods of list
-objects:
-
+The :ref:`list ` data type has some more methods. Here are all
+of the methods of list objects:
.. method:: list.append(x)
:noindex:
@@ -445,10 +444,11 @@ packing and sequence unpacking.
Sets
====
-Python also includes a data type for *sets*. A set is an unordered collection
-with no duplicate elements. Basic uses include membership testing and
-eliminating duplicate entries. Set objects also support mathematical operations
-like union, intersection, difference, and symmetric difference.
+Python also includes a data type for :ref:`sets `. A set is
+an unordered collection with no duplicate elements. Basic uses include
+membership testing and eliminating duplicate entries. Set objects also
+support mathematical operations like union, intersection, difference, and
+symmetric difference.
Curly braces or the :func:`set` function can be used to create sets. Note: to
create an empty set you have to use ``set()``, not ``{}``; the latter creates an
diff --git a/Doc/tutorial/index.rst b/Doc/tutorial/index.rst
index d0bf77dc40d..20fe161be4a 100644
--- a/Doc/tutorial/index.rst
+++ b/Doc/tutorial/index.rst
@@ -15,7 +15,7 @@ together with its interpreted nature, make it an ideal language for scripting
and rapid application development in many areas on most platforms.
The Python interpreter and the extensive standard library are freely available
-in source or binary form for all major platforms from the Python web site,
+in source or binary form for all major platforms from the Python website,
https://www.python.org/, and may be freely distributed. The same site also
contains distributions of and pointers to many free third party Python modules,
programs and tools, and additional documentation.
diff --git a/Doc/tutorial/stdlib.rst b/Doc/tutorial/stdlib.rst
index d83ecca270b..342c1a00193 100644
--- a/Doc/tutorial/stdlib.rst
+++ b/Doc/tutorial/stdlib.rst
@@ -183,13 +183,13 @@ protocols. Two of the simplest are :mod:`urllib.request` for retrieving data
from URLs and :mod:`smtplib` for sending mail::
>>> from urllib.request import urlopen
- >>> with urlopen('http://worldtimeapi.org/api/timezone/etc/UTC.txt') as response:
+ >>> with urlopen('https://docs.python.org/3/') as response:
... for line in response:
... line = line.decode() # Convert bytes to a str
- ... if line.startswith('datetime'):
+ ... if 'updated' in line:
... print(line.rstrip()) # Remove trailing newline
...
- datetime: 2022-01-01T01:36:47.689215+00:00
+ Last updated on Nov 11, 2025 (20:11 UTC).
>>> import smtplib
>>> server = smtplib.SMTP('localhost')
@@ -335,7 +335,7 @@ sophisticated and robust capabilities of its larger packages. For example:
names, no direct knowledge or handling of XML is needed.
* The :mod:`email` package is a library for managing email messages, including
- MIME and other :rfc:`2822`-based message documents. Unlike :mod:`smtplib` and
+ MIME and other :rfc:`5322`-based message documents. Unlike :mod:`smtplib` and
:mod:`poplib` which actually send and receive messages, the email package has
a complete toolset for building or decoding complex message structures
(including attachments) and for implementing internet encoding and header
diff --git a/Doc/tutorial/whatnow.rst b/Doc/tutorial/whatnow.rst
index dbe2d7fc099..359cf80a7b2 100644
--- a/Doc/tutorial/whatnow.rst
+++ b/Doc/tutorial/whatnow.rst
@@ -30,7 +30,7 @@ the set are:
More Python resources:
-* https://www.python.org: The major Python web site. It contains code,
+* https://www.python.org: The major Python website. It contains code,
documentation, and pointers to Python-related pages around the web.
* https://docs.python.org: Fast access to Python's documentation.
diff --git a/Doc/using/configure.rst b/Doc/using/configure.rst
index 1f773a3a547..cdadbe51417 100644
--- a/Doc/using/configure.rst
+++ b/Doc/using/configure.rst
@@ -4,10 +4,13 @@ Configure Python
.. highlight:: sh
+
+.. _build-requirements:
+
Build Requirements
==================
-Features and minimum versions required to build CPython:
+To build CPython, you will need:
* A `C11 `_ compiler. `Optional C11
features
@@ -22,85 +25,138 @@ Features and minimum versions required to build CPython:
* Support for threads.
-To build optional modules:
-
-* `libbz2 `_ for the :mod:`bz2` module.
-
-* `libb2 `_ (:ref:`BLAKE2 `)
- for the :mod:`hashlib` module.
-
-* `libffi `_ 3.3.0 is the recommended
- minimum version for the :mod:`ctypes` module.
-
-* ``liblzma`` for the :mod:`lzma` module.
-
-* `libmpdec `_ 2.5.0
- for the :mod:`decimal` module.
-
-* ``libncurses`` or ``libncursesw`` for the :mod:`curses` module.
-
-* ``libpanel`` or ``libpanelw`` for the :mod:`curses.panel` module.
-
-* `libreadline `_ or
- `libedit `_
- for the :mod:`readline` module.
-
-* `libuuid `_ for the :mod:`uuid` module.
-
-* `OpenSSL `_ 1.1.1 is the minimum version and
- OpenSSL 3.0.18 is the recommended minimum version for the
- :mod:`ssl` and :mod:`hashlib` extension modules.
-
-* `SQLite `_ 3.15.2 for the :mod:`sqlite3` extension module.
-
-* `Tcl/Tk `_ 8.5.12 for the :mod:`tkinter` module.
-
-* `zlib `_ 1.2.2.1 is the minimum version for the
- :mod:`zlib` module.
-
-* `zstd `_ 1.4.5 is the minimum version for
- the :mod:`compression.zstd` module.
-
-For a full list of dependencies required to build all modules and how to install
-them, see the
-`devguide `_.
-
-* Autoconf 2.72 and aclocal 1.16.5 are required to regenerate the
- :file:`configure` script.
-
-.. versionchanged:: 3.1
- Tcl/Tk version 8.3.1 is now required.
-
.. versionchanged:: 3.5
On Windows, Visual Studio 2015 or later is now required.
- Tcl/Tk version 8.4 is now required.
.. versionchanged:: 3.6
- Selected C99 features are now required, like ```` and ``static
- inline`` functions.
+ Selected C99 features, like ```` and ``static inline`` functions,
+ are now required.
.. versionchanged:: 3.7
- Thread support and OpenSSL 1.0.2 are now required.
-
-.. versionchanged:: 3.10
- OpenSSL 1.1.1 is now required.
- Require SQLite 3.7.15.
+ Thread support is now required.
.. versionchanged:: 3.11
C11 compiler, IEEE 754 and NaN support are now required.
On Windows, Visual Studio 2017 or later is required.
- Tcl/Tk version 8.5.12 is now required for the :mod:`tkinter` module.
-
-.. versionchanged:: 3.13
- Autoconf 2.71, aclocal 1.16.5 and SQLite 3.15.2 are now required.
-
-.. versionchanged:: 3.14
- Autoconf 2.72 is now required.
See also :pep:`7` "Style Guide for C Code" and :pep:`11` "CPython platform
support".
+.. _optional-module-requirements:
+
+Requirements for optional modules
+---------------------------------
+
+Some :term:`optional modules ` of the standard library
+require third-party libraries installed for development
+(for example, header files must be available).
+
+Missing requirements are reported in the ``configure`` output.
+Modules that are missing due to missing dependencies are listed near the end
+of the ``make`` output,
+sometimes using an internal name, for example, ``_ctypes`` for :mod:`ctypes`
+module.
+
+If you distribute a CPython interpreter without optional modules,
+it's best practice to advise users, who generally expect that
+standard library modules are available.
+
+Dependencies to build optional modules are:
+
+.. list-table::
+ :header-rows: 1
+ :align: left
+
+ * - Dependency
+ - Minimum version
+ - Python module
+ * - `libbz2 `_
+ -
+ - :mod:`bz2`
+ * - `libffi `_
+ - 3.3.0 recommended
+ - :mod:`ctypes`
+ * - `liblzma `_
+ -
+ - :mod:`lzma`
+ * - `libmpdec `_
+ - 2.5.0
+ - :mod:`decimal` [1]_
+ * - `libreadline `_ or
+ `libedit `_ [2]_
+ -
+ - :mod:`readline`
+ * - `libuuid `_
+ -
+ - ``_uuid`` [3]_
+ * - `ncurses `_ [4]_
+ -
+ - :mod:`curses`
+ * - `OpenSSL `_
+ - | 3.0.18 recommended
+ | (1.1.1 minimum)
+ - :mod:`ssl`, :mod:`hashlib` [5]_
+ * - `SQLite `_
+ - 3.15.2
+ - :mod:`sqlite3`
+ * - `Tcl/Tk `_
+ - 8.5.12
+ - :mod:`tkinter`, :ref:`IDLE `, :mod:`turtle`
+ * - `zlib `_
+ - 1.2.2.1
+ - :mod:`zlib`, :mod:`gzip`, :mod:`ensurepip`
+ * - `zstd `_
+ - 1.4.5
+ - :mod:`compression.zstd`
+
+.. [1] If *libmpdec* is not available, the :mod:`decimal` module will use
+ a pure-Python implementation.
+ See :option:`--with-system-libmpdec` for details.
+.. [2] See :option:`--with-readline` for choosing the backend for the
+ :mod:`readline` module.
+.. [3] The :mod:`uuid` module uses ``_uuid`` to generate "safe" UUIDs.
+ See the module documentation for details.
+.. [4] The :mod:`curses` module requires the ``libncurses`` or ``libncursesw``
+ library.
+ The :mod:`curses.panel` module additionally requires the ``libpanel`` or
+ ``libpanelw`` library.
+.. [5] If OpenSSL is not available, the :mod:`hashlib` module will use
+ bundled implementations of several hash functions.
+ See :option:`--with-builtin-hashlib-hashes` for *forcing* usage of OpenSSL.
+
+Note that the table does not include all optional modules; in particular,
+platform-specific modules like :mod:`winreg` are not listed here.
+
+.. seealso::
+
+ * The `devguide `_
+ includes a full list of dependencies required to build all modules and
+ instructions on how to install them on common platforms.
+ * :option:`--with-system-expat` allows building with an external
+ `libexpat `_ library.
+ * :ref:`configure-options-for-dependencies`
+
+.. versionchanged:: 3.1
+ Tcl/Tk version 8.3.1 is now required for :mod:`tkinter`.
+
+.. versionchanged:: 3.5
+ Tcl/Tk version 8.4 is now required for :mod:`tkinter`.
+
+.. versionchanged:: 3.7
+ OpenSSL 1.0.2 is now required for :mod:`hashlib` and :mod:`ssl`.
+
+.. versionchanged:: 3.10
+ OpenSSL 1.1.1 is now required for :mod:`hashlib` and :mod:`ssl`.
+ SQLite 3.7.15 is now required for :mod:`sqlite3`.
+
+.. versionchanged:: 3.11
+ Tcl/Tk version 8.5.12 is now required for :mod:`tkinter`.
+
+.. versionchanged:: 3.13
+ SQLite 3.15.2 is now required for :mod:`sqlite3`.
+
+
Generated files
===============
@@ -127,8 +183,19 @@ The container is optional, the following command can be run locally::
autoreconf -ivf -Werror
-The generated files can change depending on the exact ``autoconf-archive``,
-``aclocal`` and ``pkg-config`` versions.
+The generated files can change depending on the exact versions of the
+tools used.
+The container that CPython uses has
+`Autoconf `_ 2.72,
+``aclocal`` from `Automake `_ 1.16.5,
+and `pkg-config `_ 1.8.1.
+
+.. versionchanged:: 3.13
+ Autoconf 2.71 and aclocal 1.16.5 and are now used to regenerate
+ :file:`configure`.
+
+.. versionchanged:: 3.14
+ Autoconf 2.72 is now used to regenerate :file:`configure`.
.. _configure-options:
@@ -409,6 +476,8 @@ Linker options
Name for machine-dependent library files.
+.. _configure-options-for-dependencies:
+
Options for third-party dependencies
------------------------------------
@@ -431,12 +500,6 @@ Options for third-party dependencies
C compiler and linker flags for ``gdbm``.
-.. option:: LIBB2_CFLAGS
-.. option:: LIBB2_LIBS
-
- C compiler and linker flags for ``libb2`` (:ref:`BLAKE2 `),
- used by :mod:`hashlib` module, overriding ``pkg-config``.
-
.. option:: LIBEDIT_CFLAGS
.. option:: LIBEDIT_LIBS
@@ -902,6 +965,13 @@ Libraries options
.. versionchanged:: 3.13
Default to using the installed ``mpdecimal`` library.
+ .. versionchanged:: 3.15
+
+ A bundled copy of the library will no longer be selected
+ implicitly if an installed ``mpdecimal`` library is not found.
+ In Python 3.15 only, it can still be selected explicitly using
+ ``--with-system-libmpdec=no`` or ``--without-system-libmpdec``.
+
.. deprecated-removed:: 3.13 3.16
A copy of the ``mpdecimal`` library sources will no longer be distributed
with Python 3.16.
diff --git a/Doc/using/unix.rst b/Doc/using/unix.rst
index 9ec4e341932..a9950ef7525 100644
--- a/Doc/using/unix.rst
+++ b/Doc/using/unix.rst
@@ -84,11 +84,17 @@ On FreeBSD and OpenBSD
Building Python
===============
+.. seealso::
+
+ If you want to contribute to CPython, refer to the
+ `devguide `_,
+ which includes build instructions and other tips on setting up environment.
+
If you want to compile CPython yourself, first thing you should do is get the
`source `_. You can download either the
-latest release's source or just grab a fresh `clone
-`_. (If you want
-to contribute patches, you will need a clone.)
+latest release's source or grab a fresh `clone
+`_.
+You will also need to install the :ref:`build requirements `.
The build process consists of the usual commands::
diff --git a/Doc/using/windows.rst b/Doc/using/windows.rst
index 0b98cfb8d27..ee182519199 100644
--- a/Doc/using/windows.rst
+++ b/Doc/using/windows.rst
@@ -4,6 +4,8 @@
.. _Microsoft Store app: https://apps.microsoft.com/detail/9NQ7512CXL7T
+.. _legacy launcher: https://www.python.org/ftp/python/3.14.0/win32/launcher.msi
+
.. _using-on-windows:
*************************
@@ -457,6 +459,25 @@ customization.
- Specify the default format used by the ``py list`` command.
By default, ``table``.
+ * - ``install_dir``
+ - (none)
+ - Specify the root directory that runtimes will be installed into.
+ If you change this setting, previously installed runtimes will not be
+ usable unless you move them to the new location.
+
+ * - ``global_dir``
+ - (none)
+ - Specify the directory where global commands (such as ``python3.14.exe``)
+ are stored.
+ This directory should be added to your :envvar:`PATH` to make the
+ commands available from your terminal.
+
+ * - ``download_dir``
+ - (none)
+ - Specify the directory where downloaded files are stored.
+ This directory is a temporary cache, and can be cleaned up from time to
+ time.
+
Dotted names should be nested inside JSON objects, for example, ``list.format``
would be specified as ``{"list": {"format": "table"}}``.
@@ -524,12 +545,9 @@ configuration option.
The behaviour of shebangs in the Python install manager is subtly different
from the previous ``py.exe`` launcher, and the old configuration options no
longer apply. If you are specifically reliant on the old behaviour or
- configuration, we recommend keeping the legacy launcher. It may be
- `downloaded independently `_
- and installed on its own. The legacy launcher's ``py`` command will override
- PyManager's one, and you will need to use ``pymanager`` commands for
- installing and uninstalling.
-
+ configuration, we recommend installing the `legacy launcher`_. The legacy
+ launcher's ``py`` command will override PyManager's one by default, and you
+ will need to use ``pymanager`` commands for installing and uninstalling.
.. _Add-AppxPackage: https://learn.microsoft.com/powershell/module/appx/add-appxpackage
@@ -840,6 +858,17 @@ default).
These scripts are separated for each runtime, and so you may need to
add multiple paths.
+ * - Typing ``script-name.py`` in the terminal opens in a new window.
+ - This is a known limitation of the operating system. Either specify ``py``
+ before the script name, create a batch file containing ``@py "%~dpn0.py" %*``
+ with the same name as the script, or install the `legacy launcher`_
+ and select it as the association for scripts.
+
+ * - Drag-dropping files onto a script doesn't work
+ - This is a known limitation of the operating system. It is supported with
+ the `legacy launcher`_, or with the Python install manager when installed
+ from the MSI.
+
.. _windows-embeddable:
diff --git a/Doc/whatsnew/2.5.rst b/Doc/whatsnew/2.5.rst
index 3430ac8668e..e195d9d462d 100644
--- a/Doc/whatsnew/2.5.rst
+++ b/Doc/whatsnew/2.5.rst
@@ -2169,9 +2169,9 @@ Changes to Python's build process and to the C API include:
* Two new macros can be used to indicate C functions that are local to the
current file so that a faster calling convention can be used.
- ``Py_LOCAL(type)`` declares the function as returning a value of the
+ :c:macro:`Py_LOCAL` declares the function as returning a value of the
specified *type* and uses a fast-calling qualifier.
- ``Py_LOCAL_INLINE(type)`` does the same thing and also requests the
+ :c:macro:`Py_LOCAL_INLINE` does the same thing and also requests the
function be inlined. If macro :c:macro:`!PY_LOCAL_AGGRESSIVE` is defined before
:file:`python.h` is included, a set of more aggressive optimizations are enabled
for the module; you should benchmark the results to find out if these
diff --git a/Doc/whatsnew/2.7.rst b/Doc/whatsnew/2.7.rst
index 09feb185b82..7296296d144 100644
--- a/Doc/whatsnew/2.7.rst
+++ b/Doc/whatsnew/2.7.rst
@@ -2181,14 +2181,14 @@ Changes to Python's build process and to the C API include:
discussed in :issue:`5753`, and fixed by Antoine Pitrou.
* New macros: the Python header files now define the following macros:
- :c:macro:`!Py_ISALNUM`,
- :c:macro:`!Py_ISALPHA`,
- :c:macro:`!Py_ISDIGIT`,
- :c:macro:`!Py_ISLOWER`,
- :c:macro:`!Py_ISSPACE`,
- :c:macro:`!Py_ISUPPER`,
- :c:macro:`!Py_ISXDIGIT`,
- :c:macro:`!Py_TOLOWER`, and :c:macro:`!Py_TOUPPER`.
+ :c:macro:`Py_ISALNUM`,
+ :c:macro:`Py_ISALPHA`,
+ :c:macro:`Py_ISDIGIT`,
+ :c:macro:`Py_ISLOWER`,
+ :c:macro:`Py_ISSPACE`,
+ :c:macro:`Py_ISUPPER`,
+ :c:macro:`Py_ISXDIGIT`,
+ :c:macro:`Py_TOLOWER`, and :c:macro:`Py_TOUPPER`.
All of these functions are analogous to the C
standard macros for classifying characters, but ignore the current
locale setting, because in
@@ -2196,8 +2196,6 @@ Changes to Python's build process and to the C API include:
locale-independent way. (Added by Eric Smith;
:issue:`5793`.)
- .. XXX these macros don't seem to be described in the c-api docs.
-
* Removed function: :c:func:`!PyEval_CallObject` is now only available
as a macro. A function version was being kept around to preserve
ABI linking compatibility, but that was in 1997; it can certainly be
diff --git a/Doc/whatsnew/3.14.rst b/Doc/whatsnew/3.14.rst
index 1a2fbda0c4c..9459b73bcb5 100644
--- a/Doc/whatsnew/3.14.rst
+++ b/Doc/whatsnew/3.14.rst
@@ -3045,7 +3045,7 @@ Deprecated C APIs
-----------------
* The :c:macro:`!Py_HUGE_VAL` macro is now :term:`soft deprecated`.
- Use :c:macro:`!Py_INFINITY` instead.
+ Use :c:macro:`!INFINITY` instead.
(Contributed by Sergey B Kirpichev in :gh:`120026`.)
* The :c:macro:`!Py_IS_NAN`, :c:macro:`!Py_IS_INFINITY`,
diff --git a/Doc/whatsnew/3.15.rst b/Doc/whatsnew/3.15.rst
index 9eb09f535cd..f70c2e5d36b 100644
--- a/Doc/whatsnew/3.15.rst
+++ b/Doc/whatsnew/3.15.rst
@@ -307,6 +307,97 @@ Other language changes
not only integers or floats, although this does not improve precision.
(Contributed by Serhiy Storchaka in :gh:`67795`.)
+.. _whatsnew315-bytearray-take-bytes:
+
+* Added :meth:`bytearray.take_bytes(n=None, /) ` to take
+ bytes out of a :class:`bytearray` without copying. This enables optimizing code
+ which must return :class:`bytes` after working with a mutable buffer of bytes
+ such as data buffering, network protocol parsing, encoding, decoding,
+ and compression. Common code patterns which can be optimized with
+ :func:`~bytearray.take_bytes` are listed below.
+
+ .. list-table:: Suggested optimizing refactors
+ :header-rows: 1
+
+ * - Description
+ - Old
+ - New
+
+ * - Return :class:`bytes` after working with :class:`bytearray`
+ - .. code:: python
+
+ def read() -> bytes:
+ buffer = bytearray(1024)
+ ...
+ return bytes(buffer)
+
+ - .. code:: python
+
+ def read() -> bytes:
+ buffer = bytearray(1024)
+ ...
+ return buffer.take_bytes()
+
+ * - Empty a buffer getting the bytes
+ - .. code:: python
+
+ buffer = bytearray(1024)
+ ...
+ data = bytes(buffer)
+ buffer.clear()
+
+ - .. code:: python
+
+ buffer = bytearray(1024)
+ ...
+ data = buffer.take_bytes()
+
+ * - Split a buffer at a specific separator
+ - .. code:: python
+
+ buffer = bytearray(b'abc\ndef')
+ n = buffer.find(b'\n')
+ data = bytes(buffer[:n + 1])
+ del buffer[:n + 1]
+ assert data == b'abc'
+ assert buffer == bytearray(b'def')
+
+ - .. code:: python
+
+ buffer = bytearray(b'abc\ndef')
+ n = buffer.find(b'\n')
+ data = buffer.take_bytes(n + 1)
+
+ * - Split a buffer at a specific separator; discard after the separator
+ - .. code:: python
+
+ buffer = bytearray(b'abc\ndef')
+ n = buffer.find(b'\n')
+ data = bytes(buffer[:n])
+ buffer.clear()
+ assert data == b'abc'
+ assert len(buffer) == 0
+
+ - .. code:: python
+
+ buffer = bytearray(b'abc\ndef')
+ n = buffer.find(b'\n')
+ buffer.resize(n)
+ data = buffer.take_bytes()
+
+ (Contributed by Cody Maloney in :gh:`139871`.)
+
+* Many functions related to compiling or parsing Python code, such as
+ :func:`compile`, :func:`ast.parse`, :func:`symtable.symtable`,
+ and :func:`importlib.abc.InspectLoader.source_to_code`, now allow the module
+ name to be passed. It is needed to unambiguously :ref:`filter `
+ syntax warnings by module name.
+ (Contributed by Serhiy Storchaka in :gh:`135801`.)
+
+* Allowed defining the *__dict__* and *__weakref__* :ref:`__slots__ `
+ for any class.
+ (Contributed by Serhiy Storchaka in :gh:`41779`.)
+
New modules
===========
@@ -325,6 +416,10 @@ Improved modules
argparse
--------
+* The :class:`~argparse.BooleanOptionalAction` action supports now single-dash
+ long options and alternate prefix characters.
+ (Contributed by Serhiy Storchaka in :gh:`138525`.)
+
* Changed the *suggest_on_error* parameter of :class:`argparse.ArgumentParser` to
default to ``True``. This enables suggestions for mistyped arguments by default.
(Contributed by Jakob Schluse in :gh:`140450`.)
@@ -368,6 +463,24 @@ collections.abc
previously emitted if it was merely imported or accessed from the
:mod:`!collections.abc` module.
+
+concurrent.futures
+------------------
+
+* Improved error reporting when a child process in a
+ :class:`concurrent.futures.ProcessPoolExecutor` terminates abruptly.
+ The resulting traceback will now tell you the PID and exit code of the
+ terminated process.
+ (Contributed by Jonathan Berg in :gh:`139486`.)
+
+
+dataclasses
+-----------
+
+* Annotations for generated ``__init__`` methods no longer include internal
+ type names.
+
+
dbm
---
@@ -393,6 +506,14 @@ difflib
(Contributed by Jiahao Li in :gh:`134580`.)
+functools
+---------
+
+* :func:`~functools.singledispatchmethod` now supports non-:term:`descriptor`
+ callables.
+ (Contributed by Serhiy Storchaka in :gh:`140873`.)
+
+
hashlib
-------
@@ -421,6 +542,14 @@ http.cookies
(Contributed by Nick Burns and Senthil Kumaran in :gh:`92936`.)
+inspect
+-------
+
+* Add parameters *inherit_class_doc* and *fallback_to_class_doc*
+ for :func:`~inspect.getdoc`.
+ (Contributed by Serhiy Storchaka in :gh:`132686`.)
+
+
locale
------
@@ -440,6 +569,17 @@ math
(Contributed by Bénédikt Tran in :gh:`135853`.)
+mimetypes
+---------
+
+* Add ``application/node`` MIME type for ``.cjs`` extension. (Contributed by John Franey in :gh:`140937`.)
+* Add ``application/toml``. (Contributed by Gil Forcada in :gh:`139959`.)
+* Rename ``application/x-texinfo`` to ``application/texinfo``.
+ (Contributed by Charlie Lin in :gh:`140165`.)
+* Changed the MIME type for ``.ai`` files to ``application/pdf``.
+ (Contributed by Stan Ulbrych in :gh:`141239`.)
+
+
mmap
----
@@ -602,6 +742,19 @@ timeit
:ref:`environment variables `.
(Contributed by Yi Hong in :gh:`139374`.)
+tkinter
+-------
+
+* The :meth:`!tkinter.Text.search` method now supports two additional
+ arguments: *nolinestop* which allows the search to
+ continue across line boundaries;
+ and *strictlimits* which restricts the search to within the specified range.
+ (Contributed by Rihaan Meher in :gh:`130848`)
+
+* A new method :meth:`!tkinter.Text.search_all` has been introduced.
+ This method allows for searching for all matches of a pattern
+ using Tcl's ``-all`` and ``-overlap`` options.
+ (Contributed by Rihaan Meher in :gh:`130848`)
types
------
@@ -612,6 +765,17 @@ types
as described in :pep:`667`.
+unicodedata
+-----------
+
+* The Unicode database has been updated to Unicode 17.0.0.
+
+* Add :func:`unicodedata.isxidstart` and :func:`unicodedata.isxidcontinue`
+ functions to check whether a character can start or continue a
+ `Unicode Standard Annex #31 `_ identifier.
+ (Contributed by Stan Ulbrych in :gh:`129117`.)
+
+
unittest
--------
@@ -620,6 +784,17 @@ unittest
(Contributed by Garry Cairns in :gh:`134567`.)
+venv
+----
+
+* On POSIX platforms, platlib directories will be created if needed when
+ creating virtual environments, instead of using ``lib64 -> lib`` symlink.
+ This means purelib and platlib of virtual environments no longer share the
+ same ``lib`` directory on platforms where :data:`sys.platlibdir` is not
+ equal to ``lib``.
+ (Contributed by Rui Xi in :gh:`133951`.)
+
+
warnings
--------
@@ -632,17 +807,6 @@ warnings
(Contributed by Serhiy Storchaka in :gh:`135801`.)
-venv
-----
-
-* On POSIX platforms, platlib directories will be created if needed when
- creating virtual environments, instead of using ``lib64 -> lib`` symlink.
- This means purelib and platlib of virtual environments no longer share the
- same ``lib`` directory on platforms where :data:`sys.platlibdir` is not
- equal to ``lib``.
- (Contributed by Rui Xi in :gh:`133951`.)
-
-
xml.parsers.expat
-----------------
@@ -723,14 +887,6 @@ importlib.resources
(Contributed by Semyon Moroz in :gh:`138044`)
-mimetypes
----------
-
-* Add ``application/toml``. (Contributed by Gil Forcada in :gh:`139959`.)
-* Rename ``application/x-texinfo`` to ``application/texinfo``.
- (Contributed by Charlie Lin in :gh:`140165`)
-
-
pathlib
-------
@@ -780,7 +936,7 @@ typing
(Contributed by Bénédikt Tran in :gh:`133817`.)
* Using ``TD = TypedDict("TD")`` or ``TD = TypedDict("TD", None)`` to
- construct a :class:`~typing.TypedDict` type with zero field is no
+ construct a :class:`~typing.TypedDict` type with zero fields is no
longer supported. Use ``class TD(TypedDict): pass``
or ``TD = TypedDict("TD", {})`` instead.
(Contributed by Bénédikt Tran in :gh:`133823`.)
@@ -813,17 +969,6 @@ typing
(Contributed by Nikita Sobolev in :gh:`133601`.)
-unicodedata
------------
-
-* The Unicode database has been updated to Unicode 17.0.0.
-
-* Add :func:`unicodedata.isxidstart` and :func:`unicodedata.isxidcontinue`
- functions to check whether a character can start or continue a
- `Unicode Standard Annex #31 `_ identifier.
- (Contributed by Stan Ulbrych in :gh:`129117`.)
-
-
wave
----
@@ -850,7 +995,7 @@ New deprecations
* CLI:
* Deprecate :option:`-b` and :option:`!-bb` command-line options
- and schedule them to become no-op in Python 3.17.
+ and schedule them to become no-ops in Python 3.17.
These were primarily helpers for the Python 2 -> 3 transition.
Starting with Python 3.17, no :exc:`BytesWarning` will be raised
for these cases; use a type checker instead.
@@ -861,8 +1006,8 @@ New deprecations
* In hash function constructors such as :func:`~hashlib.new` or the
direct hash-named constructors such as :func:`~hashlib.md5` and
- :func:`~hashlib.sha256`, their optional initial data parameter could
- also be passed a keyword argument named ``data=`` or ``string=`` in
+ :func:`~hashlib.sha256`, the optional initial data parameter could
+ also be passed as a keyword argument named ``data=`` or ``string=`` in
various :mod:`hashlib` implementations.
Support for the ``string`` keyword argument name is now deprecated and
@@ -950,9 +1095,23 @@ New features
(Contributed by Victor Stinner in :gh:`129813`.)
+* Add a new :c:func:`PyImport_CreateModuleFromInitfunc` C-API for creating
+ a module from a *spec* and *initfunc*.
+ (Contributed by Itamar Oren in :gh:`116146`.)
+
* Add :c:func:`PyTuple_FromArray` to create a :class:`tuple` from an array.
(Contributed by Victor Stinner in :gh:`111489`.)
+* Add :c:func:`PyUnstable_Object_Dump` to dump an object to ``stderr``.
+ It should only be used for debugging.
+ (Contributed by Victor Stinner in :gh:`141070`.)
+
+* Add :c:func:`PyUnstable_ThreadState_SetStackProtection` and
+ :c:func:`PyUnstable_ThreadState_ResetStackProtection` functions to set
+ the stack protection base address and stack protection size of a Python
+ thread state.
+ (Contributed by Victor Stinner in :gh:`139653`.)
+
Changed C APIs
--------------
@@ -965,31 +1124,11 @@ Changed C APIs
Porting to Python 3.15
----------------------
-* :class:`sqlite3.Connection` APIs has been cleaned up.
-
- * All parameters of :func:`sqlite3.connect` except *database* are now keyword-only.
- * The first three parameters of methods :meth:`~sqlite3.Connection.create_function`
- and :meth:`~sqlite3.Connection.create_aggregate` are now positional-only.
- * The first parameter of methods :meth:`~sqlite3.Connection.set_authorizer`,
- :meth:`~sqlite3.Connection.set_progress_handler` and
- :meth:`~sqlite3.Connection.set_trace_callback` is now positional-only.
-
- (Contributed by Serhiy Storchaka in :gh:`133595`.)
-
* Private functions promoted to public C APIs:
The |pythoncapi_compat_project| can be used to get most of these new
functions on Python 3.14 and older.
-* :data:`resource.RLIM_INFINITY` is now always positive.
- Passing a negative integer value that corresponded to its old value
- (such as ``-1`` or ``-3``, depending on platform) to
- :func:`resource.setrlimit` and :func:`resource.prlimit` is now deprecated.
- (Contributed by Serhiy Storchaka in :gh:`137044`.)
-
-* :meth:`~mmap.mmap.resize` has been removed on platforms that don't support the
- underlying syscall, instead of raising a :exc:`SystemError`.
-
Removed C APIs
--------------
@@ -1091,6 +1230,14 @@ Deprecated C APIs
since 3.15 and will be removed in 3.17.
(Contributed by Nikita Sobolev in :gh:`136355`.)
+* :c:macro:`!Py_INFINITY` macro is :term:`soft deprecated`,
+ use the C11 standard ```` :c:macro:`!INFINITY` instead.
+ (Contributed by Sergey B Kirpichev in :gh:`141004`.)
+
+* :c:macro:`!Py_MATH_El` and :c:macro:`!Py_MATH_PIl` are deprecated
+ since 3.15 and will be removed in 3.20.
+ (Contributed by Sergey B Kirpichev in :gh:`141004`.)
+
.. Add C API deprecations above alphabetically, not here at the end.
@@ -1109,3 +1256,36 @@ Porting to Python 3.15
This section lists previously described changes and other bugfixes
that may require changes to your code.
+
+* :class:`sqlite3.Connection` APIs have been cleaned up.
+
+ * All parameters of :func:`sqlite3.connect` except *database* are now keyword-only.
+ * The first three parameters of methods :meth:`~sqlite3.Connection.create_function`
+ and :meth:`~sqlite3.Connection.create_aggregate` are now positional-only.
+ * The first parameter of methods :meth:`~sqlite3.Connection.set_authorizer`,
+ :meth:`~sqlite3.Connection.set_progress_handler` and
+ :meth:`~sqlite3.Connection.set_trace_callback` is now positional-only.
+
+ (Contributed by Serhiy Storchaka in :gh:`133595`.)
+
+* :data:`resource.RLIM_INFINITY` is now always positive.
+ Passing a negative integer value that corresponded to its old value
+ (such as ``-1`` or ``-3``, depending on platform) to
+ :func:`resource.setrlimit` and :func:`resource.prlimit` is now deprecated.
+ (Contributed by Serhiy Storchaka in :gh:`137044`.)
+
+* :meth:`~mmap.mmap.resize` has been removed on platforms that don't support the
+ underlying syscall, instead of raising a :exc:`SystemError`.
+
+* A resource warning is now emitted for an unclosed
+ :func:`xml.etree.ElementTree.iterparse` iterator if it opened a file.
+ Use its :meth:`!close` method or the :func:`contextlib.closing` context
+ manager to close it.
+ (Contributed by Osama Abdelkader and Serhiy Storchaka in :gh:`140601`.)
+
+* If a short option and a single-dash long option are passed to
+ :meth:`argparse.ArgumentParser.add_argument`, *dest* is now inferred from
+ the single-dash long option. For example, in ``add_argument('-f', '-foo')``,
+ *dest* is now ``'foo'`` instead of ``'f'``.
+ Pass an explicit *dest* argument to preserve the old behavior.
+ (Contributed by Serhiy Storchaka in :gh:`138697`.)
diff --git a/Include/cpython/bytearrayobject.h b/Include/cpython/bytearrayobject.h
index 4dddef713ce..1edd0820742 100644
--- a/Include/cpython/bytearrayobject.h
+++ b/Include/cpython/bytearrayobject.h
@@ -5,25 +5,25 @@
/* Object layout */
typedef struct {
PyObject_VAR_HEAD
- Py_ssize_t ob_alloc; /* How many bytes allocated in ob_bytes */
+ /* How many bytes allocated in ob_bytes
+
+ In the current implementation this is equivalent to Py_SIZE(ob_bytes_object).
+ The value is always loaded and stored atomically for thread safety.
+ There are API compatibilty concerns with removing so keeping for now. */
+ Py_ssize_t ob_alloc;
char *ob_bytes; /* Physical backing buffer */
char *ob_start; /* Logical start inside ob_bytes */
Py_ssize_t ob_exports; /* How many buffer exports */
+ PyObject *ob_bytes_object; /* PyBytes for zero-copy bytes conversion */
} PyByteArrayObject;
-PyAPI_DATA(char) _PyByteArray_empty_string[];
-
/* Macros and static inline functions, trading safety for speed */
#define _PyByteArray_CAST(op) \
(assert(PyByteArray_Check(op)), _Py_CAST(PyByteArrayObject*, op))
static inline char* PyByteArray_AS_STRING(PyObject *op)
{
- PyByteArrayObject *self = _PyByteArray_CAST(op);
- if (Py_SIZE(self)) {
- return self->ob_start;
- }
- return _PyByteArray_empty_string;
+ return _PyByteArray_CAST(op)->ob_start;
}
#define PyByteArray_AS_STRING(self) PyByteArray_AS_STRING(_PyObject_CAST(self))
diff --git a/Include/cpython/dictobject.h b/Include/cpython/dictobject.h
index df9ec7050fc..5f2f7b6d4f5 100644
--- a/Include/cpython/dictobject.h
+++ b/Include/cpython/dictobject.h
@@ -39,16 +39,6 @@ Py_DEPRECATED(3.14) PyAPI_FUNC(PyObject *) _PyDict_GetItemStringWithError(PyObje
PyAPI_FUNC(PyObject *) PyDict_SetDefault(
PyObject *mp, PyObject *key, PyObject *defaultobj);
-// Inserts `key` with a value `default_value`, if `key` is not already present
-// in the dictionary. If `result` is not NULL, then the value associated
-// with `key` is returned in `*result` (either the existing value, or the now
-// inserted `default_value`).
-// Returns:
-// -1 on error
-// 0 if `key` was not present and `default_value` was inserted
-// 1 if `key` was present and `default_value` was not inserted
-PyAPI_FUNC(int) PyDict_SetDefaultRef(PyObject *mp, PyObject *key, PyObject *default_value, PyObject **result);
-
/* Get the number of items of a dictionary. */
static inline Py_ssize_t PyDict_GET_SIZE(PyObject *op) {
PyDictObject *mp;
diff --git a/Include/cpython/import.h b/Include/cpython/import.h
index 0ce0b1ee6cc..149a20af8b9 100644
--- a/Include/cpython/import.h
+++ b/Include/cpython/import.h
@@ -10,6 +10,13 @@ struct _inittab {
PyAPI_DATA(struct _inittab *) PyImport_Inittab;
PyAPI_FUNC(int) PyImport_ExtendInittab(struct _inittab *newtab);
+// Custom importers may use this API to initialize statically linked
+// extension modules directly from a spec and init function,
+// without needing to go through inittab
+PyAPI_FUNC(PyObject *) PyImport_CreateModuleFromInitfunc(
+ PyObject *spec,
+ PyObject *(*initfunc)(void));
+
struct _frozen {
const char *name; /* ASCII encoded string */
const unsigned char *code;
diff --git a/Include/cpython/object.h b/Include/cpython/object.h
index d64298232e7..130a105de42 100644
--- a/Include/cpython/object.h
+++ b/Include/cpython/object.h
@@ -295,7 +295,10 @@ PyAPI_FUNC(PyObject *) PyType_GetDict(PyTypeObject *);
PyAPI_FUNC(int) PyObject_Print(PyObject *, FILE *, int);
PyAPI_FUNC(void) _Py_BreakPoint(void);
-PyAPI_FUNC(void) _PyObject_Dump(PyObject *);
+PyAPI_FUNC(void) PyUnstable_Object_Dump(PyObject *);
+
+// Alias for backward compatibility
+#define _PyObject_Dump PyUnstable_Object_Dump
PyAPI_FUNC(PyObject*) _PyObject_GetAttrId(PyObject *, _Py_Identifier *);
@@ -387,10 +390,11 @@ PyAPI_FUNC(PyObject *) _PyObject_FunctionStr(PyObject *);
process with a message on stderr if the given condition fails to hold,
but compile away to nothing if NDEBUG is defined.
- However, before aborting, Python will also try to call _PyObject_Dump() on
- the given object. This may be of use when investigating bugs in which a
- particular object is corrupt (e.g. buggy a tp_visit method in an extension
- module breaking the garbage collector), to help locate the broken objects.
+ However, before aborting, Python will also try to call
+ PyUnstable_Object_Dump() on the given object. This may be of use when
+ investigating bugs in which a particular object is corrupt (e.g. buggy a
+ tp_visit method in an extension module breaking the garbage collector), to
+ help locate the broken objects.
The WITH_MSG variant allows you to supply an additional message that Python
will attempt to print to stderr, after the object dump. */
diff --git a/Include/cpython/pyatomic_std.h b/Include/cpython/pyatomic_std.h
index 69a8b9e615e..7176f667a40 100644
--- a/Include/cpython/pyatomic_std.h
+++ b/Include/cpython/pyatomic_std.h
@@ -948,14 +948,6 @@ _Py_atomic_store_ushort_relaxed(unsigned short *obj, unsigned short value)
memory_order_relaxed);
}
-static inline void
-_Py_atomic_store_uint_release(unsigned int *obj, unsigned int value)
-{
- _Py_USING_STD;
- atomic_store_explicit((_Atomic(unsigned int)*)obj, value,
- memory_order_relaxed);
-}
-
static inline void
_Py_atomic_store_long_relaxed(long *obj, long value)
{
@@ -1031,6 +1023,14 @@ _Py_atomic_store_int_release(int *obj, int value)
memory_order_release);
}
+static inline void
+_Py_atomic_store_uint_release(unsigned int *obj, unsigned int value)
+{
+ _Py_USING_STD;
+ atomic_store_explicit((_Atomic(unsigned int)*)obj, value,
+ memory_order_release);
+}
+
static inline void
_Py_atomic_store_ssize_release(Py_ssize_t *obj, Py_ssize_t value)
{
diff --git a/Include/cpython/pyhash.h b/Include/cpython/pyhash.h
index a33ba10b8d3..dac223368db 100644
--- a/Include/cpython/pyhash.h
+++ b/Include/cpython/pyhash.h
@@ -7,7 +7,7 @@
/* Parameters used for the numeric hash implementation. See notes for
_Py_HashDouble in Python/pyhash.c. Numeric hashes are based on
- reduction modulo the prime 2**_PyHASH_BITS - 1. */
+ reduction modulo the prime 2**PyHASH_BITS - 1. */
#if SIZEOF_VOID_P >= 8
# define PyHASH_BITS 61
@@ -15,7 +15,7 @@
# define PyHASH_BITS 31
#endif
-#define PyHASH_MODULUS (((size_t)1 << _PyHASH_BITS) - 1)
+#define PyHASH_MODULUS (((size_t)1 << PyHASH_BITS) - 1)
#define PyHASH_INF 314159
#define PyHASH_IMAG PyHASH_MULTIPLIER
diff --git a/Include/cpython/pystate.h b/Include/cpython/pystate.h
index ac8798ff612..1e1e46ea4c0 100644
--- a/Include/cpython/pystate.h
+++ b/Include/cpython/pystate.h
@@ -113,6 +113,9 @@ struct _ts {
/* Currently holds the GIL. Must be its own field to avoid data races */
int holds_gil;
+ /* Currently requesting the GIL */
+ int gil_requested;
+
int _whence;
/* Thread state (_Py_THREAD_ATTACHED, _Py_THREAD_DETACHED, _Py_THREAD_SUSPENDED).
@@ -217,6 +220,15 @@ struct _ts {
*/
PyObject *threading_local_sentinel;
_PyRemoteDebuggerSupport remote_debugger_support;
+
+#ifdef Py_STATS
+ // Pointer to PyStats structure, NULL if recording is off. For the
+ // free-threaded build, the structure is per-thread (stored as a pointer
+ // in _PyThreadStateImpl). For the default build, the structure is stored
+ // in the PyInterpreterState structure (threads do not have their own
+ // structure and all share the same per-interpreter structure).
+ PyStats *pystats;
+#endif
};
/* other API */
@@ -239,6 +251,21 @@ PyAPI_FUNC(void) PyThreadState_EnterTracing(PyThreadState *tstate);
// function is set, otherwise disable them.
PyAPI_FUNC(void) PyThreadState_LeaveTracing(PyThreadState *tstate);
+#ifdef Py_STATS
+#if defined(HAVE_THREAD_LOCAL) && !defined(Py_BUILD_CORE_MODULE)
+extern _Py_thread_local PyThreadState *_Py_tss_tstate;
+
+static inline PyStats*
+_PyThreadState_GetStatsFast(void)
+{
+ if (_Py_tss_tstate == NULL) {
+ return NULL; // no attached thread state
+ }
+ return _Py_tss_tstate->pystats;
+}
+#endif
+#endif // Py_STATS
+
/* PyGILState */
/* Helper/diagnostic function - return 1 if the current thread
@@ -252,6 +279,18 @@ PyAPI_FUNC(int) PyGILState_Check(void);
*/
PyAPI_FUNC(PyObject*) _PyThread_CurrentFrames(void);
+// Set the stack protection start address and stack protection size
+// of a Python thread state
+PyAPI_FUNC(int) PyUnstable_ThreadState_SetStackProtection(
+ PyThreadState *tstate,
+ void *stack_start_addr, // Stack start address
+ size_t stack_size); // Stack size (in bytes)
+
+// Reset the stack protection start address and stack protection size
+// of a Python thread state
+PyAPI_FUNC(void) PyUnstable_ThreadState_ResetStackProtection(
+ PyThreadState *tstate);
+
/* Routines for advanced debuggers, requested by David Beazley.
Don't use unless you know what you are doing! */
PyAPI_FUNC(PyInterpreterState *) PyInterpreterState_Main(void);
diff --git a/Include/cpython/pystats.h b/Include/cpython/pystats.h
index cf830b6066f..1c94603c08b 100644
--- a/Include/cpython/pystats.h
+++ b/Include/cpython/pystats.h
@@ -4,7 +4,7 @@
//
// - _Py_INCREF_STAT_INC() and _Py_DECREF_STAT_INC() used by Py_INCREF()
// and Py_DECREF().
-// - _Py_stats variable
+// - _PyStats_GET()
//
// Functions of the sys module:
//
@@ -14,7 +14,7 @@
// - sys._stats_dump()
//
// Python must be built with ./configure --enable-pystats to define the
-// Py_STATS macro.
+// _PyStats_GET() macro.
//
// Define _PY_INTERPRETER macro to increment interpreter_increfs and
// interpreter_decrefs. Otherwise, increment increfs and decrefs.
@@ -109,6 +109,18 @@ typedef struct _gc_stats {
uint64_t objects_not_transitively_reachable;
} GCStats;
+#ifdef Py_GIL_DISABLED
+// stats specific to free-threaded build
+typedef struct _ft_stats {
+ // number of times interpreter had to spin or park when trying to acquire a mutex
+ uint64_t mutex_sleeps;
+ // number of times that the QSBR mechanism polled (compute read sequence value)
+ uint64_t qsbr_polls;
+ // number of times stop-the-world mechanism was used
+ uint64_t world_stops;
+} FTStats;
+#endif
+
typedef struct _uop_stats {
uint64_t execution_count;
uint64_t miss;
@@ -138,6 +150,8 @@ typedef struct _optimization_stats {
uint64_t optimized_trace_length_hist[_Py_UOP_HIST_SIZE];
uint64_t optimizer_attempts;
uint64_t optimizer_successes;
+ uint64_t optimizer_contradiction;
+ uint64_t optimizer_frame_overflow;
uint64_t optimizer_failure_reason_no_memory;
uint64_t remove_globals_builtins_changed;
uint64_t remove_globals_incorrect_keys;
@@ -173,22 +187,48 @@ typedef struct _stats {
CallStats call_stats;
ObjectStats object_stats;
OptimizationStats optimization_stats;
+#ifdef Py_GIL_DISABLED
+ FTStats ft_stats;
+#endif
RareEventStats rare_event_stats;
- GCStats *gc_stats;
+ GCStats gc_stats[3]; // must match NUM_GENERATIONS
} PyStats;
+// Export for most shared extensions
+PyAPI_FUNC(PyStats *) _PyStats_GetLocal(void);
-// Export for shared extensions like 'math'
-PyAPI_DATA(PyStats*) _Py_stats;
+#if defined(HAVE_THREAD_LOCAL) && !defined(Py_BUILD_CORE_MODULE)
+// use inline function version defined in cpython/pystate.h
+static inline PyStats *_PyThreadState_GetStatsFast(void);
+#define _PyStats_GET _PyThreadState_GetStatsFast
+#else
+#define _PyStats_GET _PyStats_GetLocal
+#endif
+
+#define _Py_STATS_EXPR(expr) \
+ do { \
+ PyStats *s = _PyStats_GET(); \
+ if (s != NULL) { \
+ s->expr; \
+ } \
+ } while (0)
+
+#define _Py_STATS_COND_EXPR(cond, expr) \
+ do { \
+ PyStats *s = _PyStats_GET(); \
+ if (s != NULL && (cond)) { \
+ s->expr; \
+ } \
+ } while (0)
#ifdef _PY_INTERPRETER
-# define _Py_INCREF_STAT_INC() do { if (_Py_stats) _Py_stats->object_stats.interpreter_increfs++; } while (0)
-# define _Py_DECREF_STAT_INC() do { if (_Py_stats) _Py_stats->object_stats.interpreter_decrefs++; } while (0)
-# define _Py_INCREF_IMMORTAL_STAT_INC() do { if (_Py_stats) _Py_stats->object_stats.interpreter_immortal_increfs++; } while (0)
-# define _Py_DECREF_IMMORTAL_STAT_INC() do { if (_Py_stats) _Py_stats->object_stats.interpreter_immortal_decrefs++; } while (0)
+# define _Py_INCREF_STAT_INC() _Py_STATS_EXPR(object_stats.interpreter_increfs++)
+# define _Py_DECREF_STAT_INC() _Py_STATS_EXPR(object_stats.interpreter_decrefs++)
+# define _Py_INCREF_IMMORTAL_STAT_INC() _Py_STATS_EXPR(object_stats.interpreter_immortal_increfs++)
+# define _Py_DECREF_IMMORTAL_STAT_INC() _Py_STATS_EXPR(object_stats.interpreter_immortal_decrefs++)
#else
-# define _Py_INCREF_STAT_INC() do { if (_Py_stats) _Py_stats->object_stats.increfs++; } while (0)
-# define _Py_DECREF_STAT_INC() do { if (_Py_stats) _Py_stats->object_stats.decrefs++; } while (0)
-# define _Py_INCREF_IMMORTAL_STAT_INC() do { if (_Py_stats) _Py_stats->object_stats.immortal_increfs++; } while (0)
-# define _Py_DECREF_IMMORTAL_STAT_INC() do { if (_Py_stats) _Py_stats->object_stats.immortal_decrefs++; } while (0)
+# define _Py_INCREF_STAT_INC() _Py_STATS_EXPR(object_stats.increfs++)
+# define _Py_DECREF_STAT_INC() _Py_STATS_EXPR(object_stats.decrefs++)
+# define _Py_INCREF_IMMORTAL_STAT_INC() _Py_STATS_EXPR(object_stats.immortal_increfs++)
+# define _Py_DECREF_IMMORTAL_STAT_INC() _Py_STATS_EXPR(object_stats.immortal_decrefs++)
#endif
diff --git a/Include/cpython/unicodeobject.h b/Include/cpython/unicodeobject.h
index 73e3bc44d6c..2853d24c34b 100644
--- a/Include/cpython/unicodeobject.h
+++ b/Include/cpython/unicodeobject.h
@@ -301,7 +301,6 @@ static inline Py_ssize_t PyUnicode_GET_LENGTH(PyObject *op) {
/* Returns the cached hash, or -1 if not cached yet. */
static inline Py_hash_t
PyUnstable_Unicode_GET_CACHED_HASH(PyObject *op) {
- assert(PyUnicode_Check(op));
#ifdef Py_GIL_DISABLED
return _Py_atomic_load_ssize_relaxed(&_PyASCIIObject_CAST(op)->hash);
#else
diff --git a/Include/datetime.h b/Include/datetime.h
index b78cc0e8e2e..ed36e6e48c8 100644
--- a/Include/datetime.h
+++ b/Include/datetime.h
@@ -1,8 +1,8 @@
/* datetime.h
*/
#ifndef Py_LIMITED_API
-#ifndef DATETIME_H
-#define DATETIME_H
+#ifndef Py_DATETIME_H
+#define Py_DATETIME_H
#ifdef __cplusplus
extern "C" {
#endif
@@ -263,5 +263,5 @@ static PyDateTime_CAPI *PyDateTimeAPI = NULL;
#ifdef __cplusplus
}
#endif
-#endif
+#endif /* !Py_DATETIME_H */
#endif /* !Py_LIMITED_API */
diff --git a/Include/dictobject.h b/Include/dictobject.h
index 1bbeec1ab69..0384e3131dc 100644
--- a/Include/dictobject.h
+++ b/Include/dictobject.h
@@ -68,6 +68,18 @@ PyAPI_FUNC(int) PyDict_GetItemRef(PyObject *mp, PyObject *key, PyObject **result
PyAPI_FUNC(int) PyDict_GetItemStringRef(PyObject *mp, const char *key, PyObject **result);
#endif
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x030F0000
+// Inserts `key` with a value `default_value`, if `key` is not already present
+// in the dictionary. If `result` is not NULL, then the value associated
+// with `key` is returned in `*result` (either the existing value, or the now
+// inserted `default_value`).
+// Returns:
+// -1 on error
+// 0 if `key` was not present and `default_value` was inserted
+// 1 if `key` was present and `default_value` was not inserted
+PyAPI_FUNC(int) PyDict_SetDefaultRef(PyObject *mp, PyObject *key, PyObject *default_value, PyObject **result);
+#endif
+
#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x030A0000
PyAPI_FUNC(PyObject *) PyObject_GenericGetDict(PyObject *, void *);
#endif
diff --git a/Include/exports.h b/Include/exports.h
index 0c646d5beb6..62feb09ed2b 100644
--- a/Include/exports.h
+++ b/Include/exports.h
@@ -9,6 +9,7 @@
inside the Python core, they are private to the core.
If in an extension module, it may be declared with
external linkage depending on the platform.
+ PyMODEXPORT_FUNC: Like PyMODINIT_FUNC, but for a slots array
As a number of platforms support/require "__declspec(dllimport/dllexport)",
we support a HAVE_DECLSPEC_DLL macro to save duplication.
@@ -62,9 +63,9 @@
/* module init functions inside the core need no external linkage */
/* except for Cygwin to handle embedding */
# if defined(__CYGWIN__)
-# define PyMODINIT_FUNC Py_EXPORTED_SYMBOL PyObject*
+# define _PyINIT_FUNC_DECLSPEC Py_EXPORTED_SYMBOL
# else /* __CYGWIN__ */
-# define PyMODINIT_FUNC PyObject*
+# define _PyINIT_FUNC_DECLSPEC
# endif /* __CYGWIN__ */
# else /* Py_BUILD_CORE */
/* Building an extension module, or an embedded situation */
@@ -78,9 +79,9 @@
# define PyAPI_DATA(RTYPE) extern Py_IMPORTED_SYMBOL RTYPE
/* module init functions outside the core must be exported */
# if defined(__cplusplus)
-# define PyMODINIT_FUNC extern "C" Py_EXPORTED_SYMBOL PyObject*
+# define _PyINIT_FUNC_DECLSPEC extern "C" Py_EXPORTED_SYMBOL
# else /* __cplusplus */
-# define PyMODINIT_FUNC Py_EXPORTED_SYMBOL PyObject*
+# define _PyINIT_FUNC_DECLSPEC Py_EXPORTED_SYMBOL
# endif /* __cplusplus */
# endif /* Py_BUILD_CORE */
# endif /* HAVE_DECLSPEC_DLL */
@@ -93,13 +94,15 @@
#ifndef PyAPI_DATA
# define PyAPI_DATA(RTYPE) extern Py_EXPORTED_SYMBOL RTYPE
#endif
-#ifndef PyMODINIT_FUNC
+#ifndef _PyINIT_FUNC_DECLSPEC
# if defined(__cplusplus)
-# define PyMODINIT_FUNC extern "C" Py_EXPORTED_SYMBOL PyObject*
+# define _PyINIT_FUNC_DECLSPEC extern "C" Py_EXPORTED_SYMBOL
# else /* __cplusplus */
-# define PyMODINIT_FUNC Py_EXPORTED_SYMBOL PyObject*
+# define _PyINIT_FUNC_DECLSPEC Py_EXPORTED_SYMBOL
# endif /* __cplusplus */
#endif
+#define PyMODINIT_FUNC _PyINIT_FUNC_DECLSPEC PyObject*
+#define PyMODEXPORT_FUNC _PyINIT_FUNC_DECLSPEC PyModuleDef_Slot*
#endif /* Py_EXPORTS_H */
diff --git a/Include/floatobject.h b/Include/floatobject.h
index 4d24a76edd5..814337b070a 100644
--- a/Include/floatobject.h
+++ b/Include/floatobject.h
@@ -18,14 +18,14 @@ PyAPI_DATA(PyTypeObject) PyFloat_Type;
#define Py_RETURN_NAN return PyFloat_FromDouble(Py_NAN)
-#define Py_RETURN_INF(sign) \
- do { \
- if (copysign(1., sign) == 1.) { \
- return PyFloat_FromDouble(Py_INFINITY); \
- } \
- else { \
- return PyFloat_FromDouble(-Py_INFINITY); \
- } \
+#define Py_RETURN_INF(sign) \
+ do { \
+ if (copysign(1., sign) == 1.) { \
+ return PyFloat_FromDouble(INFINITY); \
+ } \
+ else { \
+ return PyFloat_FromDouble(-INFINITY); \
+ } \
} while(0)
PyAPI_FUNC(double) PyFloat_GetMax(void);
diff --git a/Include/internal/pycore_backoff.h b/Include/internal/pycore_backoff.h
index 454c8dde031..7f60eb49508 100644
--- a/Include/internal/pycore_backoff.h
+++ b/Include/internal/pycore_backoff.h
@@ -22,33 +22,48 @@ extern "C" {
Another use is for the Tier 2 optimizer to decide when to create
a new Tier 2 trace (executor). Again, exponential backoff is used.
- The 16-bit counter is structured as a 12-bit unsigned 'value'
- and a 4-bit 'backoff' field. When resetting the counter, the
+ The 16-bit counter is structured as a 13-bit unsigned 'value'
+ and a 3-bit 'backoff' field. When resetting the counter, the
backoff field is incremented (until it reaches a limit) and the
- value is set to a bit mask representing the value 2**backoff - 1.
- The maximum backoff is 12 (the number of bits in the value).
+ value is set to a bit mask representing some prime value - 1.
+ New values and backoffs for each backoff are calculated once
+ at compile time and saved to value_and_backoff_next table.
+ The maximum backoff is 6, since 7 is an UNREACHABLE_BACKOFF.
There is an exceptional value which must not be updated, 0xFFFF.
*/
-#define BACKOFF_BITS 4
-#define MAX_BACKOFF 12
-#define UNREACHABLE_BACKOFF 15
+#define BACKOFF_BITS 3
+#define BACKOFF_MASK 7
+#define MAX_BACKOFF 6
+#define UNREACHABLE_BACKOFF 7
+#define MAX_VALUE 0x1FFF
-static inline bool
-is_unreachable_backoff_counter(_Py_BackoffCounter counter)
-{
- return counter.value_and_backoff == UNREACHABLE_BACKOFF;
-}
+#define MAKE_VALUE_AND_BACKOFF(value, backoff) \
+ ((value << BACKOFF_BITS) | backoff)
+
+// For previous backoff b we use value x such that
+// x + 1 is near to 2**(2*b+1) and x + 1 is prime.
+static const uint16_t value_and_backoff_next[] = {
+ MAKE_VALUE_AND_BACKOFF(1, 1),
+ MAKE_VALUE_AND_BACKOFF(6, 2),
+ MAKE_VALUE_AND_BACKOFF(30, 3),
+ MAKE_VALUE_AND_BACKOFF(126, 4),
+ MAKE_VALUE_AND_BACKOFF(508, 5),
+ MAKE_VALUE_AND_BACKOFF(2052, 6),
+ // We use the same backoff counter for all backoffs >= MAX_BACKOFF.
+ MAKE_VALUE_AND_BACKOFF(8190, 6),
+ MAKE_VALUE_AND_BACKOFF(8190, 6),
+};
static inline _Py_BackoffCounter
make_backoff_counter(uint16_t value, uint16_t backoff)
{
- assert(backoff <= 15);
- assert(value <= 0xFFF);
- _Py_BackoffCounter result;
- result.value_and_backoff = (value << BACKOFF_BITS) | backoff;
- return result;
+ assert(backoff <= UNREACHABLE_BACKOFF);
+ assert(value <= MAX_VALUE);
+ return ((_Py_BackoffCounter){
+ .value_and_backoff = MAKE_VALUE_AND_BACKOFF(value, backoff)
+ });
}
static inline _Py_BackoffCounter
@@ -62,14 +77,11 @@ forge_backoff_counter(uint16_t counter)
static inline _Py_BackoffCounter
restart_backoff_counter(_Py_BackoffCounter counter)
{
- assert(!is_unreachable_backoff_counter(counter));
- int backoff = counter.value_and_backoff & 15;
- if (backoff < MAX_BACKOFF) {
- return make_backoff_counter((1 << (backoff + 1)) - 1, backoff + 1);
- }
- else {
- return make_backoff_counter((1 << MAX_BACKOFF) - 1, MAX_BACKOFF);
- }
+ uint16_t backoff = counter.value_and_backoff & BACKOFF_MASK;
+ assert(backoff <= MAX_BACKOFF);
+ return ((_Py_BackoffCounter){
+ .value_and_backoff = value_and_backoff_next[backoff]
+ });
}
static inline _Py_BackoffCounter
@@ -95,12 +107,25 @@ backoff_counter_triggers(_Py_BackoffCounter counter)
return counter.value_and_backoff < UNREACHABLE_BACKOFF;
}
+static inline _Py_BackoffCounter
+trigger_backoff_counter(void)
+{
+ _Py_BackoffCounter result;
+ result.value_and_backoff = 0;
+ return result;
+}
+
// Initial JUMP_BACKWARD counter.
// Must be larger than ADAPTIVE_COOLDOWN_VALUE, otherwise when JIT code is
// invalidated we may construct a new trace before the bytecode has properly
// re-specialized:
-#define JUMP_BACKWARD_INITIAL_VALUE 4095
-#define JUMP_BACKWARD_INITIAL_BACKOFF 12
+// Note: this should be a prime number-1. This increases the likelihood of
+// finding a "good" loop iteration to trace.
+// For example, 4095 does not work for the nqueens benchmark on pyperformance
+// as we always end up tracing the loop iteration's
+// exhaustion iteration. Which aborts our current tracer.
+#define JUMP_BACKWARD_INITIAL_VALUE 4000
+#define JUMP_BACKWARD_INITIAL_BACKOFF 6
static inline _Py_BackoffCounter
initial_jump_backoff_counter(void)
{
@@ -112,8 +137,8 @@ initial_jump_backoff_counter(void)
* Must be larger than ADAPTIVE_COOLDOWN_VALUE,
* otherwise when a side exit warms up we may construct
* a new trace before the Tier 1 code has properly re-specialized. */
-#define SIDE_EXIT_INITIAL_VALUE 4095
-#define SIDE_EXIT_INITIAL_BACKOFF 12
+#define SIDE_EXIT_INITIAL_VALUE 4000
+#define SIDE_EXIT_INITIAL_BACKOFF 6
static inline _Py_BackoffCounter
initial_temperature_backoff_counter(void)
diff --git a/Include/internal/pycore_bytesobject.h b/Include/internal/pycore_bytesobject.h
index c7bc53b6073..8e8fa696ee0 100644
--- a/Include/internal/pycore_bytesobject.h
+++ b/Include/internal/pycore_bytesobject.h
@@ -60,6 +60,14 @@ PyAPI_FUNC(void)
_PyBytes_Repeat(char* dest, Py_ssize_t len_dest,
const char* src, Py_ssize_t len_src);
+/* _PyBytesObject_SIZE gives the basic size of a bytes object; any memory allocation
+ for a bytes object of length n should request PyBytesObject_SIZE + n bytes.
+
+ Using _PyBytesObject_SIZE instead of sizeof(PyBytesObject) saves
+ 3 or 7 bytes per bytes object allocation on a typical system.
+*/
+#define _PyBytesObject_SIZE (offsetof(PyBytesObject, ob_sval) + 1)
+
/* --- PyBytesWriter ------------------------------------------------------ */
struct PyBytesWriter {
diff --git a/Include/internal/pycore_ceval.h b/Include/internal/pycore_ceval.h
index fe72a0123eb..2ae84be7b33 100644
--- a/Include/internal/pycore_ceval.h
+++ b/Include/internal/pycore_ceval.h
@@ -217,7 +217,14 @@ extern void _PyEval_DeactivateOpCache(void);
static inline int _Py_MakeRecCheck(PyThreadState *tstate) {
uintptr_t here_addr = _Py_get_machine_stack_pointer();
_PyThreadStateImpl *_tstate = (_PyThreadStateImpl *)tstate;
- return here_addr < _tstate->c_stack_soft_limit;
+ // Overflow if stack pointer is between soft limit and the base of the hardware stack.
+ // If it is below the hardware stack base, assume that we have the wrong stack limits, and do nothing.
+ // We could have the wrong stack limits because of limited platform support, or user-space threads.
+#if _Py_STACK_GROWS_DOWN
+ return here_addr < _tstate->c_stack_soft_limit && here_addr >= _tstate->c_stack_soft_limit - 2 * _PyOS_STACK_MARGIN_BYTES;
+#else
+ return here_addr > _tstate->c_stack_soft_limit && here_addr <= _tstate->c_stack_soft_limit + 2 * _PyOS_STACK_MARGIN_BYTES;
+#endif
}
// Export for '_json' shared extension, used via _Py_EnterRecursiveCall()
@@ -249,7 +256,11 @@ static inline int _Py_ReachedRecursionLimit(PyThreadState *tstate) {
uintptr_t here_addr = _Py_get_machine_stack_pointer();
_PyThreadStateImpl *_tstate = (_PyThreadStateImpl *)tstate;
assert(_tstate->c_stack_hard_limit != 0);
+#if _Py_STACK_GROWS_DOWN
return here_addr <= _tstate->c_stack_soft_limit;
+#else
+ return here_addr >= _tstate->c_stack_soft_limit;
+#endif
}
static inline void _Py_LeaveRecursiveCall(void) {
@@ -392,6 +403,8 @@ _PyForIter_VirtualIteratorNext(PyThreadState* tstate, struct _PyInterpreterFrame
#define SPECIAL___AEXIT__ 3
#define SPECIAL_MAX 3
+PyAPI_DATA(const _Py_CODEUNIT *) _Py_INTERPRETER_TRAMPOLINE_INSTRUCTIONS_PTR;
+
#ifdef __cplusplus
}
#endif
diff --git a/Include/internal/pycore_code.h b/Include/internal/pycore_code.h
index 2d7d81d491c..cb9c0aa27a1 100644
--- a/Include/internal/pycore_code.h
+++ b/Include/internal/pycore_code.h
@@ -274,8 +274,13 @@ extern void _PyLineTable_InitAddressRange(
/** API for traversing the line number table. */
PyAPI_FUNC(int) _PyLineTable_NextAddressRange(PyCodeAddressRange *range);
extern int _PyLineTable_PreviousAddressRange(PyCodeAddressRange *range);
-// This is used in dump_frame() in traceback.c without an attached tstate.
-extern int _PyCode_Addr2LineNoTstate(PyCodeObject *co, int addr);
+
+// Similar to PyCode_Addr2Line(), but return -1 if the code object is invalid
+// and can be called without an attached tstate. Used by dump_frame() in
+// Python/traceback.c. The function uses heuristics to detect freed memory,
+// it's not 100% reliable.
+extern int _PyCode_SafeAddr2Line(PyCodeObject *co, int addr);
+
/** API for executors */
extern void _PyCode_Clear_Executors(PyCodeObject *code);
@@ -306,8 +311,8 @@ PyAPI_FUNC(void) _Py_Specialize_LoadGlobal(PyObject *globals, PyObject *builtins
_Py_CODEUNIT *instr, PyObject *name);
PyAPI_FUNC(void) _Py_Specialize_StoreSubscr(_PyStackRef container, _PyStackRef sub,
_Py_CODEUNIT *instr);
-PyAPI_FUNC(void) _Py_Specialize_Call(_PyStackRef callable, _Py_CODEUNIT *instr,
- int nargs);
+PyAPI_FUNC(void) _Py_Specialize_Call(_PyStackRef callable, _PyStackRef self_or_null,
+ _Py_CODEUNIT *instr, int nargs);
PyAPI_FUNC(void) _Py_Specialize_CallKw(_PyStackRef callable, _Py_CODEUNIT *instr,
int nargs);
PyAPI_FUNC(void) _Py_Specialize_BinaryOp(_PyStackRef lhs, _PyStackRef rhs, _Py_CODEUNIT *instr,
diff --git a/Include/internal/pycore_compile.h b/Include/internal/pycore_compile.h
index 1c60834fa20..527141b54d0 100644
--- a/Include/internal/pycore_compile.h
+++ b/Include/internal/pycore_compile.h
@@ -32,7 +32,8 @@ PyAPI_FUNC(PyCodeObject*) _PyAST_Compile(
PyObject *filename,
PyCompilerFlags *flags,
int optimize,
- struct _arena *arena);
+ struct _arena *arena,
+ PyObject *module);
/* AST preprocessing */
extern int _PyCompile_AstPreprocess(
@@ -41,7 +42,8 @@ extern int _PyCompile_AstPreprocess(
PyCompilerFlags *flags,
int optimize,
struct _arena *arena,
- int syntax_check_only);
+ int syntax_check_only,
+ PyObject *module);
extern int _PyAST_Preprocess(
struct _mod *,
@@ -50,7 +52,8 @@ extern int _PyAST_Preprocess(
int optimize,
int ff_features,
int syntax_check_only,
- int enable_warnings);
+ int enable_warnings,
+ PyObject *module);
typedef struct {
diff --git a/Include/internal/pycore_critical_section.h b/Include/internal/pycore_critical_section.h
index 2601de40737..60b6fc4a72e 100644
--- a/Include/internal/pycore_critical_section.h
+++ b/Include/internal/pycore_critical_section.h
@@ -32,7 +32,7 @@ extern "C" {
const bool _should_lock_cs = PyList_CheckExact(_orig_seq); \
PyCriticalSection _cs; \
if (_should_lock_cs) { \
- _PyCriticalSection_Begin(&_cs, _orig_seq); \
+ PyCriticalSection_Begin(&_cs, _orig_seq); \
}
# define Py_END_CRITICAL_SECTION_SEQUENCE_FAST() \
@@ -77,10 +77,10 @@ _PyCriticalSection_Resume(PyThreadState *tstate);
// (private) slow path for locking the mutex
PyAPI_FUNC(void)
-_PyCriticalSection_BeginSlow(PyCriticalSection *c, PyMutex *m);
+_PyCriticalSection_BeginSlow(PyThreadState *tstate, PyCriticalSection *c, PyMutex *m);
PyAPI_FUNC(void)
-_PyCriticalSection2_BeginSlow(PyCriticalSection2 *c, PyMutex *m1, PyMutex *m2,
+_PyCriticalSection2_BeginSlow(PyThreadState *tstate, PyCriticalSection2 *c, PyMutex *m1, PyMutex *m2,
int is_m1_locked);
PyAPI_FUNC(void)
@@ -95,34 +95,30 @@ _PyCriticalSection_IsActive(uintptr_t tag)
}
static inline void
-_PyCriticalSection_BeginMutex(PyCriticalSection *c, PyMutex *m)
+_PyCriticalSection_BeginMutex(PyThreadState *tstate, PyCriticalSection *c, PyMutex *m)
{
if (PyMutex_LockFast(m)) {
- PyThreadState *tstate = _PyThreadState_GET();
c->_cs_mutex = m;
c->_cs_prev = tstate->critical_section;
tstate->critical_section = (uintptr_t)c;
}
else {
- _PyCriticalSection_BeginSlow(c, m);
+ _PyCriticalSection_BeginSlow(tstate, c, m);
}
}
-#define PyCriticalSection_BeginMutex _PyCriticalSection_BeginMutex
static inline void
-_PyCriticalSection_Begin(PyCriticalSection *c, PyObject *op)
+_PyCriticalSection_Begin(PyThreadState *tstate, PyCriticalSection *c, PyObject *op)
{
- _PyCriticalSection_BeginMutex(c, &op->ob_mutex);
+ _PyCriticalSection_BeginMutex(tstate, c, &op->ob_mutex);
}
-#define PyCriticalSection_Begin _PyCriticalSection_Begin
// Removes the top-most critical section from the thread's stack of critical
// sections. If the new top-most critical section is inactive, then it is
// resumed.
static inline void
-_PyCriticalSection_Pop(PyCriticalSection *c)
+_PyCriticalSection_Pop(PyThreadState *tstate, PyCriticalSection *c)
{
- PyThreadState *tstate = _PyThreadState_GET();
uintptr_t prev = c->_cs_prev;
tstate->critical_section = prev;
@@ -132,7 +128,7 @@ _PyCriticalSection_Pop(PyCriticalSection *c)
}
static inline void
-_PyCriticalSection_End(PyCriticalSection *c)
+_PyCriticalSection_End(PyThreadState *tstate, PyCriticalSection *c)
{
// If the mutex is NULL, we used the fast path in
// _PyCriticalSection_BeginSlow for locks already held in the top-most
@@ -141,18 +137,17 @@ _PyCriticalSection_End(PyCriticalSection *c)
return;
}
PyMutex_Unlock(c->_cs_mutex);
- _PyCriticalSection_Pop(c);
+ _PyCriticalSection_Pop(tstate, c);
}
-#define PyCriticalSection_End _PyCriticalSection_End
static inline void
-_PyCriticalSection2_BeginMutex(PyCriticalSection2 *c, PyMutex *m1, PyMutex *m2)
+_PyCriticalSection2_BeginMutex(PyThreadState *tstate, PyCriticalSection2 *c, PyMutex *m1, PyMutex *m2)
{
if (m1 == m2) {
// If the two mutex arguments are the same, treat this as a critical
// section with a single mutex.
c->_cs_mutex2 = NULL;
- _PyCriticalSection_BeginMutex(&c->_cs_base, m1);
+ _PyCriticalSection_BeginMutex(tstate, &c->_cs_base, m1);
return;
}
@@ -167,7 +162,6 @@ _PyCriticalSection2_BeginMutex(PyCriticalSection2 *c, PyMutex *m1, PyMutex *m2)
if (PyMutex_LockFast(m1)) {
if (PyMutex_LockFast(m2)) {
- PyThreadState *tstate = _PyThreadState_GET();
c->_cs_base._cs_mutex = m1;
c->_cs_mutex2 = m2;
c->_cs_base._cs_prev = tstate->critical_section;
@@ -176,24 +170,22 @@ _PyCriticalSection2_BeginMutex(PyCriticalSection2 *c, PyMutex *m1, PyMutex *m2)
tstate->critical_section = p;
}
else {
- _PyCriticalSection2_BeginSlow(c, m1, m2, 1);
+ _PyCriticalSection2_BeginSlow(tstate, c, m1, m2, 1);
}
}
else {
- _PyCriticalSection2_BeginSlow(c, m1, m2, 0);
+ _PyCriticalSection2_BeginSlow(tstate, c, m1, m2, 0);
}
}
-#define PyCriticalSection2_BeginMutex _PyCriticalSection2_BeginMutex
static inline void
-_PyCriticalSection2_Begin(PyCriticalSection2 *c, PyObject *a, PyObject *b)
+_PyCriticalSection2_Begin(PyThreadState *tstate, PyCriticalSection2 *c, PyObject *a, PyObject *b)
{
- _PyCriticalSection2_BeginMutex(c, &a->ob_mutex, &b->ob_mutex);
+ _PyCriticalSection2_BeginMutex(tstate, c, &a->ob_mutex, &b->ob_mutex);
}
-#define PyCriticalSection2_Begin _PyCriticalSection2_Begin
static inline void
-_PyCriticalSection2_End(PyCriticalSection2 *c)
+_PyCriticalSection2_End(PyThreadState *tstate, PyCriticalSection2 *c)
{
// if mutex1 is NULL, we used the fast path in
// _PyCriticalSection_BeginSlow for mutexes that are already held,
@@ -207,9 +199,8 @@ _PyCriticalSection2_End(PyCriticalSection2 *c)
PyMutex_Unlock(c->_cs_mutex2);
}
PyMutex_Unlock(c->_cs_base._cs_mutex);
- _PyCriticalSection_Pop(&c->_cs_base);
+ _PyCriticalSection_Pop(tstate, &c->_cs_base);
}
-#define PyCriticalSection2_End _PyCriticalSection2_End
static inline void
_PyCriticalSection_AssertHeld(PyMutex *mutex)
@@ -251,6 +242,45 @@ _PyCriticalSection_AssertHeldObj(PyObject *op)
#endif
}
+
+#undef Py_BEGIN_CRITICAL_SECTION
+# define Py_BEGIN_CRITICAL_SECTION(op) \
+ { \
+ PyCriticalSection _py_cs; \
+ PyThreadState *_cs_tstate = _PyThreadState_GET(); \
+ _PyCriticalSection_Begin(_cs_tstate, &_py_cs, _PyObject_CAST(op))
+
+#undef Py_BEGIN_CRITICAL_SECTION_MUTEX
+# define Py_BEGIN_CRITICAL_SECTION_MUTEX(mutex) \
+ { \
+ PyCriticalSection _py_cs; \
+ PyThreadState *_cs_tstate = _PyThreadState_GET(); \
+ _PyCriticalSection_BeginMutex(_cs_tstate, &_py_cs, mutex)
+
+#undef Py_END_CRITICAL_SECTION
+# define Py_END_CRITICAL_SECTION() \
+ _PyCriticalSection_End(_cs_tstate, &_py_cs); \
+ }
+
+#undef Py_BEGIN_CRITICAL_SECTION2
+# define Py_BEGIN_CRITICAL_SECTION2(a, b) \
+ { \
+ PyCriticalSection2 _py_cs2; \
+ PyThreadState *_cs_tstate = _PyThreadState_GET(); \
+ _PyCriticalSection2_Begin(_cs_tstate, &_py_cs2, _PyObject_CAST(a), _PyObject_CAST(b))
+
+#undef Py_BEGIN_CRITICAL_SECTION2_MUTEX
+# define Py_BEGIN_CRITICAL_SECTION2_MUTEX(m1, m2) \
+ { \
+ PyCriticalSection2 _py_cs2; \
+ PyThreadState *_cs_tstate = _PyThreadState_GET(); \
+ _PyCriticalSection2_BeginMutex(_cs_tstate, &_py_cs2, m1, m2)
+
+#undef Py_END_CRITICAL_SECTION2
+# define Py_END_CRITICAL_SECTION2() \
+ _PyCriticalSection2_End(_cs_tstate, &_py_cs2); \
+ }
+
#endif /* Py_GIL_DISABLED */
#ifdef __cplusplus
diff --git a/Include/internal/pycore_debug_offsets.h b/Include/internal/pycore_debug_offsets.h
index 8e7cd16acff..0f17bf17f82 100644
--- a/Include/internal/pycore_debug_offsets.h
+++ b/Include/internal/pycore_debug_offsets.h
@@ -106,6 +106,8 @@ typedef struct _Py_DebugOffsets {
uint64_t native_thread_id;
uint64_t datastack_chunk;
uint64_t status;
+ uint64_t holds_gil;
+ uint64_t gil_requested;
} thread_state;
// InterpreterFrame offset;
@@ -210,6 +212,7 @@ typedef struct _Py_DebugOffsets {
struct _gc {
uint64_t size;
uint64_t collecting;
+ uint64_t frame;
} gc;
// Generator object offset;
@@ -273,6 +276,8 @@ typedef struct _Py_DebugOffsets {
.native_thread_id = offsetof(PyThreadState, native_thread_id), \
.datastack_chunk = offsetof(PyThreadState, datastack_chunk), \
.status = offsetof(PyThreadState, _status), \
+ .holds_gil = offsetof(PyThreadState, holds_gil), \
+ .gil_requested = offsetof(PyThreadState, gil_requested), \
}, \
.interpreter_frame = { \
.size = sizeof(_PyInterpreterFrame), \
@@ -351,6 +356,7 @@ typedef struct _Py_DebugOffsets {
.gc = { \
.size = sizeof(struct _gc_runtime_state), \
.collecting = offsetof(struct _gc_runtime_state, collecting), \
+ .frame = offsetof(struct _gc_runtime_state, frame), \
}, \
.gen_object = { \
.size = sizeof(PyGenObject), \
diff --git a/Include/internal/pycore_global_objects_fini_generated.h b/Include/internal/pycore_global_objects_fini_generated.h
index 92ded14891a..783747d1f01 100644
--- a/Include/internal/pycore_global_objects_fini_generated.h
+++ b/Include/internal/pycore_global_objects_fini_generated.h
@@ -13,7 +13,7 @@ static inline void
_PyStaticObject_CheckRefcnt(PyObject *obj) {
if (!_Py_IsImmortal(obj)) {
fprintf(stderr, "Immortal Object has less refcnt than expected.\n");
- _PyObject_Dump(obj);
+ PyUnstable_Object_Dump(obj);
}
}
#endif
@@ -1326,10 +1326,12 @@ _PyStaticObjects_CheckRefcnt(PyInterpreterState *interp) {
_PyStaticObject_CheckRefcnt((PyObject *)&_Py_STR(dot_locals));
_PyStaticObject_CheckRefcnt((PyObject *)&_Py_STR(empty));
_PyStaticObject_CheckRefcnt((PyObject *)&_Py_STR(format));
+ _PyStaticObject_CheckRefcnt((PyObject *)&_Py_STR(gc));
_PyStaticObject_CheckRefcnt((PyObject *)&_Py_STR(generic_base));
_PyStaticObject_CheckRefcnt((PyObject *)&_Py_STR(json_decoder));
_PyStaticObject_CheckRefcnt((PyObject *)&_Py_STR(kwdefaults));
_PyStaticObject_CheckRefcnt((PyObject *)&_Py_STR(list_err));
+ _PyStaticObject_CheckRefcnt((PyObject *)&_Py_STR(native));
_PyStaticObject_CheckRefcnt((PyObject *)&_Py_STR(str_replace_inf));
_PyStaticObject_CheckRefcnt((PyObject *)&_Py_STR(type_params));
_PyStaticObject_CheckRefcnt((PyObject *)&_Py_STR(utf_8));
@@ -1763,6 +1765,7 @@ _PyStaticObjects_CheckRefcnt(PyInterpreterState *interp) {
_PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(fullerror));
_PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(func));
_PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(future));
+ _PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(gc));
_PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(generation));
_PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(get));
_PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(get_debug));
@@ -1906,6 +1909,7 @@ _PyStaticObjects_CheckRefcnt(PyInterpreterState *interp) {
_PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(name_from));
_PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(namespace_separator));
_PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(namespaces));
+ _PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(native));
_PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(ndigits));
_PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(nested));
_PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(new_file_name));
@@ -2066,6 +2070,7 @@ _PyStaticObjects_CheckRefcnt(PyInterpreterState *interp) {
_PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(symmetric_difference_update));
_PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(tabsize));
_PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(tag));
+ _PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(take_bytes));
_PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(target));
_PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(target_is_directory));
_PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(task));
diff --git a/Include/internal/pycore_global_strings.h b/Include/internal/pycore_global_strings.h
index cd21b0847b7..374617d8284 100644
--- a/Include/internal/pycore_global_strings.h
+++ b/Include/internal/pycore_global_strings.h
@@ -46,10 +46,12 @@ struct _Py_global_strings {
STRUCT_FOR_STR(dot_locals, ".")
STRUCT_FOR_STR(empty, "")
STRUCT_FOR_STR(format, ".format")
+ STRUCT_FOR_STR(gc, "")
STRUCT_FOR_STR(generic_base, ".generic_base")
STRUCT_FOR_STR(json_decoder, "json.decoder")
STRUCT_FOR_STR(kwdefaults, ".kwdefaults")
STRUCT_FOR_STR(list_err, "list index out of range")
+ STRUCT_FOR_STR(native, "")
STRUCT_FOR_STR(str_replace_inf, "1e309")
STRUCT_FOR_STR(type_params, ".type_params")
STRUCT_FOR_STR(utf_8, "utf-8")
@@ -486,6 +488,7 @@ struct _Py_global_strings {
STRUCT_FOR_ID(fullerror)
STRUCT_FOR_ID(func)
STRUCT_FOR_ID(future)
+ STRUCT_FOR_ID(gc)
STRUCT_FOR_ID(generation)
STRUCT_FOR_ID(get)
STRUCT_FOR_ID(get_debug)
@@ -629,6 +632,7 @@ struct _Py_global_strings {
STRUCT_FOR_ID(name_from)
STRUCT_FOR_ID(namespace_separator)
STRUCT_FOR_ID(namespaces)
+ STRUCT_FOR_ID(native)
STRUCT_FOR_ID(ndigits)
STRUCT_FOR_ID(nested)
STRUCT_FOR_ID(new_file_name)
@@ -789,6 +793,7 @@ struct _Py_global_strings {
STRUCT_FOR_ID(symmetric_difference_update)
STRUCT_FOR_ID(tabsize)
STRUCT_FOR_ID(tag)
+ STRUCT_FOR_ID(take_bytes)
STRUCT_FOR_ID(target)
STRUCT_FOR_ID(target_is_directory)
STRUCT_FOR_ID(task)
diff --git a/Include/internal/pycore_importdl.h b/Include/internal/pycore_importdl.h
index 3ba9229cc21..f60c5510d20 100644
--- a/Include/internal/pycore_importdl.h
+++ b/Include/internal/pycore_importdl.h
@@ -14,6 +14,34 @@ extern "C" {
extern const char *_PyImport_DynLoadFiletab[];
+#ifdef HAVE_DYNAMIC_LOADING
+/* ./configure sets HAVE_DYNAMIC_LOADING if dynamic loading of modules is
+ supported on this platform. configure will then compile and link in one
+ of the dynload_*.c files, as appropriate. We will call a function in
+ those modules to get a function pointer to the module's init function.
+
+ The function should return:
+ - The function pointer on success
+ - NULL with exception set if the library cannot be loaded
+ - NULL *without* an extension set if the library could be loaded but the
+ function cannot be found in it.
+*/
+#ifdef MS_WINDOWS
+#include
+typedef FARPROC dl_funcptr;
+extern dl_funcptr _PyImport_FindSharedFuncptrWindows(const char *prefix,
+ const char *shortname,
+ PyObject *pathname,
+ FILE *fp);
+#else
+typedef void (*dl_funcptr)(void);
+extern dl_funcptr _PyImport_FindSharedFuncptr(const char *prefix,
+ const char *shortname,
+ const char *pathname, FILE *fp);
+#endif
+
+#endif /* HAVE_DYNAMIC_LOADING */
+
typedef enum ext_module_kind {
_Py_ext_module_kind_UNKNOWN = 0,
@@ -28,6 +56,11 @@ typedef enum ext_module_origin {
_Py_ext_module_origin_DYNAMIC = 3,
} _Py_ext_module_origin;
+struct hook_prefixes {
+ const char *const init_prefix;
+ const char *const export_prefix;
+};
+
/* Input for loading an extension module. */
struct _Py_ext_module_loader_info {
PyObject *filename;
@@ -40,7 +73,7 @@ struct _Py_ext_module_loader_info {
* depending on if it's builtin or not. */
PyObject *path;
_Py_ext_module_origin origin;
- const char *hook_prefix;
+ const struct hook_prefixes *hook_prefixes;
const char *newcontext;
};
extern void _Py_ext_module_loader_info_clear(
@@ -62,7 +95,9 @@ extern int _Py_ext_module_loader_info_init_from_spec(
PyObject *spec);
#endif
-/* The result from running an extension module's init function. */
+/* The result from running an extension module's init function.
+ * Not used for modules defined via PyModExport (slots array).
+ */
struct _Py_ext_module_loader_result {
PyModuleDef *def;
PyObject *module;
@@ -89,10 +124,11 @@ extern void _Py_ext_module_loader_result_apply_error(
/* The module init function. */
typedef PyObject *(*PyModInitFunction)(void);
+typedef PyModuleDef_Slot *(*PyModExportFunction)(void);
#ifdef HAVE_DYNAMIC_LOADING
-extern PyModInitFunction _PyImport_GetModInitFunc(
+extern int _PyImport_GetModuleExportHooks(
struct _Py_ext_module_loader_info *info,
- FILE *fp);
+ FILE *fp, PyModInitFunction *modinit, PyModExportFunction *modexport);
#endif
extern int _PyImport_RunModInitFunc(
PyModInitFunction p0,
@@ -104,8 +140,6 @@ extern int _PyImport_RunModInitFunc(
#define MAXSUFFIXSIZE 12
#ifdef MS_WINDOWS
-#include
-typedef FARPROC dl_funcptr;
#ifdef Py_DEBUG
# define PYD_DEBUG_SUFFIX "_d"
@@ -128,8 +162,6 @@ typedef FARPROC dl_funcptr;
#define PYD_TAGGED_SUFFIX PYD_DEBUG_SUFFIX "." PYD_SOABI ".pyd"
#define PYD_UNTAGGED_SUFFIX PYD_DEBUG_SUFFIX ".pyd"
-#else
-typedef void (*dl_funcptr)(void);
#endif
diff --git a/Include/internal/pycore_interp_structs.h b/Include/internal/pycore_interp_structs.h
index 9cdaa950e34..6b3d5711b92 100644
--- a/Include/internal/pycore_interp_structs.h
+++ b/Include/internal/pycore_interp_structs.h
@@ -14,8 +14,6 @@ extern "C" {
#include "pycore_structs.h" // PyHamtObject
#include "pycore_tstate.h" // _PyThreadStateImpl
#include "pycore_typedefs.h" // _PyRuntimeState
-#include "pycore_uop.h" // struct _PyUOpInstruction
-
#define CODE_MAX_WATCHERS 8
#define CONTEXT_MAX_WATCHERS 8
@@ -181,6 +179,10 @@ struct gc_collection_stats {
Py_ssize_t collected;
/* total number of uncollectable objects (put into gc.garbage) */
Py_ssize_t uncollectable;
+ // Total number of objects considered for collection and traversed:
+ Py_ssize_t candidates;
+ // Duration of the collection in seconds:
+ double duration;
};
/* Running stats per generation */
@@ -191,6 +193,10 @@ struct gc_generation_stats {
Py_ssize_t collected;
/* total number of uncollectable objects (put into gc.garbage) */
Py_ssize_t uncollectable;
+ // Total number of objects considered for collection and traversed:
+ Py_ssize_t candidates;
+ // Duration of the collection in seconds:
+ double duration;
};
enum _GCPhase {
@@ -199,7 +205,7 @@ enum _GCPhase {
};
/* If we change this, we need to change the default value in the
- signature of gc.collect. */
+ signature of gc.collect and change the size of PyStats.gc_stats */
#define NUM_GENERATIONS 3
struct _gc_runtime_state {
@@ -214,6 +220,9 @@ struct _gc_runtime_state {
struct gc_generation_stats generation_stats[NUM_GENERATIONS];
/* true if we are currently running the collector */
int collecting;
+ // The frame that started the current collection. It might be NULL even when
+ // collecting (if no Python frame is running):
+ _PyInterpreterFrame *frame;
/* list of uncollectable objects */
PyObject *garbage;
/* a list of callbacks to be invoked when collection is performed */
@@ -934,10 +943,10 @@ struct _is {
PyObject *common_consts[NUM_COMMON_CONSTANTS];
bool jit;
bool compiling;
- struct _PyUOpInstruction *jit_uop_buffer;
struct _PyExecutorObject *executor_list_head;
struct _PyExecutorObject *executor_deletion_list_head;
struct _PyExecutorObject *cold_executor;
+ struct _PyExecutorObject *cold_dynamic_executor;
int executor_deletion_list_remaining_capacity;
size_t executor_creation_counter;
_rare_events rare_events;
@@ -963,6 +972,18 @@ struct _is {
# ifdef Py_STACKREF_CLOSE_DEBUG
_Py_hashtable_t *closed_stackrefs_table;
# endif
+#endif
+
+#ifdef Py_STATS
+ // true if recording of pystats is on, this is used when new threads
+ // are created to decide if recording should be on for them
+ int pystats_enabled;
+ // allocated when (and if) stats are first enabled
+ PyStats *pystats_struct;
+#ifdef Py_GIL_DISABLED
+ // held when pystats related interpreter state is being updated
+ PyMutex pystats_mutex;
+#endif
#endif
/* the initial PyInterpreterState.threads.head */
diff --git a/Include/internal/pycore_interpframe.h b/Include/internal/pycore_interpframe.h
index 2ee3696317c..8949d6cc2fc 100644
--- a/Include/internal/pycore_interpframe.h
+++ b/Include/internal/pycore_interpframe.h
@@ -24,6 +24,36 @@ static inline PyCodeObject *_PyFrame_GetCode(_PyInterpreterFrame *f) {
return (PyCodeObject *)executable;
}
+// Similar to _PyFrame_GetCode(), but return NULL if the frame is invalid or
+// freed. Used by dump_frame() in Python/traceback.c. The function uses
+// heuristics to detect freed memory, it's not 100% reliable.
+static inline PyCodeObject*
+_PyFrame_SafeGetCode(_PyInterpreterFrame *f)
+{
+ // globals and builtins may be NULL on a legit frame, but it's unlikely.
+ // It's more likely that it's a sign of an invalid frame.
+ if (f->f_globals == NULL || f->f_builtins == NULL) {
+ return NULL;
+ }
+
+ if (PyStackRef_IsNull(f->f_executable)) {
+ return NULL;
+ }
+ void *ptr;
+ memcpy(&ptr, &f->f_executable, sizeof(f->f_executable));
+ if (_PyMem_IsPtrFreed(ptr)) {
+ return NULL;
+ }
+ PyObject *executable = PyStackRef_AsPyObjectBorrow(f->f_executable);
+ if (_PyObject_IsFreed(executable)) {
+ return NULL;
+ }
+ if (!PyCode_Check(executable)) {
+ return NULL;
+ }
+ return (PyCodeObject *)executable;
+}
+
static inline _Py_CODEUNIT *
_PyFrame_GetBytecode(_PyInterpreterFrame *f)
{
@@ -37,6 +67,31 @@ _PyFrame_GetBytecode(_PyInterpreterFrame *f)
#endif
}
+// Similar to PyUnstable_InterpreterFrame_GetLasti(), but return NULL if the
+// frame is invalid or freed. Used by dump_frame() in Python/traceback.c. The
+// function uses heuristics to detect freed memory, it's not 100% reliable.
+static inline int
+_PyFrame_SafeGetLasti(struct _PyInterpreterFrame *f)
+{
+ // Code based on _PyFrame_GetBytecode() but replace _PyFrame_GetCode()
+ // with _PyFrame_SafeGetCode().
+ PyCodeObject *co = _PyFrame_SafeGetCode(f);
+ if (co == NULL) {
+ return -1;
+ }
+
+ _Py_CODEUNIT *bytecode;
+#ifdef Py_GIL_DISABLED
+ _PyCodeArray *tlbc = _PyCode_GetTLBCArray(co);
+ assert(f->tlbc_index >= 0 && f->tlbc_index < tlbc->size);
+ bytecode = (_Py_CODEUNIT *)tlbc->entries[f->tlbc_index];
+#else
+ bytecode = _PyCode_CODE(co);
+#endif
+
+ return (int)(f->instr_ptr - bytecode) * sizeof(_Py_CODEUNIT);
+}
+
static inline PyFunctionObject *_PyFrame_GetFunction(_PyInterpreterFrame *f) {
PyObject *func = PyStackRef_AsPyObjectBorrow(f->f_funcobj);
assert(PyFunction_Check(func));
diff --git a/Include/internal/pycore_interpframe_structs.h b/Include/internal/pycore_interpframe_structs.h
index 835b8e58194..38510685f40 100644
--- a/Include/internal/pycore_interpframe_structs.h
+++ b/Include/internal/pycore_interpframe_structs.h
@@ -24,7 +24,6 @@ enum _frameowner {
FRAME_OWNED_BY_GENERATOR = 1,
FRAME_OWNED_BY_FRAME_OBJECT = 2,
FRAME_OWNED_BY_INTERPRETER = 3,
- FRAME_OWNED_BY_CSTACK = 4,
};
struct _PyInterpreterFrame {
diff --git a/Include/internal/pycore_magic_number.h b/Include/internal/pycore_magic_number.h
index 7ec7bd1c695..2fb46a6df50 100644
--- a/Include/internal/pycore_magic_number.h
+++ b/Include/internal/pycore_magic_number.h
@@ -286,6 +286,7 @@ Known values:
Python 3.15a1 3653 (Fix handling of opcodes that may leave operands on the stack when optimizing LOAD_FAST)
Python 3.15a1 3654 (Fix missing exception handlers in logical expression)
Python 3.15a1 3655 (Fix miscompilation of some module-level annotations)
+ Python 3.15a1 3656 (Add TRACE_RECORD instruction, for platforms with switch based interpreter)
Python 3.16 will start with 3700
@@ -299,7 +300,7 @@ PC/launcher.c must also be updated.
*/
-#define PYC_MAGIC_NUMBER 3655
+#define PYC_MAGIC_NUMBER 3656
/* This is equivalent to converting PYC_MAGIC_NUMBER to 2 bytes
(little-endian) and then appending b'\r\n'. */
#define PYC_MAGIC_NUMBER_TOKEN \
diff --git a/Include/internal/pycore_moduleobject.h b/Include/internal/pycore_moduleobject.h
index b170d7bce70..9a62daf6621 100644
--- a/Include/internal/pycore_moduleobject.h
+++ b/Include/internal/pycore_moduleobject.h
@@ -1,5 +1,8 @@
#ifndef Py_INTERNAL_MODULEOBJECT_H
#define Py_INTERNAL_MODULEOBJECT_H
+
+#include
+
#ifdef __cplusplus
extern "C" {
#endif
@@ -16,32 +19,49 @@ extern int _PyModule_IsPossiblyShadowing(PyObject *);
extern int _PyModule_IsExtension(PyObject *obj);
+typedef int (*_Py_modexecfunc)(PyObject *);
+
typedef struct {
PyObject_HEAD
PyObject *md_dict;
- PyModuleDef *md_def;
void *md_state;
PyObject *md_weaklist;
// for logging purposes after md_dict is cleared
PyObject *md_name;
+ bool md_token_is_def; /* if true, `md_token` is the PyModuleDef */
#ifdef Py_GIL_DISABLED
- void *md_gil;
+ bool md_requires_gil;
#endif
+ Py_ssize_t md_state_size;
+ traverseproc md_state_traverse;
+ inquiry md_state_clear;
+ freefunc md_state_free;
+ void *md_token;
+ _Py_modexecfunc md_exec; /* only set if md_token_is_def is true */
} PyModuleObject;
-static inline PyModuleDef* _PyModule_GetDef(PyObject *mod) {
- assert(PyModule_Check(mod));
- return ((PyModuleObject *)mod)->md_def;
+#define _PyModule_CAST(op) \
+ (assert(PyModule_Check(op)), _Py_CAST(PyModuleObject*, (op)))
+
+static inline PyModuleDef *_PyModule_GetDefOrNull(PyObject *arg) {
+ PyModuleObject *mod = _PyModule_CAST(arg);
+ if (mod->md_token_is_def) {
+ return (PyModuleDef *)mod->md_token;
+ }
+ return NULL;
+}
+
+static inline PyModuleDef *_PyModule_GetToken(PyObject *arg) {
+ PyModuleObject *mod = _PyModule_CAST(arg);
+ return (PyModuleDef *)mod->md_token;
}
static inline void* _PyModule_GetState(PyObject* mod) {
- assert(PyModule_Check(mod));
- return ((PyModuleObject *)mod)->md_state;
+ return _PyModule_CAST(mod)->md_state;
}
static inline PyObject* _PyModule_GetDict(PyObject *mod) {
- assert(PyModule_Check(mod));
- PyObject *dict = ((PyModuleObject *)mod) -> md_dict;
+ PyObject *dict = _PyModule_CAST(mod)->md_dict;
// _PyModule_GetDict(mod) must not be used after calling module_clear(mod)
assert(dict != NULL);
return dict; // borrowed reference
diff --git a/Include/internal/pycore_object.h b/Include/internal/pycore_object.h
index 980d6d7764b..fb50acd62da 100644
--- a/Include/internal/pycore_object.h
+++ b/Include/internal/pycore_object.h
@@ -863,8 +863,7 @@ static inline Py_hash_t
_PyObject_HashFast(PyObject *op)
{
if (PyUnicode_CheckExact(op)) {
- Py_hash_t hash = FT_ATOMIC_LOAD_SSIZE_RELAXED(
- _PyASCIIObject_CAST(op)->hash);
+ Py_hash_t hash = PyUnstable_Unicode_GET_CACHED_HASH(op);
if (hash != -1) {
return hash;
}
diff --git a/Include/internal/pycore_opcode_metadata.h b/Include/internal/pycore_opcode_metadata.h
index bd6b84ec7fd..cca88818c57 100644
--- a/Include/internal/pycore_opcode_metadata.h
+++ b/Include/internal/pycore_opcode_metadata.h
@@ -488,6 +488,8 @@ int _PyOpcode_num_popped(int opcode, int oparg) {
return 1;
case TO_BOOL_STR:
return 1;
+ case TRACE_RECORD:
+ return 0;
case UNARY_INVERT:
return 1;
case UNARY_NEGATIVE:
@@ -971,6 +973,8 @@ int _PyOpcode_num_pushed(int opcode, int oparg) {
return 1;
case TO_BOOL_STR:
return 1;
+ case TRACE_RECORD:
+ return 0;
case UNARY_INVERT:
return 1;
case UNARY_NEGATIVE:
@@ -1031,6 +1035,8 @@ enum InstructionFormat {
#define HAS_ERROR_NO_POP_FLAG (4096)
#define HAS_NO_SAVE_IP_FLAG (8192)
#define HAS_PERIODIC_FLAG (16384)
+#define HAS_UNPREDICTABLE_JUMP_FLAG (32768)
+#define HAS_NEEDS_GUARD_IP_FLAG (65536)
#define OPCODE_HAS_ARG(OP) (_PyOpcode_opcode_metadata[OP].flags & (HAS_ARG_FLAG))
#define OPCODE_HAS_CONST(OP) (_PyOpcode_opcode_metadata[OP].flags & (HAS_CONST_FLAG))
#define OPCODE_HAS_NAME(OP) (_PyOpcode_opcode_metadata[OP].flags & (HAS_NAME_FLAG))
@@ -1046,6 +1052,8 @@ enum InstructionFormat {
#define OPCODE_HAS_ERROR_NO_POP(OP) (_PyOpcode_opcode_metadata[OP].flags & (HAS_ERROR_NO_POP_FLAG))
#define OPCODE_HAS_NO_SAVE_IP(OP) (_PyOpcode_opcode_metadata[OP].flags & (HAS_NO_SAVE_IP_FLAG))
#define OPCODE_HAS_PERIODIC(OP) (_PyOpcode_opcode_metadata[OP].flags & (HAS_PERIODIC_FLAG))
+#define OPCODE_HAS_UNPREDICTABLE_JUMP(OP) (_PyOpcode_opcode_metadata[OP].flags & (HAS_UNPREDICTABLE_JUMP_FLAG))
+#define OPCODE_HAS_NEEDS_GUARD_IP(OP) (_PyOpcode_opcode_metadata[OP].flags & (HAS_NEEDS_GUARD_IP_FLAG))
#define OPARG_SIMPLE 0
#define OPARG_CACHE_1 1
@@ -1062,7 +1070,7 @@ enum InstructionFormat {
struct opcode_metadata {
uint8_t valid_entry;
uint8_t instr_format;
- uint16_t flags;
+ uint32_t flags;
};
extern const struct opcode_metadata _PyOpcode_opcode_metadata[267];
@@ -1077,7 +1085,7 @@ const struct opcode_metadata _PyOpcode_opcode_metadata[267] = {
[BINARY_OP_MULTIPLY_FLOAT] = { true, INSTR_FMT_IXC0000, HAS_EXIT_FLAG | HAS_ERROR_FLAG },
[BINARY_OP_MULTIPLY_INT] = { true, INSTR_FMT_IXC0000, HAS_EXIT_FLAG },
[BINARY_OP_SUBSCR_DICT] = { true, INSTR_FMT_IXC0000, HAS_EXIT_FLAG | HAS_ERROR_FLAG | HAS_ESCAPES_FLAG },
- [BINARY_OP_SUBSCR_GETITEM] = { true, INSTR_FMT_IXC0000, HAS_DEOPT_FLAG },
+ [BINARY_OP_SUBSCR_GETITEM] = { true, INSTR_FMT_IXC0000, HAS_DEOPT_FLAG | HAS_NEEDS_GUARD_IP_FLAG },
[BINARY_OP_SUBSCR_LIST_INT] = { true, INSTR_FMT_IXC0000, HAS_DEOPT_FLAG | HAS_EXIT_FLAG | HAS_ESCAPES_FLAG },
[BINARY_OP_SUBSCR_LIST_SLICE] = { true, INSTR_FMT_IXC0000, HAS_EXIT_FLAG | HAS_ERROR_FLAG | HAS_ESCAPES_FLAG },
[BINARY_OP_SUBSCR_STR_INT] = { true, INSTR_FMT_IXC0000, HAS_DEOPT_FLAG | HAS_EXIT_FLAG | HAS_ESCAPES_FLAG },
@@ -1094,22 +1102,22 @@ const struct opcode_metadata _PyOpcode_opcode_metadata[267] = {
[BUILD_TEMPLATE] = { true, INSTR_FMT_IX, HAS_ERROR_FLAG | HAS_ESCAPES_FLAG },
[BUILD_TUPLE] = { true, INSTR_FMT_IB, HAS_ARG_FLAG | HAS_ERROR_FLAG | HAS_ERROR_NO_POP_FLAG },
[CACHE] = { true, INSTR_FMT_IX, 0 },
- [CALL] = { true, INSTR_FMT_IBC00, HAS_ARG_FLAG | HAS_EVAL_BREAK_FLAG | HAS_ERROR_FLAG | HAS_ERROR_NO_POP_FLAG | HAS_ESCAPES_FLAG },
- [CALL_ALLOC_AND_ENTER_INIT] = { true, INSTR_FMT_IBC00, HAS_ARG_FLAG | HAS_DEOPT_FLAG | HAS_ERROR_FLAG | HAS_ERROR_NO_POP_FLAG | HAS_ESCAPES_FLAG },
- [CALL_BOUND_METHOD_EXACT_ARGS] = { true, INSTR_FMT_IBC00, HAS_ARG_FLAG | HAS_DEOPT_FLAG | HAS_EXIT_FLAG | HAS_ESCAPES_FLAG },
- [CALL_BOUND_METHOD_GENERAL] = { true, INSTR_FMT_IBC00, HAS_ARG_FLAG | HAS_DEOPT_FLAG | HAS_EXIT_FLAG | HAS_ERROR_FLAG | HAS_ERROR_NO_POP_FLAG | HAS_ESCAPES_FLAG },
+ [CALL] = { true, INSTR_FMT_IBC00, HAS_ARG_FLAG | HAS_EVAL_BREAK_FLAG | HAS_ERROR_FLAG | HAS_ERROR_NO_POP_FLAG | HAS_ESCAPES_FLAG | HAS_NEEDS_GUARD_IP_FLAG },
+ [CALL_ALLOC_AND_ENTER_INIT] = { true, INSTR_FMT_IBC00, HAS_ARG_FLAG | HAS_DEOPT_FLAG | HAS_ERROR_FLAG | HAS_ERROR_NO_POP_FLAG | HAS_ESCAPES_FLAG | HAS_NEEDS_GUARD_IP_FLAG },
+ [CALL_BOUND_METHOD_EXACT_ARGS] = { true, INSTR_FMT_IBC00, HAS_ARG_FLAG | HAS_DEOPT_FLAG | HAS_EXIT_FLAG | HAS_ESCAPES_FLAG | HAS_NEEDS_GUARD_IP_FLAG },
+ [CALL_BOUND_METHOD_GENERAL] = { true, INSTR_FMT_IBC00, HAS_ARG_FLAG | HAS_DEOPT_FLAG | HAS_EXIT_FLAG | HAS_ERROR_FLAG | HAS_ERROR_NO_POP_FLAG | HAS_ESCAPES_FLAG | HAS_NEEDS_GUARD_IP_FLAG },
[CALL_BUILTIN_CLASS] = { true, INSTR_FMT_IBC00, HAS_ARG_FLAG | HAS_EVAL_BREAK_FLAG | HAS_DEOPT_FLAG | HAS_ERROR_FLAG | HAS_ESCAPES_FLAG },
[CALL_BUILTIN_FAST] = { true, INSTR_FMT_IBC00, HAS_ARG_FLAG | HAS_EVAL_BREAK_FLAG | HAS_DEOPT_FLAG | HAS_ERROR_FLAG | HAS_ESCAPES_FLAG },
[CALL_BUILTIN_FAST_WITH_KEYWORDS] = { true, INSTR_FMT_IBC00, HAS_ARG_FLAG | HAS_EVAL_BREAK_FLAG | HAS_DEOPT_FLAG | HAS_ERROR_FLAG | HAS_ESCAPES_FLAG },
[CALL_BUILTIN_O] = { true, INSTR_FMT_IBC00, HAS_ARG_FLAG | HAS_EVAL_BREAK_FLAG | HAS_EXIT_FLAG | HAS_ERROR_FLAG | HAS_ESCAPES_FLAG },
- [CALL_FUNCTION_EX] = { true, INSTR_FMT_IX, HAS_EVAL_BREAK_FLAG | HAS_ERROR_FLAG | HAS_ERROR_NO_POP_FLAG | HAS_ESCAPES_FLAG },
+ [CALL_FUNCTION_EX] = { true, INSTR_FMT_IX, HAS_EVAL_BREAK_FLAG | HAS_ERROR_FLAG | HAS_ERROR_NO_POP_FLAG | HAS_ESCAPES_FLAG | HAS_NEEDS_GUARD_IP_FLAG },
[CALL_INTRINSIC_1] = { true, INSTR_FMT_IB, HAS_ARG_FLAG | HAS_ERROR_FLAG | HAS_ESCAPES_FLAG },
[CALL_INTRINSIC_2] = { true, INSTR_FMT_IB, HAS_ARG_FLAG | HAS_ERROR_FLAG | HAS_ESCAPES_FLAG },
[CALL_ISINSTANCE] = { true, INSTR_FMT_IXC00, HAS_DEOPT_FLAG | HAS_ERROR_FLAG | HAS_ERROR_NO_POP_FLAG | HAS_ESCAPES_FLAG },
- [CALL_KW] = { true, INSTR_FMT_IBC00, HAS_ARG_FLAG | HAS_ERROR_FLAG | HAS_ERROR_NO_POP_FLAG | HAS_ESCAPES_FLAG },
- [CALL_KW_BOUND_METHOD] = { true, INSTR_FMT_IBC00, HAS_ARG_FLAG | HAS_DEOPT_FLAG | HAS_EXIT_FLAG | HAS_ERROR_FLAG | HAS_ESCAPES_FLAG },
+ [CALL_KW] = { true, INSTR_FMT_IBC00, HAS_ARG_FLAG | HAS_ERROR_FLAG | HAS_ERROR_NO_POP_FLAG | HAS_ESCAPES_FLAG | HAS_NEEDS_GUARD_IP_FLAG },
+ [CALL_KW_BOUND_METHOD] = { true, INSTR_FMT_IBC00, HAS_ARG_FLAG | HAS_DEOPT_FLAG | HAS_EXIT_FLAG | HAS_ERROR_FLAG | HAS_ESCAPES_FLAG | HAS_NEEDS_GUARD_IP_FLAG },
[CALL_KW_NON_PY] = { true, INSTR_FMT_IBC00, HAS_ARG_FLAG | HAS_EVAL_BREAK_FLAG | HAS_EXIT_FLAG | HAS_ERROR_FLAG | HAS_ESCAPES_FLAG },
- [CALL_KW_PY] = { true, INSTR_FMT_IBC00, HAS_ARG_FLAG | HAS_DEOPT_FLAG | HAS_EXIT_FLAG | HAS_ERROR_FLAG | HAS_ESCAPES_FLAG },
+ [CALL_KW_PY] = { true, INSTR_FMT_IBC00, HAS_ARG_FLAG | HAS_DEOPT_FLAG | HAS_EXIT_FLAG | HAS_ERROR_FLAG | HAS_ESCAPES_FLAG | HAS_NEEDS_GUARD_IP_FLAG },
[CALL_LEN] = { true, INSTR_FMT_IXC00, HAS_DEOPT_FLAG | HAS_ERROR_FLAG | HAS_ERROR_NO_POP_FLAG | HAS_ESCAPES_FLAG },
[CALL_LIST_APPEND] = { true, INSTR_FMT_IBC00, HAS_ARG_FLAG | HAS_DEOPT_FLAG | HAS_EXIT_FLAG | HAS_ERROR_FLAG | HAS_ESCAPES_FLAG },
[CALL_METHOD_DESCRIPTOR_FAST] = { true, INSTR_FMT_IBC00, HAS_ARG_FLAG | HAS_EVAL_BREAK_FLAG | HAS_EXIT_FLAG | HAS_ERROR_FLAG | HAS_ESCAPES_FLAG },
@@ -1117,8 +1125,8 @@ const struct opcode_metadata _PyOpcode_opcode_metadata[267] = {
[CALL_METHOD_DESCRIPTOR_NOARGS] = { true, INSTR_FMT_IBC00, HAS_ARG_FLAG | HAS_EVAL_BREAK_FLAG | HAS_EXIT_FLAG | HAS_ERROR_FLAG | HAS_ESCAPES_FLAG },
[CALL_METHOD_DESCRIPTOR_O] = { true, INSTR_FMT_IBC00, HAS_ARG_FLAG | HAS_EVAL_BREAK_FLAG | HAS_EXIT_FLAG | HAS_ERROR_FLAG | HAS_ESCAPES_FLAG },
[CALL_NON_PY_GENERAL] = { true, INSTR_FMT_IBC00, HAS_ARG_FLAG | HAS_EVAL_BREAK_FLAG | HAS_EXIT_FLAG | HAS_ERROR_FLAG | HAS_ESCAPES_FLAG },
- [CALL_PY_EXACT_ARGS] = { true, INSTR_FMT_IBC00, HAS_ARG_FLAG | HAS_DEOPT_FLAG | HAS_EXIT_FLAG },
- [CALL_PY_GENERAL] = { true, INSTR_FMT_IBC00, HAS_ARG_FLAG | HAS_DEOPT_FLAG | HAS_EXIT_FLAG | HAS_ERROR_FLAG | HAS_ERROR_NO_POP_FLAG | HAS_ESCAPES_FLAG },
+ [CALL_PY_EXACT_ARGS] = { true, INSTR_FMT_IBC00, HAS_ARG_FLAG | HAS_DEOPT_FLAG | HAS_EXIT_FLAG | HAS_NEEDS_GUARD_IP_FLAG },
+ [CALL_PY_GENERAL] = { true, INSTR_FMT_IBC00, HAS_ARG_FLAG | HAS_DEOPT_FLAG | HAS_EXIT_FLAG | HAS_ERROR_FLAG | HAS_ERROR_NO_POP_FLAG | HAS_ESCAPES_FLAG | HAS_NEEDS_GUARD_IP_FLAG },
[CALL_STR_1] = { true, INSTR_FMT_IBC00, HAS_ARG_FLAG | HAS_EVAL_BREAK_FLAG | HAS_DEOPT_FLAG | HAS_ERROR_FLAG | HAS_ESCAPES_FLAG },
[CALL_TUPLE_1] = { true, INSTR_FMT_IBC00, HAS_ARG_FLAG | HAS_EVAL_BREAK_FLAG | HAS_DEOPT_FLAG | HAS_ERROR_FLAG | HAS_ESCAPES_FLAG },
[CALL_TYPE_1] = { true, INSTR_FMT_IBC00, HAS_ARG_FLAG | HAS_DEOPT_FLAG | HAS_ESCAPES_FLAG },
@@ -1143,7 +1151,7 @@ const struct opcode_metadata _PyOpcode_opcode_metadata[267] = {
[DELETE_SUBSCR] = { true, INSTR_FMT_IX, HAS_ERROR_FLAG | HAS_ESCAPES_FLAG },
[DICT_MERGE] = { true, INSTR_FMT_IB, HAS_ARG_FLAG | HAS_ERROR_FLAG | HAS_ESCAPES_FLAG },
[DICT_UPDATE] = { true, INSTR_FMT_IB, HAS_ARG_FLAG | HAS_ERROR_FLAG | HAS_ESCAPES_FLAG },
- [END_ASYNC_FOR] = { true, INSTR_FMT_IB, HAS_ARG_FLAG | HAS_JUMP_FLAG | HAS_ERROR_FLAG | HAS_ERROR_NO_POP_FLAG | HAS_ESCAPES_FLAG },
+ [END_ASYNC_FOR] = { true, INSTR_FMT_IB, HAS_ARG_FLAG | HAS_JUMP_FLAG | HAS_ERROR_FLAG | HAS_ERROR_NO_POP_FLAG | HAS_ESCAPES_FLAG | HAS_UNPREDICTABLE_JUMP_FLAG | HAS_NEEDS_GUARD_IP_FLAG },
[END_FOR] = { true, INSTR_FMT_IX, HAS_ESCAPES_FLAG | HAS_NO_SAVE_IP_FLAG },
[END_SEND] = { true, INSTR_FMT_IX, HAS_ESCAPES_FLAG | HAS_PURE_FLAG },
[ENTER_EXECUTOR] = { true, INSTR_FMT_IB, HAS_ARG_FLAG },
@@ -1151,11 +1159,11 @@ const struct opcode_metadata _PyOpcode_opcode_metadata[267] = {
[EXTENDED_ARG] = { true, INSTR_FMT_IB, HAS_ARG_FLAG },
[FORMAT_SIMPLE] = { true, INSTR_FMT_IX, HAS_ERROR_FLAG | HAS_ESCAPES_FLAG },
[FORMAT_WITH_SPEC] = { true, INSTR_FMT_IX, HAS_ERROR_FLAG | HAS_ESCAPES_FLAG },
- [FOR_ITER] = { true, INSTR_FMT_IBC, HAS_ARG_FLAG | HAS_JUMP_FLAG | HAS_ERROR_FLAG | HAS_ERROR_NO_POP_FLAG | HAS_ESCAPES_FLAG },
- [FOR_ITER_GEN] = { true, INSTR_FMT_IBC, HAS_ARG_FLAG | HAS_DEOPT_FLAG },
- [FOR_ITER_LIST] = { true, INSTR_FMT_IBC, HAS_ARG_FLAG | HAS_JUMP_FLAG | HAS_DEOPT_FLAG | HAS_EXIT_FLAG | HAS_ESCAPES_FLAG },
- [FOR_ITER_RANGE] = { true, INSTR_FMT_IBC, HAS_ARG_FLAG | HAS_JUMP_FLAG | HAS_EXIT_FLAG | HAS_ERROR_FLAG },
- [FOR_ITER_TUPLE] = { true, INSTR_FMT_IBC, HAS_ARG_FLAG | HAS_JUMP_FLAG | HAS_EXIT_FLAG },
+ [FOR_ITER] = { true, INSTR_FMT_IBC, HAS_ARG_FLAG | HAS_JUMP_FLAG | HAS_ERROR_FLAG | HAS_ERROR_NO_POP_FLAG | HAS_ESCAPES_FLAG | HAS_UNPREDICTABLE_JUMP_FLAG },
+ [FOR_ITER_GEN] = { true, INSTR_FMT_IBC, HAS_ARG_FLAG | HAS_DEOPT_FLAG | HAS_NEEDS_GUARD_IP_FLAG },
+ [FOR_ITER_LIST] = { true, INSTR_FMT_IBC, HAS_ARG_FLAG | HAS_JUMP_FLAG | HAS_DEOPT_FLAG | HAS_EXIT_FLAG | HAS_ESCAPES_FLAG | HAS_UNPREDICTABLE_JUMP_FLAG },
+ [FOR_ITER_RANGE] = { true, INSTR_FMT_IBC, HAS_ARG_FLAG | HAS_JUMP_FLAG | HAS_EXIT_FLAG | HAS_ERROR_FLAG | HAS_UNPREDICTABLE_JUMP_FLAG },
+ [FOR_ITER_TUPLE] = { true, INSTR_FMT_IBC, HAS_ARG_FLAG | HAS_JUMP_FLAG | HAS_EXIT_FLAG | HAS_UNPREDICTABLE_JUMP_FLAG },
[GET_AITER] = { true, INSTR_FMT_IX, HAS_ERROR_FLAG | HAS_ESCAPES_FLAG },
[GET_ANEXT] = { true, INSTR_FMT_IX, HAS_ERROR_FLAG | HAS_ERROR_NO_POP_FLAG | HAS_ESCAPES_FLAG },
[GET_AWAITABLE] = { true, INSTR_FMT_IB, HAS_ARG_FLAG | HAS_ERROR_FLAG | HAS_ESCAPES_FLAG },
@@ -1164,13 +1172,13 @@ const struct opcode_metadata _PyOpcode_opcode_metadata[267] = {
[GET_YIELD_FROM_ITER] = { true, INSTR_FMT_IX, HAS_ERROR_FLAG | HAS_ERROR_NO_POP_FLAG | HAS_ESCAPES_FLAG },
[IMPORT_FROM] = { true, INSTR_FMT_IB, HAS_ARG_FLAG | HAS_NAME_FLAG | HAS_ERROR_FLAG | HAS_ESCAPES_FLAG },
[IMPORT_NAME] = { true, INSTR_FMT_IB, HAS_ARG_FLAG | HAS_NAME_FLAG | HAS_ERROR_FLAG | HAS_ESCAPES_FLAG },
- [INSTRUMENTED_CALL] = { true, INSTR_FMT_IBC00, HAS_ARG_FLAG | HAS_EVAL_BREAK_FLAG | HAS_ERROR_FLAG | HAS_ERROR_NO_POP_FLAG | HAS_ESCAPES_FLAG },
- [INSTRUMENTED_CALL_FUNCTION_EX] = { true, INSTR_FMT_IX, HAS_EVAL_BREAK_FLAG | HAS_ERROR_FLAG | HAS_ERROR_NO_POP_FLAG | HAS_ESCAPES_FLAG },
- [INSTRUMENTED_CALL_KW] = { true, INSTR_FMT_IBC00, HAS_ARG_FLAG | HAS_ERROR_FLAG | HAS_ERROR_NO_POP_FLAG | HAS_ESCAPES_FLAG },
- [INSTRUMENTED_END_ASYNC_FOR] = { true, INSTR_FMT_IB, HAS_ARG_FLAG | HAS_JUMP_FLAG | HAS_ERROR_FLAG | HAS_ERROR_NO_POP_FLAG | HAS_ESCAPES_FLAG },
+ [INSTRUMENTED_CALL] = { true, INSTR_FMT_IBC00, HAS_ARG_FLAG | HAS_EVAL_BREAK_FLAG | HAS_ERROR_FLAG | HAS_ERROR_NO_POP_FLAG | HAS_ESCAPES_FLAG | HAS_NEEDS_GUARD_IP_FLAG },
+ [INSTRUMENTED_CALL_FUNCTION_EX] = { true, INSTR_FMT_IX, HAS_EVAL_BREAK_FLAG | HAS_ERROR_FLAG | HAS_ERROR_NO_POP_FLAG | HAS_ESCAPES_FLAG | HAS_NEEDS_GUARD_IP_FLAG },
+ [INSTRUMENTED_CALL_KW] = { true, INSTR_FMT_IBC00, HAS_ARG_FLAG | HAS_ERROR_FLAG | HAS_ERROR_NO_POP_FLAG | HAS_ESCAPES_FLAG | HAS_NEEDS_GUARD_IP_FLAG },
+ [INSTRUMENTED_END_ASYNC_FOR] = { true, INSTR_FMT_IB, HAS_ARG_FLAG | HAS_JUMP_FLAG | HAS_ERROR_FLAG | HAS_ERROR_NO_POP_FLAG | HAS_ESCAPES_FLAG | HAS_UNPREDICTABLE_JUMP_FLAG | HAS_NEEDS_GUARD_IP_FLAG },
[INSTRUMENTED_END_FOR] = { true, INSTR_FMT_IX, HAS_ERROR_FLAG | HAS_ERROR_NO_POP_FLAG | HAS_ESCAPES_FLAG | HAS_NO_SAVE_IP_FLAG },
[INSTRUMENTED_END_SEND] = { true, INSTR_FMT_IX, HAS_ERROR_FLAG | HAS_ERROR_NO_POP_FLAG | HAS_ESCAPES_FLAG },
- [INSTRUMENTED_FOR_ITER] = { true, INSTR_FMT_IBC, HAS_ARG_FLAG | HAS_JUMP_FLAG | HAS_ERROR_FLAG | HAS_ERROR_NO_POP_FLAG | HAS_ESCAPES_FLAG },
+ [INSTRUMENTED_FOR_ITER] = { true, INSTR_FMT_IBC, HAS_ARG_FLAG | HAS_JUMP_FLAG | HAS_ERROR_FLAG | HAS_ERROR_NO_POP_FLAG | HAS_ESCAPES_FLAG | HAS_UNPREDICTABLE_JUMP_FLAG | HAS_NEEDS_GUARD_IP_FLAG },
[INSTRUMENTED_INSTRUCTION] = { true, INSTR_FMT_IX, HAS_ERROR_FLAG | HAS_ESCAPES_FLAG },
[INSTRUMENTED_JUMP_BACKWARD] = { true, INSTR_FMT_IBC, HAS_ARG_FLAG | HAS_EVAL_BREAK_FLAG | HAS_ERROR_FLAG | HAS_ESCAPES_FLAG },
[INSTRUMENTED_JUMP_FORWARD] = { true, INSTR_FMT_IB, HAS_ARG_FLAG },
@@ -1183,8 +1191,8 @@ const struct opcode_metadata _PyOpcode_opcode_metadata[267] = {
[INSTRUMENTED_POP_JUMP_IF_NOT_NONE] = { true, INSTR_FMT_IBC, HAS_ARG_FLAG | HAS_ESCAPES_FLAG },
[INSTRUMENTED_POP_JUMP_IF_TRUE] = { true, INSTR_FMT_IBC, HAS_ARG_FLAG },
[INSTRUMENTED_RESUME] = { true, INSTR_FMT_IB, HAS_ARG_FLAG | HAS_EVAL_BREAK_FLAG | HAS_ERROR_FLAG | HAS_ERROR_NO_POP_FLAG | HAS_ESCAPES_FLAG },
- [INSTRUMENTED_RETURN_VALUE] = { true, INSTR_FMT_IX, HAS_ERROR_FLAG | HAS_ESCAPES_FLAG },
- [INSTRUMENTED_YIELD_VALUE] = { true, INSTR_FMT_IB, HAS_ARG_FLAG | HAS_ERROR_FLAG | HAS_ERROR_NO_POP_FLAG | HAS_ESCAPES_FLAG },
+ [INSTRUMENTED_RETURN_VALUE] = { true, INSTR_FMT_IX, HAS_ERROR_FLAG | HAS_ESCAPES_FLAG | HAS_NEEDS_GUARD_IP_FLAG },
+ [INSTRUMENTED_YIELD_VALUE] = { true, INSTR_FMT_IB, HAS_ARG_FLAG | HAS_ERROR_FLAG | HAS_ERROR_NO_POP_FLAG | HAS_ESCAPES_FLAG | HAS_NEEDS_GUARD_IP_FLAG },
[INTERPRETER_EXIT] = { true, INSTR_FMT_IX, HAS_ESCAPES_FLAG },
[IS_OP] = { true, INSTR_FMT_IB, HAS_ARG_FLAG | HAS_ESCAPES_FLAG },
[JUMP_BACKWARD] = { true, INSTR_FMT_IBC, HAS_ARG_FLAG | HAS_JUMP_FLAG | HAS_EVAL_BREAK_FLAG | HAS_ERROR_FLAG | HAS_ESCAPES_FLAG },
@@ -1197,7 +1205,7 @@ const struct opcode_metadata _PyOpcode_opcode_metadata[267] = {
[LOAD_ATTR] = { true, INSTR_FMT_IBC00000000, HAS_ARG_FLAG | HAS_NAME_FLAG | HAS_ERROR_FLAG | HAS_ESCAPES_FLAG },
[LOAD_ATTR_CLASS] = { true, INSTR_FMT_IBC00000000, HAS_ARG_FLAG | HAS_EXIT_FLAG | HAS_ESCAPES_FLAG },
[LOAD_ATTR_CLASS_WITH_METACLASS_CHECK] = { true, INSTR_FMT_IBC00000000, HAS_ARG_FLAG | HAS_EXIT_FLAG | HAS_ESCAPES_FLAG },
- [LOAD_ATTR_GETATTRIBUTE_OVERRIDDEN] = { true, INSTR_FMT_IBC00000000, HAS_ARG_FLAG | HAS_NAME_FLAG | HAS_DEOPT_FLAG },
+ [LOAD_ATTR_GETATTRIBUTE_OVERRIDDEN] = { true, INSTR_FMT_IBC00000000, HAS_ARG_FLAG | HAS_NAME_FLAG | HAS_DEOPT_FLAG | HAS_NEEDS_GUARD_IP_FLAG },
[LOAD_ATTR_INSTANCE_VALUE] = { true, INSTR_FMT_IBC00000000, HAS_ARG_FLAG | HAS_DEOPT_FLAG | HAS_EXIT_FLAG | HAS_ESCAPES_FLAG },
[LOAD_ATTR_METHOD_LAZY_DICT] = { true, INSTR_FMT_IBC00000000, HAS_ARG_FLAG | HAS_DEOPT_FLAG | HAS_EXIT_FLAG },
[LOAD_ATTR_METHOD_NO_DICT] = { true, INSTR_FMT_IBC00000000, HAS_ARG_FLAG | HAS_EXIT_FLAG },
@@ -1205,7 +1213,7 @@ const struct opcode_metadata _PyOpcode_opcode_metadata[267] = {
[LOAD_ATTR_MODULE] = { true, INSTR_FMT_IBC00000000, HAS_ARG_FLAG | HAS_DEOPT_FLAG | HAS_ESCAPES_FLAG },
[LOAD_ATTR_NONDESCRIPTOR_NO_DICT] = { true, INSTR_FMT_IBC00000000, HAS_ARG_FLAG | HAS_EXIT_FLAG | HAS_ESCAPES_FLAG },
[LOAD_ATTR_NONDESCRIPTOR_WITH_VALUES] = { true, INSTR_FMT_IBC00000000, HAS_ARG_FLAG | HAS_DEOPT_FLAG | HAS_EXIT_FLAG | HAS_ESCAPES_FLAG },
- [LOAD_ATTR_PROPERTY] = { true, INSTR_FMT_IBC00000000, HAS_ARG_FLAG | HAS_DEOPT_FLAG | HAS_EXIT_FLAG },
+ [LOAD_ATTR_PROPERTY] = { true, INSTR_FMT_IBC00000000, HAS_ARG_FLAG | HAS_DEOPT_FLAG | HAS_EXIT_FLAG | HAS_NEEDS_GUARD_IP_FLAG },
[LOAD_ATTR_SLOT] = { true, INSTR_FMT_IBC00000000, HAS_ARG_FLAG | HAS_DEOPT_FLAG | HAS_EXIT_FLAG | HAS_ESCAPES_FLAG },
[LOAD_ATTR_WITH_HINT] = { true, INSTR_FMT_IBC00000000, HAS_ARG_FLAG | HAS_NAME_FLAG | HAS_DEOPT_FLAG | HAS_EXIT_FLAG | HAS_ESCAPES_FLAG },
[LOAD_BUILD_CLASS] = { true, INSTR_FMT_IX, HAS_ERROR_FLAG | HAS_ESCAPES_FLAG },
@@ -1253,10 +1261,10 @@ const struct opcode_metadata _PyOpcode_opcode_metadata[267] = {
[RESERVED] = { true, INSTR_FMT_IX, 0 },
[RESUME] = { true, INSTR_FMT_IB, HAS_ARG_FLAG | HAS_EVAL_BREAK_FLAG | HAS_ERROR_FLAG | HAS_ERROR_NO_POP_FLAG | HAS_ESCAPES_FLAG },
[RESUME_CHECK] = { true, INSTR_FMT_IX, HAS_DEOPT_FLAG },
- [RETURN_GENERATOR] = { true, INSTR_FMT_IX, HAS_ERROR_FLAG | HAS_ESCAPES_FLAG },
- [RETURN_VALUE] = { true, INSTR_FMT_IX, HAS_ESCAPES_FLAG },
- [SEND] = { true, INSTR_FMT_IBC, HAS_ARG_FLAG | HAS_JUMP_FLAG | HAS_ERROR_FLAG | HAS_ESCAPES_FLAG },
- [SEND_GEN] = { true, INSTR_FMT_IBC, HAS_ARG_FLAG | HAS_DEOPT_FLAG },
+ [RETURN_GENERATOR] = { true, INSTR_FMT_IX, HAS_ERROR_FLAG | HAS_ESCAPES_FLAG | HAS_NEEDS_GUARD_IP_FLAG },
+ [RETURN_VALUE] = { true, INSTR_FMT_IX, HAS_ESCAPES_FLAG | HAS_NEEDS_GUARD_IP_FLAG },
+ [SEND] = { true, INSTR_FMT_IBC, HAS_ARG_FLAG | HAS_JUMP_FLAG | HAS_ERROR_FLAG | HAS_ESCAPES_FLAG | HAS_UNPREDICTABLE_JUMP_FLAG | HAS_NEEDS_GUARD_IP_FLAG },
+ [SEND_GEN] = { true, INSTR_FMT_IBC, HAS_ARG_FLAG | HAS_DEOPT_FLAG | HAS_NEEDS_GUARD_IP_FLAG },
[SETUP_ANNOTATIONS] = { true, INSTR_FMT_IX, HAS_ERROR_FLAG | HAS_ESCAPES_FLAG },
[SET_ADD] = { true, INSTR_FMT_IB, HAS_ARG_FLAG | HAS_ERROR_FLAG | HAS_ESCAPES_FLAG },
[SET_FUNCTION_ATTRIBUTE] = { true, INSTR_FMT_IB, HAS_ARG_FLAG },
@@ -1283,6 +1291,7 @@ const struct opcode_metadata _PyOpcode_opcode_metadata[267] = {
[TO_BOOL_LIST] = { true, INSTR_FMT_IXC00, HAS_EXIT_FLAG | HAS_ESCAPES_FLAG },
[TO_BOOL_NONE] = { true, INSTR_FMT_IXC00, HAS_EXIT_FLAG },
[TO_BOOL_STR] = { true, INSTR_FMT_IXC00, HAS_EXIT_FLAG | HAS_ESCAPES_FLAG },
+ [TRACE_RECORD] = { true, INSTR_FMT_IB, HAS_ARG_FLAG | HAS_ERROR_FLAG | HAS_ESCAPES_FLAG },
[UNARY_INVERT] = { true, INSTR_FMT_IX, HAS_ERROR_FLAG | HAS_ESCAPES_FLAG },
[UNARY_NEGATIVE] = { true, INSTR_FMT_IX, HAS_ERROR_FLAG | HAS_ESCAPES_FLAG },
[UNARY_NOT] = { true, INSTR_FMT_IX, HAS_PURE_FLAG },
@@ -1292,7 +1301,7 @@ const struct opcode_metadata _PyOpcode_opcode_metadata[267] = {
[UNPACK_SEQUENCE_TUPLE] = { true, INSTR_FMT_IBC, HAS_ARG_FLAG | HAS_DEOPT_FLAG | HAS_EXIT_FLAG | HAS_ESCAPES_FLAG },
[UNPACK_SEQUENCE_TWO_TUPLE] = { true, INSTR_FMT_IBC, HAS_ARG_FLAG | HAS_DEOPT_FLAG | HAS_EXIT_FLAG | HAS_ESCAPES_FLAG },
[WITH_EXCEPT_START] = { true, INSTR_FMT_IX, HAS_ERROR_FLAG | HAS_ESCAPES_FLAG },
- [YIELD_VALUE] = { true, INSTR_FMT_IB, HAS_ARG_FLAG },
+ [YIELD_VALUE] = { true, INSTR_FMT_IB, HAS_ARG_FLAG | HAS_NEEDS_GUARD_IP_FLAG },
[ANNOTATIONS_PLACEHOLDER] = { true, -1, HAS_PURE_FLAG },
[JUMP] = { true, -1, HAS_ARG_FLAG | HAS_JUMP_FLAG | HAS_EVAL_BREAK_FLAG | HAS_ERROR_FLAG | HAS_ESCAPES_FLAG },
[JUMP_IF_FALSE] = { true, -1, HAS_ARG_FLAG | HAS_JUMP_FLAG | HAS_ERROR_FLAG | HAS_ESCAPES_FLAG },
@@ -1406,6 +1415,9 @@ _PyOpcode_macro_expansion[256] = {
[IMPORT_FROM] = { .nuops = 1, .uops = { { _IMPORT_FROM, OPARG_SIMPLE, 0 } } },
[IMPORT_NAME] = { .nuops = 1, .uops = { { _IMPORT_NAME, OPARG_SIMPLE, 0 } } },
[IS_OP] = { .nuops = 1, .uops = { { _IS_OP, OPARG_SIMPLE, 0 } } },
+ [JUMP_BACKWARD] = { .nuops = 2, .uops = { { _CHECK_PERIODIC, OPARG_SIMPLE, 1 }, { _JUMP_BACKWARD_NO_INTERRUPT, OPARG_REPLACED, 1 } } },
+ [JUMP_BACKWARD_NO_INTERRUPT] = { .nuops = 1, .uops = { { _JUMP_BACKWARD_NO_INTERRUPT, OPARG_REPLACED, 0 } } },
+ [JUMP_BACKWARD_NO_JIT] = { .nuops = 2, .uops = { { _CHECK_PERIODIC, OPARG_SIMPLE, 1 }, { _JUMP_BACKWARD_NO_INTERRUPT, OPARG_REPLACED, 1 } } },
[LIST_APPEND] = { .nuops = 1, .uops = { { _LIST_APPEND, OPARG_SIMPLE, 0 } } },
[LIST_EXTEND] = { .nuops = 1, .uops = { { _LIST_EXTEND, OPARG_SIMPLE, 0 } } },
[LOAD_ATTR] = { .nuops = 1, .uops = { { _LOAD_ATTR, OPARG_SIMPLE, 8 } } },
@@ -1731,6 +1743,7 @@ const char *_PyOpcode_OpName[267] = {
[TO_BOOL_LIST] = "TO_BOOL_LIST",
[TO_BOOL_NONE] = "TO_BOOL_NONE",
[TO_BOOL_STR] = "TO_BOOL_STR",
+ [TRACE_RECORD] = "TRACE_RECORD",
[UNARY_INVERT] = "UNARY_INVERT",
[UNARY_NEGATIVE] = "UNARY_NEGATIVE",
[UNARY_NOT] = "UNARY_NOT",
@@ -1802,7 +1815,6 @@ const uint8_t _PyOpcode_Deopt[256] = {
[230] = 230,
[231] = 231,
[232] = 232,
- [233] = 233,
[BINARY_OP] = BINARY_OP,
[BINARY_OP_ADD_FLOAT] = BINARY_OP,
[BINARY_OP_ADD_INT] = BINARY_OP,
@@ -2018,6 +2030,7 @@ const uint8_t _PyOpcode_Deopt[256] = {
[TO_BOOL_LIST] = TO_BOOL,
[TO_BOOL_NONE] = TO_BOOL,
[TO_BOOL_STR] = TO_BOOL,
+ [TRACE_RECORD] = TRACE_RECORD,
[UNARY_INVERT] = UNARY_INVERT,
[UNARY_NEGATIVE] = UNARY_NEGATIVE,
[UNARY_NOT] = UNARY_NOT,
@@ -2063,7 +2076,6 @@ const uint8_t _PyOpcode_Deopt[256] = {
case 230: \
case 231: \
case 232: \
- case 233: \
;
struct pseudo_targets {
uint8_t as_sequence;
diff --git a/Include/internal/pycore_optimizer.h b/Include/internal/pycore_optimizer.h
index 8ed5436eb68..e7177552cf6 100644
--- a/Include/internal/pycore_optimizer.h
+++ b/Include/internal/pycore_optimizer.h
@@ -21,14 +21,6 @@ typedef struct _PyExecutorLinkListNode {
} _PyExecutorLinkListNode;
-/* Bloom filter with m = 256
- * https://en.wikipedia.org/wiki/Bloom_filter */
-#define _Py_BLOOM_FILTER_WORDS 8
-
-typedef struct {
- uint32_t bits[_Py_BLOOM_FILTER_WORDS];
-} _PyBloomFilter;
-
typedef struct {
uint8_t opcode;
uint8_t oparg;
@@ -44,7 +36,9 @@ typedef struct {
typedef struct _PyExitData {
uint32_t target;
- uint16_t index;
+ uint16_t index:14;
+ uint16_t is_dynamic:1;
+ uint16_t is_control_flow:1;
_Py_BackoffCounter temperature;
struct _PyExecutorObject *executor;
} _PyExitData;
@@ -94,9 +88,8 @@ PyAPI_FUNC(void) _Py_Executors_InvalidateCold(PyInterpreterState *interp);
// This value is arbitrary and was not optimized.
#define JIT_CLEANUP_THRESHOLD 1000
-#define TRACE_STACK_SIZE 5
-
-int _Py_uop_analyze_and_optimize(_PyInterpreterFrame *frame,
+int _Py_uop_analyze_and_optimize(
+ PyFunctionObject *func,
_PyUOpInstruction *trace, int trace_len, int curr_stackentries,
_PyBloomFilter *dependencies);
@@ -130,7 +123,7 @@ static inline uint16_t uop_get_error_target(const _PyUOpInstruction *inst)
#define TY_ARENA_SIZE (UOP_MAX_TRACE_LENGTH * 5)
// Need extras for root frame and for overflow frame (see TRACE_STACK_PUSH())
-#define MAX_ABSTRACT_FRAME_DEPTH (TRACE_STACK_SIZE + 2)
+#define MAX_ABSTRACT_FRAME_DEPTH (16)
// The maximum number of side exits that we can take before requiring forward
// progress (and inserting a new ENTER_EXECUTOR instruction). In practice, this
@@ -258,6 +251,7 @@ struct _Py_UOpsAbstractFrame {
int stack_len;
int locals_len;
PyFunctionObject *func;
+ PyCodeObject *code;
JitOptRef *stack_pointer;
JitOptRef *stack;
@@ -333,11 +327,11 @@ extern _Py_UOpsAbstractFrame *_Py_uop_frame_new(
int curr_stackentries,
JitOptRef *args,
int arg_len);
-extern int _Py_uop_frame_pop(JitOptContext *ctx);
+extern int _Py_uop_frame_pop(JitOptContext *ctx, PyCodeObject *co, int curr_stackentries);
PyAPI_FUNC(PyObject *) _Py_uop_symbols_test(PyObject *self, PyObject *ignored);
-PyAPI_FUNC(int) _PyOptimizer_Optimize(_PyInterpreterFrame *frame, _Py_CODEUNIT *start, _PyExecutorObject **exec_ptr, int chain_depth);
+PyAPI_FUNC(int) _PyOptimizer_Optimize(_PyInterpreterFrame *frame, PyThreadState *tstate);
static inline _PyExecutorObject *_PyExecutor_FromExit(_PyExitData *exit)
{
@@ -346,6 +340,7 @@ static inline _PyExecutorObject *_PyExecutor_FromExit(_PyExitData *exit)
}
extern _PyExecutorObject *_PyExecutor_GetColdExecutor(void);
+extern _PyExecutorObject *_PyExecutor_GetColdDynamicExecutor(void);
PyAPI_FUNC(void) _PyExecutor_ClearExit(_PyExitData *exit);
@@ -354,7 +349,9 @@ static inline int is_terminator(const _PyUOpInstruction *uop)
int opcode = uop->opcode;
return (
opcode == _EXIT_TRACE ||
- opcode == _JUMP_TO_TOP
+ opcode == _DEOPT ||
+ opcode == _JUMP_TO_TOP ||
+ opcode == _DYNAMIC_EXIT
);
}
@@ -365,6 +362,18 @@ PyAPI_FUNC(int) _PyDumpExecutors(FILE *out);
extern void _Py_ClearExecutorDeletionList(PyInterpreterState *interp);
#endif
+int _PyJit_translate_single_bytecode_to_trace(PyThreadState *tstate, _PyInterpreterFrame *frame, _Py_CODEUNIT *next_instr, int stop_tracing_opcode);
+
+PyAPI_FUNC(int)
+_PyJit_TryInitializeTracing(PyThreadState *tstate, _PyInterpreterFrame *frame,
+ _Py_CODEUNIT *curr_instr, _Py_CODEUNIT *start_instr,
+ _Py_CODEUNIT *close_loop_instr, int curr_stackdepth, int chain_depth, _PyExitData *exit,
+ int oparg);
+
+void _PyJit_FinalizeTracing(PyThreadState *tstate);
+
+void _PyJit_Tracer_InvalidateDependency(PyThreadState *old_tstate, void *obj);
+
#ifdef __cplusplus
}
#endif
diff --git a/Include/internal/pycore_parser.h b/Include/internal/pycore_parser.h
index 2885dee63dc..2c46f59ab7d 100644
--- a/Include/internal/pycore_parser.h
+++ b/Include/internal/pycore_parser.h
@@ -48,7 +48,8 @@ extern struct _mod* _PyParser_ASTFromString(
PyObject* filename,
int mode,
PyCompilerFlags *flags,
- PyArena *arena);
+ PyArena *arena,
+ PyObject *module);
extern struct _mod* _PyParser_ASTFromFile(
FILE *fp,
diff --git a/Include/internal/pycore_pyerrors.h b/Include/internal/pycore_pyerrors.h
index 2c2048f7e12..f80808fcc8c 100644
--- a/Include/internal/pycore_pyerrors.h
+++ b/Include/internal/pycore_pyerrors.h
@@ -123,7 +123,8 @@ extern void _PyErr_SetNone(PyThreadState *tstate, PyObject *exception);
extern PyObject* _PyErr_NoMemory(PyThreadState *tstate);
extern int _PyErr_EmitSyntaxWarning(PyObject *msg, PyObject *filename, int lineno, int col_offset,
- int end_lineno, int end_col_offset);
+ int end_lineno, int end_col_offset,
+ PyObject *module);
extern void _PyErr_RaiseSyntaxError(PyObject *msg, PyObject *filename, int lineno, int col_offset,
int end_lineno, int end_col_offset);
diff --git a/Include/internal/pycore_pymath.h b/Include/internal/pycore_pymath.h
index eea8996ba68..4fcac3aab8b 100644
--- a/Include/internal/pycore_pymath.h
+++ b/Include/internal/pycore_pymath.h
@@ -33,7 +33,7 @@ extern "C" {
static inline void _Py_ADJUST_ERANGE1(double x)
{
if (errno == 0) {
- if (x == Py_INFINITY || x == -Py_INFINITY) {
+ if (x == INFINITY || x == -INFINITY) {
errno = ERANGE;
}
}
@@ -44,8 +44,8 @@ static inline void _Py_ADJUST_ERANGE1(double x)
static inline void _Py_ADJUST_ERANGE2(double x, double y)
{
- if (x == Py_INFINITY || x == -Py_INFINITY ||
- y == Py_INFINITY || y == -Py_INFINITY)
+ if (x == INFINITY || x == -INFINITY ||
+ y == INFINITY || y == -INFINITY)
{
if (errno == 0) {
errno = ERANGE;
diff --git a/Include/internal/pycore_pymem.h b/Include/internal/pycore_pymem.h
index f3f2ae0a140..ed943b51056 100644
--- a/Include/internal/pycore_pymem.h
+++ b/Include/internal/pycore_pymem.h
@@ -54,15 +54,17 @@ static inline int _PyMem_IsPtrFreed(const void *ptr)
{
uintptr_t value = (uintptr_t)ptr;
#if SIZEOF_VOID_P == 8
- return (value == 0
+ return (value <= 0xff // NULL, 0x1, 0x2, ..., 0xff
|| value == (uintptr_t)0xCDCDCDCDCDCDCDCD
|| value == (uintptr_t)0xDDDDDDDDDDDDDDDD
- || value == (uintptr_t)0xFDFDFDFDFDFDFDFD);
+ || value == (uintptr_t)0xFDFDFDFDFDFDFDFD
+ || value >= (uintptr_t)0xFFFFFFFFFFFFFF00); // -0xff, ..., -2, -1
#elif SIZEOF_VOID_P == 4
- return (value == 0
+ return (value <= 0xff
|| value == (uintptr_t)0xCDCDCDCD
|| value == (uintptr_t)0xDDDDDDDD
- || value == (uintptr_t)0xFDFDFDFD);
+ || value == (uintptr_t)0xFDFDFDFD
+ || value >= (uintptr_t)0xFFFFFF00);
#else
# error "unknown pointer size"
#endif
diff --git a/Include/internal/pycore_pystate.h b/Include/internal/pycore_pystate.h
index cab458f8402..189a8dde9f0 100644
--- a/Include/internal/pycore_pystate.h
+++ b/Include/internal/pycore_pystate.h
@@ -331,7 +331,11 @@ _Py_RecursionLimit_GetMargin(PyThreadState *tstate)
_PyThreadStateImpl *_tstate = (_PyThreadStateImpl *)tstate;
assert(_tstate->c_stack_hard_limit != 0);
intptr_t here_addr = _Py_get_machine_stack_pointer();
+#if _Py_STACK_GROWS_DOWN
return Py_ARITHMETIC_RIGHT_SHIFT(intptr_t, here_addr - (intptr_t)_tstate->c_stack_soft_limit, _PyOS_STACK_MARGIN_SHIFT);
+#else
+ return Py_ARITHMETIC_RIGHT_SHIFT(intptr_t, (intptr_t)_tstate->c_stack_soft_limit - here_addr, _PyOS_STACK_MARGIN_SHIFT);
+#endif
}
#ifdef __cplusplus
diff --git a/Include/internal/pycore_pystats.h b/Include/internal/pycore_pystats.h
index f8af398a560..50ab21aa0f1 100644
--- a/Include/internal/pycore_pystats.h
+++ b/Include/internal/pycore_pystats.h
@@ -9,7 +9,7 @@ extern "C" {
#endif
#ifdef Py_STATS
-extern void _Py_StatsOn(void);
+extern int _Py_StatsOn(void);
extern void _Py_StatsOff(void);
extern void _Py_StatsClear(void);
extern int _Py_PrintSpecializationStats(int to_file);
diff --git a/Include/internal/pycore_pythonrun.h b/Include/internal/pycore_pythonrun.h
index c2832098ddb..04a557e1204 100644
--- a/Include/internal/pycore_pythonrun.h
+++ b/Include/internal/pycore_pythonrun.h
@@ -33,6 +33,12 @@ extern const char* _Py_SourceAsString(
PyCompilerFlags *cf,
PyObject **cmd_copy);
+extern PyObject * _Py_CompileStringObjectWithModule(
+ const char *str,
+ PyObject *filename, int start,
+ PyCompilerFlags *flags, int optimize,
+ PyObject *module);
+
/* Stack size, in "pointers". This must be large enough, so
* no two calls to check recursion depth are more than this far
@@ -54,6 +60,12 @@ extern const char* _Py_SourceAsString(
# define _PyOS_STACK_MARGIN_SHIFT (_PyOS_LOG2_STACK_MARGIN + 2)
#endif
+#ifdef _Py_THREAD_SANITIZER
+# define _PyOS_MIN_STACK_SIZE (_PyOS_STACK_MARGIN_BYTES * 6)
+#else
+# define _PyOS_MIN_STACK_SIZE (_PyOS_STACK_MARGIN_BYTES * 3)
+#endif
+
#ifdef __cplusplus
}
diff --git a/Include/internal/pycore_runtime_init_generated.h b/Include/internal/pycore_runtime_init_generated.h
index 50d82d0a365..a66c97f7f13 100644
--- a/Include/internal/pycore_runtime_init_generated.h
+++ b/Include/internal/pycore_runtime_init_generated.h
@@ -1321,10 +1321,12 @@ extern "C" {
INIT_STR(dot_locals, "."), \
INIT_STR(empty, ""), \
INIT_STR(format, ".format"), \
+ INIT_STR(gc, ""), \
INIT_STR(generic_base, ".generic_base"), \
INIT_STR(json_decoder, "json.decoder"), \
INIT_STR(kwdefaults, ".kwdefaults"), \
INIT_STR(list_err, "list index out of range"), \
+ INIT_STR(native, ""), \
INIT_STR(str_replace_inf, "1e309"), \
INIT_STR(type_params, ".type_params"), \
INIT_STR(utf_8, "utf-8"), \
@@ -1761,6 +1763,7 @@ extern "C" {
INIT_ID(fullerror), \
INIT_ID(func), \
INIT_ID(future), \
+ INIT_ID(gc), \
INIT_ID(generation), \
INIT_ID(get), \
INIT_ID(get_debug), \
@@ -1904,6 +1907,7 @@ extern "C" {
INIT_ID(name_from), \
INIT_ID(namespace_separator), \
INIT_ID(namespaces), \
+ INIT_ID(native), \
INIT_ID(ndigits), \
INIT_ID(nested), \
INIT_ID(new_file_name), \
@@ -2064,6 +2068,7 @@ extern "C" {
INIT_ID(symmetric_difference_update), \
INIT_ID(tabsize), \
INIT_ID(tag), \
+ INIT_ID(take_bytes), \
INIT_ID(target), \
INIT_ID(target_is_directory), \
INIT_ID(task), \
diff --git a/Include/internal/pycore_stackref.h b/Include/internal/pycore_stackref.h
index 15a703a0820..e59611c07fa 100644
--- a/Include/internal/pycore_stackref.h
+++ b/Include/internal/pycore_stackref.h
@@ -63,6 +63,8 @@ PyAPI_FUNC(PyObject *) _Py_stackref_get_object(_PyStackRef ref);
PyAPI_FUNC(PyObject *) _Py_stackref_close(_PyStackRef ref, const char *filename, int linenumber);
PyAPI_FUNC(_PyStackRef) _Py_stackref_create(PyObject *obj, uint16_t flags, const char *filename, int linenumber);
PyAPI_FUNC(void) _Py_stackref_record_borrow(_PyStackRef ref, const char *filename, int linenumber);
+PyAPI_FUNC(_PyStackRef) _Py_stackref_get_borrowed_from(_PyStackRef ref, const char *filename, int linenumber);
+PyAPI_FUNC(void) _Py_stackref_set_borrowed_from(_PyStackRef ref, _PyStackRef borrowed_from, const char *filename, int linenumber);
extern void _Py_stackref_associate(PyInterpreterState *interp, PyObject *obj, _PyStackRef ref);
static const _PyStackRef PyStackRef_NULL = { .index = 0 };
@@ -248,7 +250,12 @@ _PyStackRef_DUP(_PyStackRef ref, const char *filename, int linenumber)
} else {
flags = Py_TAG_REFCNT;
}
- return _Py_stackref_create(obj, flags, filename, linenumber);
+ _PyStackRef new_ref = _Py_stackref_create(obj, flags, filename, linenumber);
+ if (flags == Py_TAG_REFCNT && !_Py_IsImmortal(obj)) {
+ _PyStackRef borrowed_from = _Py_stackref_get_borrowed_from(ref, filename, linenumber);
+ _Py_stackref_set_borrowed_from(new_ref, borrowed_from, filename, linenumber);
+ }
+ return new_ref;
}
#define PyStackRef_DUP(REF) _PyStackRef_DUP(REF, __FILE__, __LINE__)
@@ -259,6 +266,7 @@ _PyStackRef_CLOSE_SPECIALIZED(_PyStackRef ref, destructor destruct, const char *
assert(!PyStackRef_IsNull(ref));
assert(!PyStackRef_IsTaggedInt(ref));
PyObject *obj = _Py_stackref_close(ref, filename, linenumber);
+ assert(Py_REFCNT(obj) > 0);
if (PyStackRef_RefcountOnObject(ref)) {
_Py_DECREF_SPECIALIZED(obj, destruct);
}
@@ -274,7 +282,11 @@ _PyStackRef_Borrow(_PyStackRef ref, const char *filename, int linenumber)
return ref;
}
PyObject *obj = _Py_stackref_get_object(ref);
- return _Py_stackref_create(obj, Py_TAG_REFCNT, filename, linenumber);
+ _PyStackRef new_ref = _Py_stackref_create(obj, Py_TAG_REFCNT, filename, linenumber);
+ if (!_Py_IsImmortal(obj)) {
+ _Py_stackref_set_borrowed_from(new_ref, ref, filename, linenumber);
+ }
+ return new_ref;
}
#define PyStackRef_Borrow(REF) _PyStackRef_Borrow((REF), __FILE__, __LINE__)
@@ -310,13 +322,22 @@ PyStackRef_IsHeapSafe(_PyStackRef ref)
static inline _PyStackRef
_PyStackRef_MakeHeapSafe(_PyStackRef ref, const char *filename, int linenumber)
{
- if (PyStackRef_IsHeapSafe(ref)) {
+ // Special references that can't be closed.
+ if (ref.index < INITIAL_STACKREF_INDEX) {
return ref;
}
+ bool heap_safe = PyStackRef_IsHeapSafe(ref);
PyObject *obj = _Py_stackref_close(ref, filename, linenumber);
- Py_INCREF(obj);
- return _Py_stackref_create(obj, 0, filename, linenumber);
+ uint16_t flags = 0;
+ if (heap_safe) {
+ // Close old ref and create a new one with the same flags.
+ // This is necessary for correct borrow checking.
+ flags = ref.index & Py_TAG_BITS;
+ } else {
+ Py_INCREF(obj);
+ }
+ return _Py_stackref_create(obj, flags, filename, linenumber);
}
#define PyStackRef_MakeHeapSafe(REF) _PyStackRef_MakeHeapSafe(REF, __FILE__, __LINE__)
diff --git a/Include/internal/pycore_stats.h b/Include/internal/pycore_stats.h
index 24f239a2135..850e6ea4552 100644
--- a/Include/internal/pycore_stats.h
+++ b/Include/internal/pycore_stats.h
@@ -15,39 +15,56 @@ extern "C" {
#include "pycore_bitutils.h" // _Py_bit_length
-#define STAT_INC(opname, name) do { if (_Py_stats) _Py_stats->opcode_stats[opname].specialization.name++; } while (0)
-#define STAT_DEC(opname, name) do { if (_Py_stats) _Py_stats->opcode_stats[opname].specialization.name--; } while (0)
-#define OPCODE_EXE_INC(opname) do { if (_Py_stats) _Py_stats->opcode_stats[opname].execution_count++; } while (0)
-#define CALL_STAT_INC(name) do { if (_Py_stats) _Py_stats->call_stats.name++; } while (0)
-#define OBJECT_STAT_INC(name) do { if (_Py_stats) _Py_stats->object_stats.name++; } while (0)
-#define OBJECT_STAT_INC_COND(name, cond) \
- do { if (_Py_stats && cond) _Py_stats->object_stats.name++; } while (0)
-#define EVAL_CALL_STAT_INC(name) do { if (_Py_stats) _Py_stats->call_stats.eval_calls[name]++; } while (0)
-#define EVAL_CALL_STAT_INC_IF_FUNCTION(name, callable) \
- do { if (_Py_stats && PyFunction_Check(callable)) _Py_stats->call_stats.eval_calls[name]++; } while (0)
-#define GC_STAT_ADD(gen, name, n) do { if (_Py_stats) _Py_stats->gc_stats[(gen)].name += (n); } while (0)
-#define OPT_STAT_INC(name) do { if (_Py_stats) _Py_stats->optimization_stats.name++; } while (0)
-#define OPT_STAT_ADD(name, n) do { if (_Py_stats) _Py_stats->optimization_stats.name += (n); } while (0)
-#define UOP_STAT_INC(opname, name) do { if (_Py_stats) { assert(opname < 512); _Py_stats->optimization_stats.opcode[opname].name++; } } while (0)
-#define UOP_PAIR_INC(uopcode, lastuop) \
- do { \
- if (lastuop && _Py_stats) { \
- _Py_stats->optimization_stats.opcode[lastuop].pair_count[uopcode]++; \
- } \
- lastuop = uopcode; \
- } while (0)
-#define OPT_UNSUPPORTED_OPCODE(opname) do { if (_Py_stats) _Py_stats->optimization_stats.unsupported_opcode[opname]++; } while (0)
-#define OPT_ERROR_IN_OPCODE(opname) do { if (_Py_stats) _Py_stats->optimization_stats.error_in_opcode[opname]++; } while (0)
-#define OPT_HIST(length, name) \
+#define STAT_INC(opname, name) _Py_STATS_EXPR(opcode_stats[opname].specialization.name++)
+#define STAT_DEC(opname, name) _Py_STATS_EXPR(opcode_stats[opname].specialization.name--)
+#define OPCODE_EXE_INC(opname) _Py_STATS_EXPR(opcode_stats[opname].execution_count++)
+#define CALL_STAT_INC(name) _Py_STATS_EXPR(call_stats.name++)
+#define OBJECT_STAT_INC(name) _Py_STATS_EXPR(object_stats.name++)
+#define OBJECT_STAT_INC_COND(name, cond) _Py_STATS_COND_EXPR(cond, object_stats.name++)
+#define EVAL_CALL_STAT_INC(name) _Py_STATS_EXPR(call_stats.eval_calls[name]++)
+#define EVAL_CALL_STAT_INC_IF_FUNCTION(name, callable) _Py_STATS_COND_EXPR(PyFunction_Check(callable), call_stats.eval_calls[name]++)
+#define GC_STAT_ADD(gen, name, n) _Py_STATS_EXPR(gc_stats[(gen)].name += (n))
+#define OPT_STAT_INC(name) _Py_STATS_EXPR(optimization_stats.name++)
+#define OPT_STAT_ADD(name, n) _Py_STATS_EXPR(optimization_stats.name += (n))
+#define UOP_STAT_INC(opname, name) \
do { \
- if (_Py_stats) { \
- int bucket = _Py_bit_length(length >= 1 ? length - 1 : 0); \
- bucket = (bucket >= _Py_UOP_HIST_SIZE) ? _Py_UOP_HIST_SIZE - 1 : bucket; \
- _Py_stats->optimization_stats.name[bucket]++; \
+ PyStats *s = _PyStats_GET(); \
+ if (s) { \
+ assert(opname < 512); \
+ s->optimization_stats.opcode[opname].name++; \
} \
} while (0)
-#define RARE_EVENT_STAT_INC(name) do { if (_Py_stats) _Py_stats->rare_event_stats.name++; } while (0)
-#define OPCODE_DEFERRED_INC(opname) do { if (_Py_stats && opcode == opname) _Py_stats->opcode_stats[opname].specialization.deferred++; } while (0)
+#define UOP_PAIR_INC(uopcode, lastuop) \
+ do { \
+ PyStats *s = _PyStats_GET(); \
+ if (lastuop && s) { \
+ s->optimization_stats.opcode[lastuop].pair_count[uopcode]++; \
+ } \
+ lastuop = uopcode; \
+ } while (0)
+#define OPT_UNSUPPORTED_OPCODE(opname) _Py_STATS_EXPR(optimization_stats.unsupported_opcode[opname]++)
+#define OPT_ERROR_IN_OPCODE(opname) _Py_STATS_EXPR(optimization_stats.error_in_opcode[opname]++)
+#define OPT_HIST(length, name) \
+ do { \
+ PyStats *s = _PyStats_GET(); \
+ if (s) { \
+ int bucket = _Py_bit_length(length >= 1 ? length - 1 : 0); \
+ bucket = (bucket >= _Py_UOP_HIST_SIZE) ? _Py_UOP_HIST_SIZE - 1 : bucket; \
+ s->optimization_stats.name[bucket]++; \
+ } \
+ } while (0)
+#define RARE_EVENT_STAT_INC(name) _Py_STATS_EXPR(rare_event_stats.name++)
+#define OPCODE_DEFERRED_INC(opname) _Py_STATS_COND_EXPR(opcode==opname, opcode_stats[opname].specialization.deferred++)
+
+#ifdef Py_GIL_DISABLED
+#define FT_STAT_MUTEX_SLEEP_INC() _Py_STATS_EXPR(ft_stats.mutex_sleeps++)
+#define FT_STAT_QSBR_POLL_INC() _Py_STATS_EXPR(ft_stats.qsbr_polls++)
+#define FT_STAT_WORLD_STOP_INC() _Py_STATS_EXPR(ft_stats.world_stops++)
+#else
+#define FT_STAT_MUTEX_SLEEP_INC()
+#define FT_STAT_QSBR_POLL_INC()
+#define FT_STAT_WORLD_STOP_INC()
+#endif
// Export for '_opcode' shared extension
PyAPI_FUNC(PyObject*) _Py_GetSpecializationStats(void);
@@ -71,6 +88,9 @@ PyAPI_FUNC(PyObject*) _Py_GetSpecializationStats(void);
#define OPT_HIST(length, name) ((void)0)
#define RARE_EVENT_STAT_INC(name) ((void)0)
#define OPCODE_DEFERRED_INC(opname) ((void)0)
+#define FT_STAT_MUTEX_SLEEP_INC()
+#define FT_STAT_QSBR_POLL_INC()
+#define FT_STAT_WORLD_STOP_INC()
#endif // !Py_STATS
@@ -90,6 +110,11 @@ PyAPI_FUNC(PyObject*) _Py_GetSpecializationStats(void);
RARE_EVENT_INTERP_INC(interp, name); \
} while (0); \
+PyStatus _PyStats_InterpInit(PyInterpreterState *);
+bool _PyStats_ThreadInit(PyInterpreterState *, _PyThreadStateImpl *);
+void _PyStats_ThreadFini(_PyThreadStateImpl *);
+void _PyStats_Attach(_PyThreadStateImpl *);
+void _PyStats_Detach(_PyThreadStateImpl *);
#ifdef __cplusplus
}
diff --git a/Include/internal/pycore_symtable.h b/Include/internal/pycore_symtable.h
index 98099b4a497..9dbfa913219 100644
--- a/Include/internal/pycore_symtable.h
+++ b/Include/internal/pycore_symtable.h
@@ -188,7 +188,8 @@ extern struct symtable* _Py_SymtableStringObjectFlags(
const char *str,
PyObject *filename,
int start,
- PyCompilerFlags *flags);
+ PyCompilerFlags *flags,
+ PyObject *module);
int _PyFuture_FromAST(
struct _mod * mod,
diff --git a/Include/internal/pycore_time.h b/Include/internal/pycore_time.h
index 23312471c65..b671225ca6e 100644
--- a/Include/internal/pycore_time.h
+++ b/Include/internal/pycore_time.h
@@ -147,11 +147,6 @@ extern int _PyTime_FromSecondsDouble(
// Clamp to [PyTime_MIN; PyTime_MAX] on overflow.
extern PyTime_t _PyTime_FromMicrosecondsClamp(PyTime_t us);
-// Create a timestamp from a Python int object (number of nanoseconds).
-// Export for '_lsprof' shared extension.
-PyAPI_FUNC(int) _PyTime_FromLong(PyTime_t *t,
- PyObject *obj);
-
// Convert a number of seconds (Python float or int) to a timestamp.
// Raise an exception and return -1 on error, return 0 on success.
// Export for '_socket' shared extension.
@@ -182,10 +177,6 @@ extern PyTime_t _PyTime_As100Nanoseconds(PyTime_t t,
_PyTime_round_t round);
#endif
-// Convert a timestamp (number of nanoseconds) as a Python int object.
-// Export for '_testinternalcapi' shared extension.
-PyAPI_FUNC(PyObject*) _PyTime_AsLong(PyTime_t t);
-
#ifndef MS_WINDOWS
// Create a timestamp from a timeval structure.
// Raise an exception and return -1 on overflow, return 0 on success.
diff --git a/Include/internal/pycore_tstate.h b/Include/internal/pycore_tstate.h
index bad968428c7..50048801b2e 100644
--- a/Include/internal/pycore_tstate.h
+++ b/Include/internal/pycore_tstate.h
@@ -12,7 +12,8 @@ extern "C" {
#include "pycore_freelist_state.h" // struct _Py_freelists
#include "pycore_mimalloc.h" // struct _mimalloc_thread_state
#include "pycore_qsbr.h" // struct qsbr
-
+#include "pycore_uop.h" // struct _PyUOpInstruction
+#include "pycore_structs.h"
#ifdef Py_GIL_DISABLED
struct _gc_thread_state {
@@ -21,6 +22,38 @@ struct _gc_thread_state {
};
#endif
+#if _Py_TIER2
+typedef struct _PyJitTracerInitialState {
+ int stack_depth;
+ int chain_depth;
+ struct _PyExitData *exit;
+ PyCodeObject *code; // Strong
+ PyFunctionObject *func; // Strong
+ _Py_CODEUNIT *start_instr;
+ _Py_CODEUNIT *close_loop_instr;
+ _Py_CODEUNIT *jump_backward_instr;
+} _PyJitTracerInitialState;
+
+typedef struct _PyJitTracerPreviousState {
+ bool dependencies_still_valid;
+ bool instr_is_super;
+ int code_max_size;
+ int code_curr_size;
+ int instr_oparg;
+ int instr_stacklevel;
+ _Py_CODEUNIT *instr;
+ PyCodeObject *instr_code; // Strong
+ struct _PyInterpreterFrame *instr_frame;
+ _PyBloomFilter dependencies;
+} _PyJitTracerPreviousState;
+
+typedef struct _PyJitTracerState {
+ _PyUOpInstruction *code_buffer;
+ _PyJitTracerInitialState initial_state;
+ _PyJitTracerPreviousState prev_state;
+} _PyJitTracerState;
+#endif
+
// Every PyThreadState is actually allocated as a _PyThreadStateImpl. The
// PyThreadState fields are exposed as part of the C API, although most fields
// are intended to be private. The _PyThreadStateImpl fields not exposed.
@@ -37,6 +70,10 @@ typedef struct _PyThreadStateImpl {
uintptr_t c_stack_soft_limit;
uintptr_t c_stack_hard_limit;
+ // PyUnstable_ThreadState_ResetStackProtection() values
+ uintptr_t c_stack_init_base;
+ uintptr_t c_stack_init_top;
+
PyObject *asyncio_running_loop; // Strong reference
PyObject *asyncio_running_task; // Strong reference
@@ -70,12 +107,20 @@ typedef struct _PyThreadStateImpl {
// When >1, code objects do not immortalize their non-string constants.
int suppress_co_const_immortalization;
+
+#ifdef Py_STATS
+ // per-thread stats, will be merged into interp->pystats_struct
+ PyStats *pystats_struct; // allocated by _PyStats_ThreadInit()
#endif
+#endif // Py_GIL_DISABLED
+
#if defined(Py_REF_DEBUG) && defined(Py_GIL_DISABLED)
Py_ssize_t reftotal; // this thread's total refcount operations
#endif
-
+#if _Py_TIER2
+ _PyJitTracerState jit_tracer_state;
+#endif
} _PyThreadStateImpl;
#ifdef __cplusplus
diff --git a/Include/internal/pycore_unicodeobject_generated.h b/Include/internal/pycore_unicodeobject_generated.h
index b4d920154b6..2061b1d2049 100644
--- a/Include/internal/pycore_unicodeobject_generated.h
+++ b/Include/internal/pycore_unicodeobject_generated.h
@@ -1732,6 +1732,10 @@ _PyUnicode_InitStaticStrings(PyInterpreterState *interp) {
_PyUnicode_InternStatic(interp, &string);
assert(_PyUnicode_CheckConsistency(string, 1));
assert(PyUnicode_GET_LENGTH(string) != 1);
+ string = &_Py_ID(gc);
+ _PyUnicode_InternStatic(interp, &string);
+ assert(_PyUnicode_CheckConsistency(string, 1));
+ assert(PyUnicode_GET_LENGTH(string) != 1);
string = &_Py_ID(generation);
_PyUnicode_InternStatic(interp, &string);
assert(_PyUnicode_CheckConsistency(string, 1));
@@ -2304,6 +2308,10 @@ _PyUnicode_InitStaticStrings(PyInterpreterState *interp) {
_PyUnicode_InternStatic(interp, &string);
assert(_PyUnicode_CheckConsistency(string, 1));
assert(PyUnicode_GET_LENGTH(string) != 1);
+ string = &_Py_ID(native);
+ _PyUnicode_InternStatic(interp, &string);
+ assert(_PyUnicode_CheckConsistency(string, 1));
+ assert(PyUnicode_GET_LENGTH(string) != 1);
string = &_Py_ID(ndigits);
_PyUnicode_InternStatic(interp, &string);
assert(_PyUnicode_CheckConsistency(string, 1));
@@ -2944,6 +2952,10 @@ _PyUnicode_InitStaticStrings(PyInterpreterState *interp) {
_PyUnicode_InternStatic(interp, &string);
assert(_PyUnicode_CheckConsistency(string, 1));
assert(PyUnicode_GET_LENGTH(string) != 1);
+ string = &_Py_ID(take_bytes);
+ _PyUnicode_InternStatic(interp, &string);
+ assert(_PyUnicode_CheckConsistency(string, 1));
+ assert(PyUnicode_GET_LENGTH(string) != 1);
string = &_Py_ID(target);
_PyUnicode_InternStatic(interp, &string);
assert(_PyUnicode_CheckConsistency(string, 1));
@@ -3236,6 +3248,10 @@ _PyUnicode_InitStaticStrings(PyInterpreterState *interp) {
_PyUnicode_InternStatic(interp, &string);
assert(_PyUnicode_CheckConsistency(string, 1));
assert(PyUnicode_GET_LENGTH(string) != 1);
+ string = &_Py_STR(gc);
+ _PyUnicode_InternStatic(interp, &string);
+ assert(_PyUnicode_CheckConsistency(string, 1));
+ assert(PyUnicode_GET_LENGTH(string) != 1);
string = &_Py_STR(anon_null);
_PyUnicode_InternStatic(interp, &string);
assert(_PyUnicode_CheckConsistency(string, 1));
@@ -3260,6 +3276,10 @@ _PyUnicode_InitStaticStrings(PyInterpreterState *interp) {
_PyUnicode_InternStatic(interp, &string);
assert(_PyUnicode_CheckConsistency(string, 1));
assert(PyUnicode_GET_LENGTH(string) != 1);
+ string = &_Py_STR(native);
+ _PyUnicode_InternStatic(interp, &string);
+ assert(_PyUnicode_CheckConsistency(string, 1));
+ assert(PyUnicode_GET_LENGTH(string) != 1);
string = &_Py_STR(anon_setcomp);
_PyUnicode_InternStatic(interp, &string);
assert(_PyUnicode_CheckConsistency(string, 1));
diff --git a/Include/internal/pycore_uop.h b/Include/internal/pycore_uop.h
index 4abefd3b95d..4e1b15af42c 100644
--- a/Include/internal/pycore_uop.h
+++ b/Include/internal/pycore_uop.h
@@ -35,10 +35,18 @@ typedef struct _PyUOpInstruction{
#endif
} _PyUOpInstruction;
-// This is the length of the trace we project initially.
-#define UOP_MAX_TRACE_LENGTH 1200
+// This is the length of the trace we translate initially.
+#define UOP_MAX_TRACE_LENGTH 3000
#define UOP_BUFFER_SIZE (UOP_MAX_TRACE_LENGTH * sizeof(_PyUOpInstruction))
+/* Bloom filter with m = 256
+ * https://en.wikipedia.org/wiki/Bloom_filter */
+#define _Py_BLOOM_FILTER_WORDS 8
+
+typedef struct {
+ uint32_t bits[_Py_BLOOM_FILTER_WORDS];
+} _PyBloomFilter;
+
#ifdef __cplusplus
}
#endif
diff --git a/Include/internal/pycore_uop_ids.h b/Include/internal/pycore_uop_ids.h
index ff1d75c0cb1..c38f28f9db1 100644
--- a/Include/internal/pycore_uop_ids.h
+++ b/Include/internal/pycore_uop_ids.h
@@ -81,101 +81,107 @@ extern "C" {
#define _CHECK_STACK_SPACE 357
#define _CHECK_STACK_SPACE_OPERAND 358
#define _CHECK_VALIDITY 359
-#define _COLD_EXIT 360
-#define _COMPARE_OP 361
-#define _COMPARE_OP_FLOAT 362
-#define _COMPARE_OP_INT 363
-#define _COMPARE_OP_STR 364
-#define _CONTAINS_OP 365
-#define _CONTAINS_OP_DICT 366
-#define _CONTAINS_OP_SET 367
+#define _COLD_DYNAMIC_EXIT 360
+#define _COLD_EXIT 361
+#define _COMPARE_OP 362
+#define _COMPARE_OP_FLOAT 363
+#define _COMPARE_OP_INT 364
+#define _COMPARE_OP_STR 365
+#define _CONTAINS_OP 366
+#define _CONTAINS_OP_DICT 367
+#define _CONTAINS_OP_SET 368
#define _CONVERT_VALUE CONVERT_VALUE
-#define _COPY 368
-#define _COPY_1 369
-#define _COPY_2 370
-#define _COPY_3 371
+#define _COPY 369
+#define _COPY_1 370
+#define _COPY_2 371
+#define _COPY_3 372
#define _COPY_FREE_VARS COPY_FREE_VARS
-#define _CREATE_INIT_FRAME 372
+#define _CREATE_INIT_FRAME 373
#define _DELETE_ATTR DELETE_ATTR
#define _DELETE_DEREF DELETE_DEREF
#define _DELETE_FAST DELETE_FAST
#define _DELETE_GLOBAL DELETE_GLOBAL
#define _DELETE_NAME DELETE_NAME
#define _DELETE_SUBSCR DELETE_SUBSCR
-#define _DEOPT 373
+#define _DEOPT 374
#define _DICT_MERGE DICT_MERGE
#define _DICT_UPDATE DICT_UPDATE
-#define _DO_CALL 374
-#define _DO_CALL_FUNCTION_EX 375
-#define _DO_CALL_KW 376
+#define _DO_CALL 375
+#define _DO_CALL_FUNCTION_EX 376
+#define _DO_CALL_KW 377
+#define _DYNAMIC_EXIT 378
#define _END_FOR END_FOR
#define _END_SEND END_SEND
-#define _ERROR_POP_N 377
+#define _ERROR_POP_N 379
#define _EXIT_INIT_CHECK EXIT_INIT_CHECK
-#define _EXPAND_METHOD 378
-#define _EXPAND_METHOD_KW 379
-#define _FATAL_ERROR 380
+#define _EXPAND_METHOD 380
+#define _EXPAND_METHOD_KW 381
+#define _FATAL_ERROR 382
#define _FORMAT_SIMPLE FORMAT_SIMPLE
#define _FORMAT_WITH_SPEC FORMAT_WITH_SPEC
-#define _FOR_ITER 381
-#define _FOR_ITER_GEN_FRAME 382
-#define _FOR_ITER_TIER_TWO 383
+#define _FOR_ITER 383
+#define _FOR_ITER_GEN_FRAME 384
+#define _FOR_ITER_TIER_TWO 385
#define _GET_AITER GET_AITER
#define _GET_ANEXT GET_ANEXT
#define _GET_AWAITABLE GET_AWAITABLE
#define _GET_ITER GET_ITER
#define _GET_LEN GET_LEN
#define _GET_YIELD_FROM_ITER GET_YIELD_FROM_ITER
-#define _GUARD_BINARY_OP_EXTEND 384
-#define _GUARD_CALLABLE_ISINSTANCE 385
-#define _GUARD_CALLABLE_LEN 386
-#define _GUARD_CALLABLE_LIST_APPEND 387
-#define _GUARD_CALLABLE_STR_1 388
-#define _GUARD_CALLABLE_TUPLE_1 389
-#define _GUARD_CALLABLE_TYPE_1 390
-#define _GUARD_DORV_NO_DICT 391
-#define _GUARD_DORV_VALUES_INST_ATTR_FROM_DICT 392
-#define _GUARD_GLOBALS_VERSION 393
-#define _GUARD_IS_FALSE_POP 394
-#define _GUARD_IS_NONE_POP 395
-#define _GUARD_IS_NOT_NONE_POP 396
-#define _GUARD_IS_TRUE_POP 397
-#define _GUARD_KEYS_VERSION 398
-#define _GUARD_NOS_DICT 399
-#define _GUARD_NOS_FLOAT 400
-#define _GUARD_NOS_INT 401
-#define _GUARD_NOS_LIST 402
-#define _GUARD_NOS_NOT_NULL 403
-#define _GUARD_NOS_NULL 404
-#define _GUARD_NOS_OVERFLOWED 405
-#define _GUARD_NOS_TUPLE 406
-#define _GUARD_NOS_UNICODE 407
-#define _GUARD_NOT_EXHAUSTED_LIST 408
-#define _GUARD_NOT_EXHAUSTED_RANGE 409
-#define _GUARD_NOT_EXHAUSTED_TUPLE 410
-#define _GUARD_THIRD_NULL 411
-#define _GUARD_TOS_ANY_SET 412
-#define _GUARD_TOS_DICT 413
-#define _GUARD_TOS_FLOAT 414
-#define _GUARD_TOS_INT 415
-#define _GUARD_TOS_LIST 416
-#define _GUARD_TOS_OVERFLOWED 417
-#define _GUARD_TOS_SLICE 418
-#define _GUARD_TOS_TUPLE 419
-#define _GUARD_TOS_UNICODE 420
-#define _GUARD_TYPE_VERSION 421
-#define _GUARD_TYPE_VERSION_AND_LOCK 422
-#define _HANDLE_PENDING_AND_DEOPT 423
+#define _GUARD_BINARY_OP_EXTEND 386
+#define _GUARD_CALLABLE_ISINSTANCE 387
+#define _GUARD_CALLABLE_LEN 388
+#define _GUARD_CALLABLE_LIST_APPEND 389
+#define _GUARD_CALLABLE_STR_1 390
+#define _GUARD_CALLABLE_TUPLE_1 391
+#define _GUARD_CALLABLE_TYPE_1 392
+#define _GUARD_DORV_NO_DICT 393
+#define _GUARD_DORV_VALUES_INST_ATTR_FROM_DICT 394
+#define _GUARD_GLOBALS_VERSION 395
+#define _GUARD_IP_RETURN_GENERATOR 396
+#define _GUARD_IP_RETURN_VALUE 397
+#define _GUARD_IP_YIELD_VALUE 398
+#define _GUARD_IP__PUSH_FRAME 399
+#define _GUARD_IS_FALSE_POP 400
+#define _GUARD_IS_NONE_POP 401
+#define _GUARD_IS_NOT_NONE_POP 402
+#define _GUARD_IS_TRUE_POP 403
+#define _GUARD_KEYS_VERSION 404
+#define _GUARD_NOS_DICT 405
+#define _GUARD_NOS_FLOAT 406
+#define _GUARD_NOS_INT 407
+#define _GUARD_NOS_LIST 408
+#define _GUARD_NOS_NOT_NULL 409
+#define _GUARD_NOS_NULL 410
+#define _GUARD_NOS_OVERFLOWED 411
+#define _GUARD_NOS_TUPLE 412
+#define _GUARD_NOS_UNICODE 413
+#define _GUARD_NOT_EXHAUSTED_LIST 414
+#define _GUARD_NOT_EXHAUSTED_RANGE 415
+#define _GUARD_NOT_EXHAUSTED_TUPLE 416
+#define _GUARD_THIRD_NULL 417
+#define _GUARD_TOS_ANY_SET 418
+#define _GUARD_TOS_DICT 419
+#define _GUARD_TOS_FLOAT 420
+#define _GUARD_TOS_INT 421
+#define _GUARD_TOS_LIST 422
+#define _GUARD_TOS_OVERFLOWED 423
+#define _GUARD_TOS_SLICE 424
+#define _GUARD_TOS_TUPLE 425
+#define _GUARD_TOS_UNICODE 426
+#define _GUARD_TYPE_VERSION 427
+#define _GUARD_TYPE_VERSION_AND_LOCK 428
+#define _HANDLE_PENDING_AND_DEOPT 429
#define _IMPORT_FROM IMPORT_FROM
#define _IMPORT_NAME IMPORT_NAME
-#define _INIT_CALL_BOUND_METHOD_EXACT_ARGS 424
-#define _INIT_CALL_PY_EXACT_ARGS 425
-#define _INIT_CALL_PY_EXACT_ARGS_0 426
-#define _INIT_CALL_PY_EXACT_ARGS_1 427
-#define _INIT_CALL_PY_EXACT_ARGS_2 428
-#define _INIT_CALL_PY_EXACT_ARGS_3 429
-#define _INIT_CALL_PY_EXACT_ARGS_4 430
-#define _INSERT_NULL 431
+#define _INIT_CALL_BOUND_METHOD_EXACT_ARGS 430
+#define _INIT_CALL_PY_EXACT_ARGS 431
+#define _INIT_CALL_PY_EXACT_ARGS_0 432
+#define _INIT_CALL_PY_EXACT_ARGS_1 433
+#define _INIT_CALL_PY_EXACT_ARGS_2 434
+#define _INIT_CALL_PY_EXACT_ARGS_3 435
+#define _INIT_CALL_PY_EXACT_ARGS_4 436
+#define _INSERT_NULL 437
#define _INSTRUMENTED_FOR_ITER INSTRUMENTED_FOR_ITER
#define _INSTRUMENTED_INSTRUCTION INSTRUMENTED_INSTRUCTION
#define _INSTRUMENTED_JUMP_FORWARD INSTRUMENTED_JUMP_FORWARD
@@ -185,177 +191,179 @@ extern "C" {
#define _INSTRUMENTED_POP_JUMP_IF_NONE INSTRUMENTED_POP_JUMP_IF_NONE
#define _INSTRUMENTED_POP_JUMP_IF_NOT_NONE INSTRUMENTED_POP_JUMP_IF_NOT_NONE
#define _INSTRUMENTED_POP_JUMP_IF_TRUE INSTRUMENTED_POP_JUMP_IF_TRUE
-#define _IS_NONE 432
+#define _IS_NONE 438
#define _IS_OP IS_OP
-#define _ITER_CHECK_LIST 433
-#define _ITER_CHECK_RANGE 434
-#define _ITER_CHECK_TUPLE 435
-#define _ITER_JUMP_LIST 436
-#define _ITER_JUMP_RANGE 437
-#define _ITER_JUMP_TUPLE 438
-#define _ITER_NEXT_LIST 439
-#define _ITER_NEXT_LIST_TIER_TWO 440
-#define _ITER_NEXT_RANGE 441
-#define _ITER_NEXT_TUPLE 442
-#define _JUMP_TO_TOP 443
+#define _ITER_CHECK_LIST 439
+#define _ITER_CHECK_RANGE 440
+#define _ITER_CHECK_TUPLE 441
+#define _ITER_JUMP_LIST 442
+#define _ITER_JUMP_RANGE 443
+#define _ITER_JUMP_TUPLE 444
+#define _ITER_NEXT_LIST 445
+#define _ITER_NEXT_LIST_TIER_TWO 446
+#define _ITER_NEXT_RANGE 447
+#define _ITER_NEXT_TUPLE 448
+#define _JUMP_BACKWARD_NO_INTERRUPT JUMP_BACKWARD_NO_INTERRUPT
+#define _JUMP_TO_TOP 449
#define _LIST_APPEND LIST_APPEND
#define _LIST_EXTEND LIST_EXTEND
-#define _LOAD_ATTR 444
-#define _LOAD_ATTR_CLASS 445
+#define _LOAD_ATTR 450
+#define _LOAD_ATTR_CLASS 451
#define _LOAD_ATTR_GETATTRIBUTE_OVERRIDDEN LOAD_ATTR_GETATTRIBUTE_OVERRIDDEN
-#define _LOAD_ATTR_INSTANCE_VALUE 446
-#define _LOAD_ATTR_METHOD_LAZY_DICT 447
-#define _LOAD_ATTR_METHOD_NO_DICT 448
-#define _LOAD_ATTR_METHOD_WITH_VALUES 449
-#define _LOAD_ATTR_MODULE 450
-#define _LOAD_ATTR_NONDESCRIPTOR_NO_DICT 451
-#define _LOAD_ATTR_NONDESCRIPTOR_WITH_VALUES 452
-#define _LOAD_ATTR_PROPERTY_FRAME 453
-#define _LOAD_ATTR_SLOT 454
-#define _LOAD_ATTR_WITH_HINT 455
+#define _LOAD_ATTR_INSTANCE_VALUE 452
+#define _LOAD_ATTR_METHOD_LAZY_DICT 453
+#define _LOAD_ATTR_METHOD_NO_DICT 454
+#define _LOAD_ATTR_METHOD_WITH_VALUES 455
+#define _LOAD_ATTR_MODULE 456
+#define _LOAD_ATTR_NONDESCRIPTOR_NO_DICT 457
+#define _LOAD_ATTR_NONDESCRIPTOR_WITH_VALUES 458
+#define _LOAD_ATTR_PROPERTY_FRAME 459
+#define _LOAD_ATTR_SLOT 460
+#define _LOAD_ATTR_WITH_HINT 461
#define _LOAD_BUILD_CLASS LOAD_BUILD_CLASS
-#define _LOAD_BYTECODE 456
+#define _LOAD_BYTECODE 462
#define _LOAD_COMMON_CONSTANT LOAD_COMMON_CONSTANT
#define _LOAD_CONST LOAD_CONST
-#define _LOAD_CONST_INLINE 457
-#define _LOAD_CONST_INLINE_BORROW 458
-#define _LOAD_CONST_UNDER_INLINE 459
-#define _LOAD_CONST_UNDER_INLINE_BORROW 460
+#define _LOAD_CONST_INLINE 463
+#define _LOAD_CONST_INLINE_BORROW 464
+#define _LOAD_CONST_UNDER_INLINE 465
+#define _LOAD_CONST_UNDER_INLINE_BORROW 466
#define _LOAD_DEREF LOAD_DEREF
-#define _LOAD_FAST 461
-#define _LOAD_FAST_0 462
-#define _LOAD_FAST_1 463
-#define _LOAD_FAST_2 464
-#define _LOAD_FAST_3 465
-#define _LOAD_FAST_4 466
-#define _LOAD_FAST_5 467
-#define _LOAD_FAST_6 468
-#define _LOAD_FAST_7 469
+#define _LOAD_FAST 467
+#define _LOAD_FAST_0 468
+#define _LOAD_FAST_1 469
+#define _LOAD_FAST_2 470
+#define _LOAD_FAST_3 471
+#define _LOAD_FAST_4 472
+#define _LOAD_FAST_5 473
+#define _LOAD_FAST_6 474
+#define _LOAD_FAST_7 475
#define _LOAD_FAST_AND_CLEAR LOAD_FAST_AND_CLEAR
-#define _LOAD_FAST_BORROW 470
-#define _LOAD_FAST_BORROW_0 471
-#define _LOAD_FAST_BORROW_1 472
-#define _LOAD_FAST_BORROW_2 473
-#define _LOAD_FAST_BORROW_3 474
-#define _LOAD_FAST_BORROW_4 475
-#define _LOAD_FAST_BORROW_5 476
-#define _LOAD_FAST_BORROW_6 477
-#define _LOAD_FAST_BORROW_7 478
+#define _LOAD_FAST_BORROW 476
+#define _LOAD_FAST_BORROW_0 477
+#define _LOAD_FAST_BORROW_1 478
+#define _LOAD_FAST_BORROW_2 479
+#define _LOAD_FAST_BORROW_3 480
+#define _LOAD_FAST_BORROW_4 481
+#define _LOAD_FAST_BORROW_5 482
+#define _LOAD_FAST_BORROW_6 483
+#define _LOAD_FAST_BORROW_7 484
#define _LOAD_FAST_BORROW_LOAD_FAST_BORROW LOAD_FAST_BORROW_LOAD_FAST_BORROW
#define _LOAD_FAST_CHECK LOAD_FAST_CHECK
#define _LOAD_FAST_LOAD_FAST LOAD_FAST_LOAD_FAST
#define _LOAD_FROM_DICT_OR_DEREF LOAD_FROM_DICT_OR_DEREF
#define _LOAD_FROM_DICT_OR_GLOBALS LOAD_FROM_DICT_OR_GLOBALS
-#define _LOAD_GLOBAL 479
-#define _LOAD_GLOBAL_BUILTINS 480
-#define _LOAD_GLOBAL_MODULE 481
+#define _LOAD_GLOBAL 485
+#define _LOAD_GLOBAL_BUILTINS 486
+#define _LOAD_GLOBAL_MODULE 487
#define _LOAD_LOCALS LOAD_LOCALS
#define _LOAD_NAME LOAD_NAME
-#define _LOAD_SMALL_INT 482
-#define _LOAD_SMALL_INT_0 483
-#define _LOAD_SMALL_INT_1 484
-#define _LOAD_SMALL_INT_2 485
-#define _LOAD_SMALL_INT_3 486
-#define _LOAD_SPECIAL 487
+#define _LOAD_SMALL_INT 488
+#define _LOAD_SMALL_INT_0 489
+#define _LOAD_SMALL_INT_1 490
+#define _LOAD_SMALL_INT_2 491
+#define _LOAD_SMALL_INT_3 492
+#define _LOAD_SPECIAL 493
#define _LOAD_SUPER_ATTR_ATTR LOAD_SUPER_ATTR_ATTR
#define _LOAD_SUPER_ATTR_METHOD LOAD_SUPER_ATTR_METHOD
-#define _MAKE_CALLARGS_A_TUPLE 488
+#define _MAKE_CALLARGS_A_TUPLE 494
#define _MAKE_CELL MAKE_CELL
#define _MAKE_FUNCTION MAKE_FUNCTION
-#define _MAKE_WARM 489
+#define _MAKE_WARM 495
#define _MAP_ADD MAP_ADD
#define _MATCH_CLASS MATCH_CLASS
#define _MATCH_KEYS MATCH_KEYS
#define _MATCH_MAPPING MATCH_MAPPING
#define _MATCH_SEQUENCE MATCH_SEQUENCE
-#define _MAYBE_EXPAND_METHOD 490
-#define _MAYBE_EXPAND_METHOD_KW 491
-#define _MONITOR_CALL 492
-#define _MONITOR_CALL_KW 493
-#define _MONITOR_JUMP_BACKWARD 494
-#define _MONITOR_RESUME 495
+#define _MAYBE_EXPAND_METHOD 496
+#define _MAYBE_EXPAND_METHOD_KW 497
+#define _MONITOR_CALL 498
+#define _MONITOR_CALL_KW 499
+#define _MONITOR_JUMP_BACKWARD 500
+#define _MONITOR_RESUME 501
#define _NOP NOP
-#define _POP_CALL 496
-#define _POP_CALL_LOAD_CONST_INLINE_BORROW 497
-#define _POP_CALL_ONE 498
-#define _POP_CALL_ONE_LOAD_CONST_INLINE_BORROW 499
-#define _POP_CALL_TWO 500
-#define _POP_CALL_TWO_LOAD_CONST_INLINE_BORROW 501
+#define _POP_CALL 502
+#define _POP_CALL_LOAD_CONST_INLINE_BORROW 503
+#define _POP_CALL_ONE 504
+#define _POP_CALL_ONE_LOAD_CONST_INLINE_BORROW 505
+#define _POP_CALL_TWO 506
+#define _POP_CALL_TWO_LOAD_CONST_INLINE_BORROW 507
#define _POP_EXCEPT POP_EXCEPT
#define _POP_ITER POP_ITER
-#define _POP_JUMP_IF_FALSE 502
-#define _POP_JUMP_IF_TRUE 503
+#define _POP_JUMP_IF_FALSE 508
+#define _POP_JUMP_IF_TRUE 509
#define _POP_TOP POP_TOP
-#define _POP_TOP_FLOAT 504
-#define _POP_TOP_INT 505
-#define _POP_TOP_LOAD_CONST_INLINE 506
-#define _POP_TOP_LOAD_CONST_INLINE_BORROW 507
-#define _POP_TOP_NOP 508
-#define _POP_TOP_UNICODE 509
-#define _POP_TWO 510
-#define _POP_TWO_LOAD_CONST_INLINE_BORROW 511
+#define _POP_TOP_FLOAT 510
+#define _POP_TOP_INT 511
+#define _POP_TOP_LOAD_CONST_INLINE 512
+#define _POP_TOP_LOAD_CONST_INLINE_BORROW 513
+#define _POP_TOP_NOP 514
+#define _POP_TOP_UNICODE 515
+#define _POP_TWO 516
+#define _POP_TWO_LOAD_CONST_INLINE_BORROW 517
#define _PUSH_EXC_INFO PUSH_EXC_INFO
-#define _PUSH_FRAME 512
+#define _PUSH_FRAME 518
#define _PUSH_NULL PUSH_NULL
-#define _PUSH_NULL_CONDITIONAL 513
-#define _PY_FRAME_GENERAL 514
-#define _PY_FRAME_KW 515
-#define _QUICKEN_RESUME 516
-#define _REPLACE_WITH_TRUE 517
+#define _PUSH_NULL_CONDITIONAL 519
+#define _PY_FRAME_GENERAL 520
+#define _PY_FRAME_KW 521
+#define _QUICKEN_RESUME 522
+#define _REPLACE_WITH_TRUE 523
#define _RESUME_CHECK RESUME_CHECK
#define _RETURN_GENERATOR RETURN_GENERATOR
#define _RETURN_VALUE RETURN_VALUE
-#define _SAVE_RETURN_OFFSET 518
-#define _SEND 519
-#define _SEND_GEN_FRAME 520
+#define _SAVE_RETURN_OFFSET 524
+#define _SEND 525
+#define _SEND_GEN_FRAME 526
#define _SETUP_ANNOTATIONS SETUP_ANNOTATIONS
#define _SET_ADD SET_ADD
#define _SET_FUNCTION_ATTRIBUTE SET_FUNCTION_ATTRIBUTE
#define _SET_UPDATE SET_UPDATE
-#define _START_EXECUTOR 521
-#define _STORE_ATTR 522
-#define _STORE_ATTR_INSTANCE_VALUE 523
-#define _STORE_ATTR_SLOT 524
-#define _STORE_ATTR_WITH_HINT 525
+#define _START_EXECUTOR 527
+#define _STORE_ATTR 528
+#define _STORE_ATTR_INSTANCE_VALUE 529
+#define _STORE_ATTR_SLOT 530
+#define _STORE_ATTR_WITH_HINT 531
#define _STORE_DEREF STORE_DEREF
-#define _STORE_FAST 526
-#define _STORE_FAST_0 527
-#define _STORE_FAST_1 528
-#define _STORE_FAST_2 529
-#define _STORE_FAST_3 530
-#define _STORE_FAST_4 531
-#define _STORE_FAST_5 532
-#define _STORE_FAST_6 533
-#define _STORE_FAST_7 534
+#define _STORE_FAST 532
+#define _STORE_FAST_0 533
+#define _STORE_FAST_1 534
+#define _STORE_FAST_2 535
+#define _STORE_FAST_3 536
+#define _STORE_FAST_4 537
+#define _STORE_FAST_5 538
+#define _STORE_FAST_6 539
+#define _STORE_FAST_7 540
#define _STORE_FAST_LOAD_FAST STORE_FAST_LOAD_FAST
#define _STORE_FAST_STORE_FAST STORE_FAST_STORE_FAST
#define _STORE_GLOBAL STORE_GLOBAL
#define _STORE_NAME STORE_NAME
-#define _STORE_SLICE 535
-#define _STORE_SUBSCR 536
-#define _STORE_SUBSCR_DICT 537
-#define _STORE_SUBSCR_LIST_INT 538
-#define _SWAP 539
-#define _SWAP_2 540
-#define _SWAP_3 541
-#define _TIER2_RESUME_CHECK 542
-#define _TO_BOOL 543
+#define _STORE_SLICE 541
+#define _STORE_SUBSCR 542
+#define _STORE_SUBSCR_DICT 543
+#define _STORE_SUBSCR_LIST_INT 544
+#define _SWAP 545
+#define _SWAP_2 546
+#define _SWAP_3 547
+#define _TIER2_RESUME_CHECK 548
+#define _TO_BOOL 549
#define _TO_BOOL_BOOL TO_BOOL_BOOL
#define _TO_BOOL_INT TO_BOOL_INT
-#define _TO_BOOL_LIST 544
+#define _TO_BOOL_LIST 550
#define _TO_BOOL_NONE TO_BOOL_NONE
-#define _TO_BOOL_STR 545
+#define _TO_BOOL_STR 551
+#define _TRACE_RECORD TRACE_RECORD
#define _UNARY_INVERT UNARY_INVERT
#define _UNARY_NEGATIVE UNARY_NEGATIVE
#define _UNARY_NOT UNARY_NOT
#define _UNPACK_EX UNPACK_EX
-#define _UNPACK_SEQUENCE 546
-#define _UNPACK_SEQUENCE_LIST 547
-#define _UNPACK_SEQUENCE_TUPLE 548
-#define _UNPACK_SEQUENCE_TWO_TUPLE 549
+#define _UNPACK_SEQUENCE 552
+#define _UNPACK_SEQUENCE_LIST 553
+#define _UNPACK_SEQUENCE_TUPLE 554
+#define _UNPACK_SEQUENCE_TWO_TUPLE 555
#define _WITH_EXCEPT_START WITH_EXCEPT_START
#define _YIELD_VALUE YIELD_VALUE
-#define MAX_UOP_ID 549
+#define MAX_UOP_ID 555
#ifdef __cplusplus
}
diff --git a/Include/internal/pycore_uop_metadata.h b/Include/internal/pycore_uop_metadata.h
index 12487719969..d5a3c362d87 100644
--- a/Include/internal/pycore_uop_metadata.h
+++ b/Include/internal/pycore_uop_metadata.h
@@ -11,7 +11,7 @@ extern "C" {
#include
#include "pycore_uop_ids.h"
-extern const uint16_t _PyUop_Flags[MAX_UOP_ID+1];
+extern const uint32_t _PyUop_Flags[MAX_UOP_ID+1];
typedef struct _rep_range { uint8_t start; uint8_t stop; } ReplicationRange;
extern const ReplicationRange _PyUop_Replication[MAX_UOP_ID+1];
extern const char * const _PyOpcode_uop_name[MAX_UOP_ID+1];
@@ -19,7 +19,7 @@ extern const char * const _PyOpcode_uop_name[MAX_UOP_ID+1];
extern int _PyUop_num_popped(int opcode, int oparg);
#ifdef NEED_OPCODE_METADATA
-const uint16_t _PyUop_Flags[MAX_UOP_ID+1] = {
+const uint32_t _PyUop_Flags[MAX_UOP_ID+1] = {
[_NOP] = HAS_PURE_FLAG,
[_CHECK_PERIODIC] = HAS_EVAL_BREAK_FLAG | HAS_ERROR_FLAG | HAS_ESCAPES_FLAG,
[_CHECK_PERIODIC_IF_NOT_YIELD_FROM] = HAS_ARG_FLAG | HAS_EVAL_BREAK_FLAG | HAS_ERROR_FLAG | HAS_ESCAPES_FLAG,
@@ -128,12 +128,12 @@ const uint16_t _PyUop_Flags[MAX_UOP_ID+1] = {
[_DELETE_SUBSCR] = HAS_ERROR_FLAG | HAS_ESCAPES_FLAG,
[_CALL_INTRINSIC_1] = HAS_ARG_FLAG | HAS_ERROR_FLAG | HAS_ESCAPES_FLAG,
[_CALL_INTRINSIC_2] = HAS_ARG_FLAG | HAS_ERROR_FLAG | HAS_ESCAPES_FLAG,
- [_RETURN_VALUE] = HAS_ESCAPES_FLAG,
+ [_RETURN_VALUE] = HAS_ESCAPES_FLAG | HAS_NEEDS_GUARD_IP_FLAG,
[_GET_AITER] = HAS_ERROR_FLAG | HAS_ESCAPES_FLAG,
[_GET_ANEXT] = HAS_ERROR_FLAG | HAS_ERROR_NO_POP_FLAG | HAS_ESCAPES_FLAG,
[_GET_AWAITABLE] = HAS_ARG_FLAG | HAS_ERROR_FLAG | HAS_ESCAPES_FLAG,
[_SEND_GEN_FRAME] = HAS_ARG_FLAG | HAS_DEOPT_FLAG,
- [_YIELD_VALUE] = HAS_ARG_FLAG,
+ [_YIELD_VALUE] = HAS_ARG_FLAG | HAS_NEEDS_GUARD_IP_FLAG,
[_POP_EXCEPT] = HAS_ESCAPES_FLAG,
[_LOAD_COMMON_CONSTANT] = HAS_ARG_FLAG,
[_LOAD_BUILD_CLASS] = HAS_ERROR_FLAG | HAS_ESCAPES_FLAG,
@@ -256,7 +256,7 @@ const uint16_t _PyUop_Flags[MAX_UOP_ID+1] = {
[_INIT_CALL_PY_EXACT_ARGS_3] = HAS_PURE_FLAG,
[_INIT_CALL_PY_EXACT_ARGS_4] = HAS_PURE_FLAG,
[_INIT_CALL_PY_EXACT_ARGS] = HAS_ARG_FLAG | HAS_PURE_FLAG,
- [_PUSH_FRAME] = 0,
+ [_PUSH_FRAME] = HAS_NEEDS_GUARD_IP_FLAG,
[_GUARD_NOS_NULL] = HAS_DEOPT_FLAG,
[_GUARD_NOS_NOT_NULL] = HAS_EXIT_FLAG,
[_GUARD_THIRD_NULL] = HAS_DEOPT_FLAG,
@@ -293,7 +293,7 @@ const uint16_t _PyUop_Flags[MAX_UOP_ID+1] = {
[_MAKE_CALLARGS_A_TUPLE] = HAS_ERROR_FLAG | HAS_ERROR_NO_POP_FLAG | HAS_ESCAPES_FLAG,
[_MAKE_FUNCTION] = HAS_ERROR_FLAG | HAS_ESCAPES_FLAG,
[_SET_FUNCTION_ATTRIBUTE] = HAS_ARG_FLAG,
- [_RETURN_GENERATOR] = HAS_ERROR_FLAG | HAS_ESCAPES_FLAG,
+ [_RETURN_GENERATOR] = HAS_ERROR_FLAG | HAS_ESCAPES_FLAG | HAS_NEEDS_GUARD_IP_FLAG,
[_BUILD_SLICE] = HAS_ARG_FLAG | HAS_ERROR_FLAG | HAS_ESCAPES_FLAG,
[_CONVERT_VALUE] = HAS_ARG_FLAG | HAS_ERROR_FLAG | HAS_ESCAPES_FLAG,
[_FORMAT_SIMPLE] = HAS_ERROR_FLAG | HAS_ESCAPES_FLAG,
@@ -315,6 +315,7 @@ const uint16_t _PyUop_Flags[MAX_UOP_ID+1] = {
[_CHECK_STACK_SPACE_OPERAND] = HAS_DEOPT_FLAG,
[_SAVE_RETURN_OFFSET] = HAS_ARG_FLAG,
[_EXIT_TRACE] = HAS_ESCAPES_FLAG,
+ [_DYNAMIC_EXIT] = HAS_ESCAPES_FLAG,
[_CHECK_VALIDITY] = HAS_DEOPT_FLAG,
[_LOAD_CONST_INLINE] = HAS_PURE_FLAG,
[_POP_TOP_LOAD_CONST_INLINE] = HAS_ESCAPES_FLAG | HAS_PURE_FLAG,
@@ -336,7 +337,12 @@ const uint16_t _PyUop_Flags[MAX_UOP_ID+1] = {
[_HANDLE_PENDING_AND_DEOPT] = HAS_ESCAPES_FLAG,
[_ERROR_POP_N] = HAS_ARG_FLAG,
[_TIER2_RESUME_CHECK] = HAS_PERIODIC_FLAG,
- [_COLD_EXIT] = HAS_ESCAPES_FLAG,
+ [_COLD_EXIT] = 0,
+ [_COLD_DYNAMIC_EXIT] = 0,
+ [_GUARD_IP__PUSH_FRAME] = HAS_EXIT_FLAG,
+ [_GUARD_IP_YIELD_VALUE] = HAS_EXIT_FLAG,
+ [_GUARD_IP_RETURN_VALUE] = HAS_EXIT_FLAG,
+ [_GUARD_IP_RETURN_GENERATOR] = HAS_EXIT_FLAG,
};
const ReplicationRange _PyUop_Replication[MAX_UOP_ID+1] = {
@@ -419,6 +425,7 @@ const char *const _PyOpcode_uop_name[MAX_UOP_ID+1] = {
[_CHECK_STACK_SPACE] = "_CHECK_STACK_SPACE",
[_CHECK_STACK_SPACE_OPERAND] = "_CHECK_STACK_SPACE_OPERAND",
[_CHECK_VALIDITY] = "_CHECK_VALIDITY",
+ [_COLD_DYNAMIC_EXIT] = "_COLD_DYNAMIC_EXIT",
[_COLD_EXIT] = "_COLD_EXIT",
[_COMPARE_OP] = "_COMPARE_OP",
[_COMPARE_OP_FLOAT] = "_COMPARE_OP_FLOAT",
@@ -443,6 +450,7 @@ const char *const _PyOpcode_uop_name[MAX_UOP_ID+1] = {
[_DEOPT] = "_DEOPT",
[_DICT_MERGE] = "_DICT_MERGE",
[_DICT_UPDATE] = "_DICT_UPDATE",
+ [_DYNAMIC_EXIT] = "_DYNAMIC_EXIT",
[_END_FOR] = "_END_FOR",
[_END_SEND] = "_END_SEND",
[_ERROR_POP_N] = "_ERROR_POP_N",
@@ -471,6 +479,10 @@ const char *const _PyOpcode_uop_name[MAX_UOP_ID+1] = {
[_GUARD_DORV_NO_DICT] = "_GUARD_DORV_NO_DICT",
[_GUARD_DORV_VALUES_INST_ATTR_FROM_DICT] = "_GUARD_DORV_VALUES_INST_ATTR_FROM_DICT",
[_GUARD_GLOBALS_VERSION] = "_GUARD_GLOBALS_VERSION",
+ [_GUARD_IP_RETURN_GENERATOR] = "_GUARD_IP_RETURN_GENERATOR",
+ [_GUARD_IP_RETURN_VALUE] = "_GUARD_IP_RETURN_VALUE",
+ [_GUARD_IP_YIELD_VALUE] = "_GUARD_IP_YIELD_VALUE",
+ [_GUARD_IP__PUSH_FRAME] = "_GUARD_IP__PUSH_FRAME",
[_GUARD_IS_FALSE_POP] = "_GUARD_IS_FALSE_POP",
[_GUARD_IS_NONE_POP] = "_GUARD_IS_NONE_POP",
[_GUARD_IS_NOT_NONE_POP] = "_GUARD_IS_NOT_NONE_POP",
@@ -1261,6 +1273,8 @@ int _PyUop_num_popped(int opcode, int oparg)
return 0;
case _EXIT_TRACE:
return 0;
+ case _DYNAMIC_EXIT:
+ return 0;
case _CHECK_VALIDITY:
return 0;
case _LOAD_CONST_INLINE:
@@ -1305,6 +1319,16 @@ int _PyUop_num_popped(int opcode, int oparg)
return 0;
case _COLD_EXIT:
return 0;
+ case _COLD_DYNAMIC_EXIT:
+ return 0;
+ case _GUARD_IP__PUSH_FRAME:
+ return 0;
+ case _GUARD_IP_YIELD_VALUE:
+ return 0;
+ case _GUARD_IP_RETURN_VALUE:
+ return 0;
+ case _GUARD_IP_RETURN_GENERATOR:
+ return 0;
default:
return -1;
}
diff --git a/Include/moduleobject.h b/Include/moduleobject.h
index e3afac0a343..e83bc395aa4 100644
--- a/Include/moduleobject.h
+++ b/Include/moduleobject.h
@@ -83,11 +83,19 @@ struct PyModuleDef_Slot {
#endif
#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= _Py_PACK_VERSION(3, 15)
# define Py_mod_abi 5
+# define Py_mod_name 6
+# define Py_mod_doc 7
+# define Py_mod_state_size 8
+# define Py_mod_methods 9
+# define Py_mod_state_traverse 10
+# define Py_mod_state_clear 11
+# define Py_mod_state_free 12
+# define Py_mod_token 13
#endif
#ifndef Py_LIMITED_API
-#define _Py_mod_LAST_SLOT 5
+#define _Py_mod_LAST_SLOT 13
#endif
#endif /* New in 3.5 */
@@ -109,6 +117,13 @@ struct PyModuleDef_Slot {
PyAPI_FUNC(int) PyUnstable_Module_SetGIL(PyObject *module, void *gil);
#endif
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= _Py_PACK_VERSION(3, 15)
+PyAPI_FUNC(PyObject *) PyModule_FromSlotsAndSpec(const PyModuleDef_Slot *,
+ PyObject *spec);
+PyAPI_FUNC(int) PyModule_Exec(PyObject *mod);
+PyAPI_FUNC(int) PyModule_GetStateSize(PyObject *mod, Py_ssize_t *result);
+PyAPI_FUNC(int) PyModule_GetToken(PyObject *, void **result);
+#endif
#ifndef _Py_OPAQUE_PYOBJECT
struct PyModuleDef {
diff --git a/Include/object.h b/Include/object.h
index 291e4f0a7ed..f17dcba4f47 100644
--- a/Include/object.h
+++ b/Include/object.h
@@ -839,6 +839,11 @@ PyAPI_FUNC(PyObject *) PyType_GetModuleByDef(PyTypeObject *, PyModuleDef *);
PyAPI_FUNC(int) PyType_Freeze(PyTypeObject *type);
#endif
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= _Py_PACK_VERSION(3, 15)
+PyAPI_FUNC(PyObject *) PyType_GetModuleByToken(PyTypeObject *type,
+ const void *token);
+#endif
+
#ifdef __cplusplus
}
#endif
diff --git a/Include/opcode_ids.h b/Include/opcode_ids.h
index 1d5c74adefc..0d066c16901 100644
--- a/Include/opcode_ids.h
+++ b/Include/opcode_ids.h
@@ -213,28 +213,29 @@ extern "C" {
#define UNPACK_SEQUENCE_LIST 207
#define UNPACK_SEQUENCE_TUPLE 208
#define UNPACK_SEQUENCE_TWO_TUPLE 209
-#define INSTRUMENTED_END_FOR 234
-#define INSTRUMENTED_POP_ITER 235
-#define INSTRUMENTED_END_SEND 236
-#define INSTRUMENTED_FOR_ITER 237
-#define INSTRUMENTED_INSTRUCTION 238
-#define INSTRUMENTED_JUMP_FORWARD 239
-#define INSTRUMENTED_NOT_TAKEN 240
-#define INSTRUMENTED_POP_JUMP_IF_TRUE 241
-#define INSTRUMENTED_POP_JUMP_IF_FALSE 242
-#define INSTRUMENTED_POP_JUMP_IF_NONE 243
-#define INSTRUMENTED_POP_JUMP_IF_NOT_NONE 244
-#define INSTRUMENTED_RESUME 245
-#define INSTRUMENTED_RETURN_VALUE 246
-#define INSTRUMENTED_YIELD_VALUE 247
-#define INSTRUMENTED_END_ASYNC_FOR 248
-#define INSTRUMENTED_LOAD_SUPER_ATTR 249
-#define INSTRUMENTED_CALL 250
-#define INSTRUMENTED_CALL_KW 251
-#define INSTRUMENTED_CALL_FUNCTION_EX 252
-#define INSTRUMENTED_JUMP_BACKWARD 253
-#define INSTRUMENTED_LINE 254
-#define ENTER_EXECUTOR 255
+#define INSTRUMENTED_END_FOR 233
+#define INSTRUMENTED_POP_ITER 234
+#define INSTRUMENTED_END_SEND 235
+#define INSTRUMENTED_FOR_ITER 236
+#define INSTRUMENTED_INSTRUCTION 237
+#define INSTRUMENTED_JUMP_FORWARD 238
+#define INSTRUMENTED_NOT_TAKEN 239
+#define INSTRUMENTED_POP_JUMP_IF_TRUE 240
+#define INSTRUMENTED_POP_JUMP_IF_FALSE 241
+#define INSTRUMENTED_POP_JUMP_IF_NONE 242
+#define INSTRUMENTED_POP_JUMP_IF_NOT_NONE 243
+#define INSTRUMENTED_RESUME 244
+#define INSTRUMENTED_RETURN_VALUE 245
+#define INSTRUMENTED_YIELD_VALUE 246
+#define INSTRUMENTED_END_ASYNC_FOR 247
+#define INSTRUMENTED_LOAD_SUPER_ATTR 248
+#define INSTRUMENTED_CALL 249
+#define INSTRUMENTED_CALL_KW 250
+#define INSTRUMENTED_CALL_FUNCTION_EX 251
+#define INSTRUMENTED_JUMP_BACKWARD 252
+#define INSTRUMENTED_LINE 253
+#define ENTER_EXECUTOR 254
+#define TRACE_RECORD 255
#define ANNOTATIONS_PLACEHOLDER 256
#define JUMP 257
#define JUMP_IF_FALSE 258
@@ -249,7 +250,7 @@ extern "C" {
#define HAVE_ARGUMENT 43
#define MIN_SPECIALIZED_OPCODE 129
-#define MIN_INSTRUMENTED_OPCODE 234
+#define MIN_INSTRUMENTED_OPCODE 233
#ifdef __cplusplus
}
diff --git a/Include/patchlevel.h b/Include/patchlevel.h
index e3996ee8679..804aa1a0427 100644
--- a/Include/patchlevel.h
+++ b/Include/patchlevel.h
@@ -24,10 +24,10 @@
#define PY_MINOR_VERSION 15
#define PY_MICRO_VERSION 0
#define PY_RELEASE_LEVEL PY_RELEASE_LEVEL_ALPHA
-#define PY_RELEASE_SERIAL 1
+#define PY_RELEASE_SERIAL 2
/* Version as a string */
-#define PY_VERSION "3.15.0a1+"
+#define PY_VERSION "3.15.0a2+"
/*--end constants--*/
diff --git a/Include/pymath.h b/Include/pymath.h
index e2919c7b527..7cfe441365d 100644
--- a/Include/pymath.h
+++ b/Include/pymath.h
@@ -7,6 +7,7 @@
/* High precision definition of pi and e (Euler)
* The values are taken from libc6's math.h.
*/
+// Deprecated since Python 3.15.
#ifndef Py_MATH_PIl
#define Py_MATH_PIl 3.1415926535897932384626433832795029L
#endif
@@ -14,6 +15,7 @@
#define Py_MATH_PI 3.14159265358979323846
#endif
+// Deprecated since Python 3.15.
#ifndef Py_MATH_El
#define Py_MATH_El 2.7182818284590452353602874713526625L
#endif
@@ -43,13 +45,14 @@
#define Py_IS_FINITE(X) isfinite(X)
// Py_INFINITY: Value that evaluates to a positive double infinity.
+// Soft deprecated since Python 3.15, use INFINITY instead.
#ifndef Py_INFINITY
# define Py_INFINITY ((double)INFINITY)
#endif
/* Py_HUGE_VAL should always be the same as Py_INFINITY. But historically
* this was not reliable and Python did not require IEEE floats and C99
- * conformity. The macro was soft deprecated in Python 3.14, use Py_INFINITY instead.
+ * conformity. The macro was soft deprecated in Python 3.14, use INFINITY instead.
*/
#ifndef Py_HUGE_VAL
# define Py_HUGE_VAL HUGE_VAL
diff --git a/Include/pyport.h b/Include/pyport.h
index e77b39026a5..97c0e195d19 100644
--- a/Include/pyport.h
+++ b/Include/pyport.h
@@ -504,6 +504,7 @@ extern "C" {
* Thread support is stubbed and any attempt to create a new thread fails.
*/
#if (!defined(HAVE_PTHREAD_STUBS) && \
+ !defined(__wasi__) && \
(!defined(__EMSCRIPTEN__) || defined(__EMSCRIPTEN_PTHREADS__)))
# define Py_CAN_START_THREADS 1
#endif
@@ -677,4 +678,10 @@ extern "C" {
#endif
+// Assume the stack grows down unless specified otherwise
+#ifndef _Py_STACK_GROWS_DOWN
+# define _Py_STACK_GROWS_DOWN 1
+#endif
+
+
#endif /* Py_PYPORT_H */
diff --git a/InternalDocs/jit.md b/InternalDocs/jit.md
index 09585380737..1740b22b85f 100644
--- a/InternalDocs/jit.md
+++ b/InternalDocs/jit.md
@@ -53,7 +53,7 @@ ## The micro-op optimizer
## The JIT interpreter
After a `JUMP_BACKWARD` instruction invokes the uop optimizer to create a uop
-executor, it transfers control to this executor via the `GOTO_TIER_TWO` macro.
+executor, it transfers control to this executor via the `TIER1_TO_TIER2` macro.
CPython implements two executors. Here we describe the JIT interpreter,
which is the simpler of them and is therefore useful for debugging and analyzing
diff --git a/InternalDocs/stack_protection.md b/InternalDocs/stack_protection.md
index fa025bd930f..14802e57d09 100644
--- a/InternalDocs/stack_protection.md
+++ b/InternalDocs/stack_protection.md
@@ -38,12 +38,19 @@ # Stack Protection
```python
kb_used = (stack_top - stack_pointer)>>10
-if stack_pointer < hard_limit:
+if stack_pointer < bottom_of_machine_stack:
+ pass # Our stack limits could be wrong so it is safest to do nothing.
+elif stack_pointer < hard_limit:
FatalError(f"Unrecoverable stack overflow (used {kb_used} kB)")
elif stack_pointer < soft_limit:
raise RecursionError(f"Stack overflow (used {kb_used} kB)")
```
+### User space threads and other oddities
+
+Some libraries provide user-space threads. These will change the C stack at runtime.
+To guard against this we only raise if the stack pointer is in the window between the expected stack base and the soft limit.
+
### Diagnosing and fixing stack overflows
For stack protection to work correctly the amount of stack consumed between calls to `_Py_EnterRecursiveCall()` must be less than `_PyOS_STACK_MARGIN_BYTES`.
diff --git a/Lib/_colorize.py b/Lib/_colorize.py
index 63e951d6488..29d7cc67b6e 100644
--- a/Lib/_colorize.py
+++ b/Lib/_colorize.py
@@ -1,4 +1,3 @@
-import io
import os
import sys
@@ -169,7 +168,12 @@ class Argparse(ThemeSection):
short_option: str = ANSIColors.BOLD_GREEN
label: str = ANSIColors.BOLD_YELLOW
action: str = ANSIColors.BOLD_GREEN
+ default: str = ANSIColors.GREY
+ default_value: str = ANSIColors.YELLOW
reset: str = ANSIColors.RESET
+ error: str = ANSIColors.BOLD_MAGENTA
+ warning: str = ANSIColors.BOLD_YELLOW
+ message: str = ANSIColors.MAGENTA
@dataclass(frozen=True, kw_only=True)
@@ -327,7 +331,7 @@ def _safe_getenv(k: str, fallback: str | None = None) -> str | None:
try:
return os.isatty(file.fileno())
- except io.UnsupportedOperation:
+ except OSError:
return hasattr(file, "isatty") and file.isatty()
diff --git a/Lib/_opcode_metadata.py b/Lib/_opcode_metadata.py
index f168d169a32..e681cb17e43 100644
--- a/Lib/_opcode_metadata.py
+++ b/Lib/_opcode_metadata.py
@@ -208,8 +208,9 @@ opmap = {
'CACHE': 0,
'RESERVED': 17,
'RESUME': 128,
- 'INSTRUMENTED_LINE': 254,
- 'ENTER_EXECUTOR': 255,
+ 'INSTRUMENTED_LINE': 253,
+ 'ENTER_EXECUTOR': 254,
+ 'TRACE_RECORD': 255,
'BINARY_SLICE': 1,
'BUILD_TEMPLATE': 2,
'CALL_FUNCTION_EX': 4,
@@ -328,26 +329,26 @@ opmap = {
'UNPACK_EX': 118,
'UNPACK_SEQUENCE': 119,
'YIELD_VALUE': 120,
- 'INSTRUMENTED_END_FOR': 234,
- 'INSTRUMENTED_POP_ITER': 235,
- 'INSTRUMENTED_END_SEND': 236,
- 'INSTRUMENTED_FOR_ITER': 237,
- 'INSTRUMENTED_INSTRUCTION': 238,
- 'INSTRUMENTED_JUMP_FORWARD': 239,
- 'INSTRUMENTED_NOT_TAKEN': 240,
- 'INSTRUMENTED_POP_JUMP_IF_TRUE': 241,
- 'INSTRUMENTED_POP_JUMP_IF_FALSE': 242,
- 'INSTRUMENTED_POP_JUMP_IF_NONE': 243,
- 'INSTRUMENTED_POP_JUMP_IF_NOT_NONE': 244,
- 'INSTRUMENTED_RESUME': 245,
- 'INSTRUMENTED_RETURN_VALUE': 246,
- 'INSTRUMENTED_YIELD_VALUE': 247,
- 'INSTRUMENTED_END_ASYNC_FOR': 248,
- 'INSTRUMENTED_LOAD_SUPER_ATTR': 249,
- 'INSTRUMENTED_CALL': 250,
- 'INSTRUMENTED_CALL_KW': 251,
- 'INSTRUMENTED_CALL_FUNCTION_EX': 252,
- 'INSTRUMENTED_JUMP_BACKWARD': 253,
+ 'INSTRUMENTED_END_FOR': 233,
+ 'INSTRUMENTED_POP_ITER': 234,
+ 'INSTRUMENTED_END_SEND': 235,
+ 'INSTRUMENTED_FOR_ITER': 236,
+ 'INSTRUMENTED_INSTRUCTION': 237,
+ 'INSTRUMENTED_JUMP_FORWARD': 238,
+ 'INSTRUMENTED_NOT_TAKEN': 239,
+ 'INSTRUMENTED_POP_JUMP_IF_TRUE': 240,
+ 'INSTRUMENTED_POP_JUMP_IF_FALSE': 241,
+ 'INSTRUMENTED_POP_JUMP_IF_NONE': 242,
+ 'INSTRUMENTED_POP_JUMP_IF_NOT_NONE': 243,
+ 'INSTRUMENTED_RESUME': 244,
+ 'INSTRUMENTED_RETURN_VALUE': 245,
+ 'INSTRUMENTED_YIELD_VALUE': 246,
+ 'INSTRUMENTED_END_ASYNC_FOR': 247,
+ 'INSTRUMENTED_LOAD_SUPER_ATTR': 248,
+ 'INSTRUMENTED_CALL': 249,
+ 'INSTRUMENTED_CALL_KW': 250,
+ 'INSTRUMENTED_CALL_FUNCTION_EX': 251,
+ 'INSTRUMENTED_JUMP_BACKWARD': 252,
'ANNOTATIONS_PLACEHOLDER': 256,
'JUMP': 257,
'JUMP_IF_FALSE': 258,
@@ -362,4 +363,4 @@ opmap = {
}
HAVE_ARGUMENT = 43
-MIN_INSTRUMENTED_OPCODE = 234
+MIN_INSTRUMENTED_OPCODE = 233
diff --git a/Lib/_py_warnings.py b/Lib/_py_warnings.py
index 91a9f44b201..67c74fdd2d0 100644
--- a/Lib/_py_warnings.py
+++ b/Lib/_py_warnings.py
@@ -646,6 +646,9 @@ def __str__(self):
"line : %r}" % (self.message, self._category_name,
self.filename, self.lineno, self.line))
+ def __repr__(self):
+ return f'<{type(self).__qualname__} {self}>'
+
class catch_warnings(object):
diff --git a/Lib/_pyio.py b/Lib/_pyio.py
index 423178e87a8..69a088df8fc 100644
--- a/Lib/_pyio.py
+++ b/Lib/_pyio.py
@@ -546,7 +546,7 @@ def nreadahead():
res += b
if res.endswith(b"\n"):
break
- return bytes(res)
+ return res.take_bytes()
def __iter__(self):
self._checkClosed()
@@ -620,7 +620,7 @@ def read(self, size=-1):
if n < 0 or n > len(b):
raise ValueError(f"readinto returned {n} outside buffer size {len(b)}")
del b[n:]
- return bytes(b)
+ return b.take_bytes()
def readall(self):
"""Read until EOF, using multiple read() call."""
@@ -628,7 +628,7 @@ def readall(self):
while data := self.read(DEFAULT_BUFFER_SIZE):
res += data
if res:
- return bytes(res)
+ return res.take_bytes()
else:
# b'' or None
return data
@@ -1738,7 +1738,7 @@ def readall(self):
assert len(result) - bytes_read >= 1, \
"os.readinto buffer size 0 will result in erroneous EOF / returns 0"
result.resize(bytes_read)
- return bytes(result)
+ return result.take_bytes()
def readinto(self, buffer):
"""Same as RawIOBase.readinto()."""
diff --git a/Lib/_pyrepl/simple_interact.py b/Lib/_pyrepl/simple_interact.py
index ff1bdab9fea..3b0debf2ba0 100644
--- a/Lib/_pyrepl/simple_interact.py
+++ b/Lib/_pyrepl/simple_interact.py
@@ -31,7 +31,6 @@
import sys
import code
import warnings
-import errno
from .readline import _get_reader, multiline_input, append_history_file
diff --git a/Lib/_pyrepl/windows_console.py b/Lib/_pyrepl/windows_console.py
index c56dcd6d7dd..f9f5988af0b 100644
--- a/Lib/_pyrepl/windows_console.py
+++ b/Lib/_pyrepl/windows_console.py
@@ -249,22 +249,10 @@ def input_hook(self):
def __write_changed_line(
self, y: int, oldline: str, newline: str, px_coord: int
) -> None:
- # this is frustrating; there's no reason to test (say)
- # self.dch1 inside the loop -- but alternative ways of
- # structuring this function are equally painful (I'm trying to
- # avoid writing code generators these days...)
minlen = min(wlen(oldline), wlen(newline))
x_pos = 0
x_coord = 0
- px_pos = 0
- j = 0
- for c in oldline:
- if j >= px_coord:
- break
- j += wlen(c)
- px_pos += 1
-
# reuse the oldline as much as possible, but stop as soon as we
# encounter an ESCAPE, because it might be the start of an escape
# sequence
@@ -358,7 +346,6 @@ def prepare(self) -> None:
self.height, self.width = self.getheightwidth()
self.posxy = 0, 0
- self.__gone_tall = 0
self.__offset = 0
if self.__vt_support:
diff --git a/Lib/annotationlib.py b/Lib/annotationlib.py
index 81886a0467d..a5788cdbfae 100644
--- a/Lib/annotationlib.py
+++ b/Lib/annotationlib.py
@@ -85,6 +85,9 @@ def __init__(
# These are always set to None here but may be non-None if a ForwardRef
# is created through __class__ assignment on a _Stringifier object.
self.__globals__ = None
+ # This may be either a cell object (for a ForwardRef referring to a single name)
+ # or a dict mapping cell names to cell objects (for a ForwardRef containing references
+ # to multiple names).
self.__cell__ = None
self.__extra_names__ = None
# These are initially None but serve as a cache and may be set to a non-None
@@ -117,7 +120,7 @@ def evaluate(
is_forwardref_format = True
case _:
raise NotImplementedError(format)
- if self.__cell__ is not None:
+ if isinstance(self.__cell__, types.CellType):
try:
return self.__cell__.cell_contents
except ValueError:
@@ -147,26 +150,42 @@ def evaluate(
if globals is None:
globals = {}
+ if type_params is None and owner is not None:
+ type_params = getattr(owner, "__type_params__", None)
+
if locals is None:
locals = {}
if isinstance(owner, type):
locals.update(vars(owner))
+ elif (
+ type_params is not None
+ or isinstance(self.__cell__, dict)
+ or self.__extra_names__
+ ):
+ # Create a new locals dict if necessary,
+ # to avoid mutating the argument.
+ locals = dict(locals)
- if type_params is None and owner is not None:
- # "Inject" type parameters into the local namespace
- # (unless they are shadowed by assignments *in* the local namespace),
- # as a way of emulating annotation scopes when calling `eval()`
- type_params = getattr(owner, "__type_params__", None)
-
- # Type parameters exist in their own scope, which is logically
- # between the locals and the globals. We simulate this by adding
- # them to the globals.
+ # "Inject" type parameters into the local namespace
+ # (unless they are shadowed by assignments *in* the local namespace),
+ # as a way of emulating annotation scopes when calling `eval()`
if type_params is not None:
- globals = dict(globals)
for param in type_params:
- globals[param.__name__] = param
+ locals.setdefault(param.__name__, param)
+
+ # Similar logic can be used for nonlocals, which should not
+ # override locals.
+ if isinstance(self.__cell__, dict):
+ for cell_name, cell in self.__cell__.items():
+ try:
+ cell_value = cell.cell_contents
+ except ValueError:
+ pass
+ else:
+ locals.setdefault(cell_name, cell_value)
+
if self.__extra_names__:
- locals = {**locals, **self.__extra_names__}
+ locals.update(self.__extra_names__)
arg = self.__forward_arg__
if arg.isidentifier() and not keyword.iskeyword(arg):
@@ -187,8 +206,11 @@ def evaluate(
except Exception:
if not is_forwardref_format:
raise
+
+ # All variables, in scoping order, should be checked before
+ # triggering __missing__ to create a _Stringifier.
new_locals = _StringifierDict(
- {**builtins.__dict__, **locals},
+ {**builtins.__dict__, **globals, **locals},
globals=globals,
owner=owner,
is_class=self.__forward_is_class__,
@@ -199,7 +221,7 @@ def evaluate(
except Exception:
return self
else:
- new_locals.transmogrify()
+ new_locals.transmogrify(self.__cell__)
return result
def _evaluate(self, globalns, localns, type_params=_sentinel, *, recursive_guard):
@@ -271,7 +293,7 @@ def __hash__(self):
self.__forward_module__,
id(self.__globals__), # dictionaries are not hashable, so hash by identity
self.__forward_is_class__,
- self.__cell__,
+ tuple(sorted(self.__cell__.items())) if isinstance(self.__cell__, dict) else self.__cell__,
self.__owner__,
tuple(sorted(self.__extra_names__.items())) if self.__extra_names__ else None,
))
@@ -639,13 +661,15 @@ def __missing__(self, key):
self.stringifiers.append(fwdref)
return fwdref
- def transmogrify(self):
+ def transmogrify(self, cell_dict):
for obj in self.stringifiers:
obj.__class__ = ForwardRef
obj.__stringifier_dict__ = None # not needed for ForwardRef
if isinstance(obj.__ast_node__, str):
obj.__arg__ = obj.__ast_node__
obj.__ast_node__ = None
+ if cell_dict is not None and obj.__cell__ is None:
+ obj.__cell__ = cell_dict
def create_unique_name(self):
name = f"__annotationlib_name_{self.next_id}__"
@@ -709,7 +733,7 @@ def call_annotate_function(annotate, format, *, owner=None, _is_evaluate=False):
globals = _StringifierDict({}, format=format)
is_class = isinstance(owner, type)
- closure = _build_closure(
+ closure, _ = _build_closure(
annotate, owner, is_class, globals, allow_evaluation=False
)
func = types.FunctionType(
@@ -753,7 +777,7 @@ def call_annotate_function(annotate, format, *, owner=None, _is_evaluate=False):
is_class=is_class,
format=format,
)
- closure = _build_closure(
+ closure, cell_dict = _build_closure(
annotate, owner, is_class, globals, allow_evaluation=True
)
func = types.FunctionType(
@@ -771,7 +795,7 @@ def call_annotate_function(annotate, format, *, owner=None, _is_evaluate=False):
except Exception:
pass
else:
- globals.transmogrify()
+ globals.transmogrify(cell_dict)
return result
# Try again, but do not provide any globals. This allows us to return
@@ -783,7 +807,7 @@ def call_annotate_function(annotate, format, *, owner=None, _is_evaluate=False):
is_class=is_class,
format=format,
)
- closure = _build_closure(
+ closure, cell_dict = _build_closure(
annotate, owner, is_class, globals, allow_evaluation=False
)
func = types.FunctionType(
@@ -794,7 +818,7 @@ def call_annotate_function(annotate, format, *, owner=None, _is_evaluate=False):
kwdefaults=annotate.__kwdefaults__,
)
result = func(Format.VALUE_WITH_FAKE_GLOBALS)
- globals.transmogrify()
+ globals.transmogrify(cell_dict)
if _is_evaluate:
if isinstance(result, ForwardRef):
return result.evaluate(format=Format.FORWARDREF)
@@ -819,14 +843,11 @@ def call_annotate_function(annotate, format, *, owner=None, _is_evaluate=False):
def _build_closure(annotate, owner, is_class, stringifier_dict, *, allow_evaluation):
if not annotate.__closure__:
- return None
- freevars = annotate.__code__.co_freevars
+ return None, None
new_closure = []
- for i, cell in enumerate(annotate.__closure__):
- if i < len(freevars):
- name = freevars[i]
- else:
- name = "__cell__"
+ cell_dict = {}
+ for name, cell in zip(annotate.__code__.co_freevars, annotate.__closure__, strict=True):
+ cell_dict[name] = cell
new_cell = None
if allow_evaluation:
try:
@@ -847,7 +868,7 @@ def _build_closure(annotate, owner, is_class, stringifier_dict, *, allow_evaluat
stringifier_dict.stringifiers.append(fwdref)
new_cell = types.CellType(fwdref)
new_closure.append(new_cell)
- return tuple(new_closure)
+ return tuple(new_closure), cell_dict
def _stringify_single(anno):
diff --git a/Lib/argparse.py b/Lib/argparse.py
index 1f4413a9897..55ecdadd8c9 100644
--- a/Lib/argparse.py
+++ b/Lib/argparse.py
@@ -748,7 +748,14 @@ def _get_help_string(self, action):
if action.default is not SUPPRESS:
defaulting_nargs = [OPTIONAL, ZERO_OR_MORE]
if action.option_strings or action.nargs in defaulting_nargs:
- help += _(' (default: %(default)s)')
+ t = self._theme
+ default_str = _(" (default: %(default)s)")
+ prefix, suffix = default_str.split("%(default)s")
+ help += (
+ f" {t.default}{prefix.lstrip()}"
+ f"{t.default_value}%(default)s"
+ f"{t.default}{suffix}{t.reset}"
+ )
return help
@@ -932,15 +939,26 @@ def __init__(self,
deprecated=False):
_option_strings = []
+ neg_option_strings = []
for option_string in option_strings:
_option_strings.append(option_string)
- if option_string.startswith('--'):
- if option_string.startswith('--no-'):
+ if len(option_string) > 2 and option_string[0] == option_string[1]:
+ # two-dash long option: '--foo' -> '--no-foo'
+ if option_string.startswith('no-', 2):
raise ValueError(f'invalid option name {option_string!r} '
f'for BooleanOptionalAction')
- option_string = '--no-' + option_string[2:]
+ option_string = option_string[:2] + 'no-' + option_string[2:]
_option_strings.append(option_string)
+ neg_option_strings.append(option_string)
+ elif len(option_string) > 2 and option_string[0] != option_string[1]:
+ # single-dash long option: '-foo' -> '-nofoo'
+ if option_string.startswith('no', 1):
+ raise ValueError(f'invalid option name {option_string!r} '
+ f'for BooleanOptionalAction')
+ option_string = option_string[:1] + 'no' + option_string[1:]
+ _option_strings.append(option_string)
+ neg_option_strings.append(option_string)
super().__init__(
option_strings=_option_strings,
@@ -950,11 +968,12 @@ def __init__(self,
required=required,
help=help,
deprecated=deprecated)
+ self.neg_option_strings = neg_option_strings
def __call__(self, parser, namespace, values, option_string=None):
if option_string in self.option_strings:
- setattr(namespace, self.dest, not option_string.startswith('--no-'))
+ setattr(namespace, self.dest, option_string not in self.neg_option_strings)
def format_usage(self):
return ' | '.join(self.option_strings)
@@ -1660,29 +1679,35 @@ def _get_positional_kwargs(self, dest, **kwargs):
def _get_optional_kwargs(self, *args, **kwargs):
# determine short and long option strings
option_strings = []
- long_option_strings = []
for option_string in args:
# error on strings that don't start with an appropriate prefix
if not option_string[0] in self.prefix_chars:
raise ValueError(
f'invalid option string {option_string!r}: '
f'must start with a character {self.prefix_chars!r}')
-
- # strings starting with two prefix characters are long options
option_strings.append(option_string)
- if len(option_string) > 1 and option_string[1] in self.prefix_chars:
- long_option_strings.append(option_string)
# infer destination, '--foo-bar' -> 'foo_bar' and '-x' -> 'x'
dest = kwargs.pop('dest', None)
if dest is None:
- if long_option_strings:
- dest_option_string = long_option_strings[0]
- else:
- dest_option_string = option_strings[0]
- dest = dest_option_string.lstrip(self.prefix_chars)
+ priority = 0
+ for option_string in option_strings:
+ if len(option_string) <= 2:
+ # short option: '-x' -> 'x'
+ if priority < 1:
+ dest = option_string.lstrip(self.prefix_chars)
+ priority = 1
+ elif option_string[1] not in self.prefix_chars:
+ # single-dash long option: '-foo' -> 'foo'
+ if priority < 2:
+ dest = option_string.lstrip(self.prefix_chars)
+ priority = 2
+ else:
+ # two-dash long option: '--foo' -> 'foo'
+ dest = option_string.lstrip(self.prefix_chars)
+ break
if not dest:
- msg = f'dest= is required for options like {option_string!r}'
+ msg = f'dest= is required for options like {repr(option_strings)[1:-1]}'
raise TypeError(msg)
dest = dest.replace('-', '_')
@@ -2749,6 +2774,14 @@ def _print_message(self, message, file=None):
except (AttributeError, OSError):
pass
+ def _get_theme(self, file=None):
+ from _colorize import can_colorize, get_theme
+
+ if self.color and can_colorize(file=file):
+ return get_theme(force_color=True).argparse
+ else:
+ return get_theme(force_no_color=True).argparse
+
# ===============
# Exiting methods
# ===============
@@ -2768,13 +2801,21 @@ def error(self, message):
should either exit or raise an exception.
"""
self.print_usage(_sys.stderr)
+ theme = self._get_theme(file=_sys.stderr)
+ fmt = _('%(prog)s: error: %(message)s\n')
+ fmt = fmt.replace('error: %(message)s',
+ f'{theme.error}error:{theme.reset} {theme.message}%(message)s{theme.reset}')
+
args = {'prog': self.prog, 'message': message}
- self.exit(2, _('%(prog)s: error: %(message)s\n') % args)
+ self.exit(2, fmt % args)
def _warning(self, message):
+ theme = self._get_theme(file=_sys.stderr)
+ fmt = _('%(prog)s: warning: %(message)s\n')
+ fmt = fmt.replace('warning: %(message)s',
+ f'{theme.warning}warning:{theme.reset} {theme.message}%(message)s{theme.reset}')
args = {'prog': self.prog, 'message': message}
- self._print_message(_('%(prog)s: warning: %(message)s\n') % args, _sys.stderr)
-
+ self._print_message(fmt % args, _sys.stderr)
def __getattr__(name):
if name == "__version__":
diff --git a/Lib/ast.py b/Lib/ast.py
index 983ac1710d0..d9743ba7ab4 100644
--- a/Lib/ast.py
+++ b/Lib/ast.py
@@ -24,7 +24,7 @@
def parse(source, filename='', mode='exec', *,
- type_comments=False, feature_version=None, optimize=-1):
+ type_comments=False, feature_version=None, optimize=-1, module=None):
"""
Parse the source into an AST node.
Equivalent to compile(source, filename, mode, PyCF_ONLY_AST).
@@ -44,7 +44,8 @@ def parse(source, filename='', mode='exec', *,
feature_version = minor
# Else it should be an int giving the minor version for 3.x.
return compile(source, filename, mode, flags,
- _feature_version=feature_version, optimize=optimize)
+ _feature_version=feature_version, optimize=optimize,
+ module=module)
def literal_eval(node_or_string):
diff --git a/Lib/asyncio/base_subprocess.py b/Lib/asyncio/base_subprocess.py
index d40af422e61..321a4e5d5d1 100644
--- a/Lib/asyncio/base_subprocess.py
+++ b/Lib/asyncio/base_subprocess.py
@@ -26,6 +26,7 @@ def __init__(self, loop, protocol, args, shell,
self._pending_calls = collections.deque()
self._pipes = {}
self._finished = False
+ self._pipes_connected = False
if stdin == subprocess.PIPE:
self._pipes[0] = None
@@ -213,6 +214,7 @@ async def _connect_pipes(self, waiter):
else:
if waiter is not None and not waiter.cancelled():
waiter.set_result(None)
+ self._pipes_connected = True
def _call(self, cb, *data):
if self._pending_calls is not None:
@@ -256,6 +258,15 @@ def _try_finish(self):
assert not self._finished
if self._returncode is None:
return
+ if not self._pipes_connected:
+ # self._pipes_connected can be False if not all pipes were connected
+ # because either the process failed to start or the self._connect_pipes task
+ # got cancelled. In this broken state we consider all pipes disconnected and
+ # to avoid hanging forever in self._wait as otherwise _exit_waiters
+ # would never be woken up, we wake them up here.
+ for waiter in self._exit_waiters:
+ if not waiter.cancelled():
+ waiter.set_result(self._returncode)
if all(p is not None and p.disconnected
for p in self._pipes.values()):
self._finished = True
diff --git a/Lib/asyncio/tools.py b/Lib/asyncio/tools.py
index f39e11fdd51..1d463ea09ba 100644
--- a/Lib/asyncio/tools.py
+++ b/Lib/asyncio/tools.py
@@ -1,6 +1,6 @@
"""Tools to analyze tasks running in asyncio programs."""
-from collections import defaultdict, namedtuple
+from collections import defaultdict
from itertools import count
from enum import Enum
import sys
diff --git a/Lib/base64.py b/Lib/base64.py
index 5d78cc09f40..f95132a4274 100644
--- a/Lib/base64.py
+++ b/Lib/base64.py
@@ -462,9 +462,12 @@ def b85decode(b):
# Delay the initialization of tables to not waste memory
# if the function is never called
if _b85dec is None:
- _b85dec = [None] * 256
+ # we don't assign to _b85dec directly to avoid issues when
+ # multiple threads call this function simultaneously
+ b85dec_tmp = [None] * 256
for i, c in enumerate(_b85alphabet):
- _b85dec[c] = i
+ b85dec_tmp[c] = i
+ _b85dec = b85dec_tmp
b = _bytes_from_decode_data(b)
padding = (-len(b)) % 5
@@ -601,7 +604,14 @@ def main():
with open(args[0], 'rb') as f:
func(f, sys.stdout.buffer)
else:
- func(sys.stdin.buffer, sys.stdout.buffer)
+ if sys.stdin.isatty():
+ # gh-138775: read terminal input data all at once to detect EOF
+ import io
+ data = sys.stdin.buffer.read()
+ buffer = io.BytesIO(data)
+ else:
+ buffer = sys.stdin.buffer
+ func(buffer, sys.stdout.buffer)
if __name__ == '__main__':
diff --git a/Lib/bdb.py b/Lib/bdb.py
index efc3e0a235a..50cf2b3f5b3 100644
--- a/Lib/bdb.py
+++ b/Lib/bdb.py
@@ -199,6 +199,8 @@ def __init__(self, skip=None, backend='settrace'):
self.frame_returning = None
self.trace_opcodes = False
self.enterframe = None
+ self.cmdframe = None
+ self.cmdlineno = None
self.code_linenos = weakref.WeakKeyDictionary()
self.backend = backend
if backend == 'monitoring':
@@ -297,7 +299,12 @@ def dispatch_line(self, frame):
self.user_line(). Raise BdbQuit if self.quitting is set.
Return self.trace_dispatch to continue tracing in this scope.
"""
- if self.stop_here(frame) or self.break_here(frame):
+ # GH-136057
+ # For line events, we don't want to stop at the same line where
+ # the latest next/step command was issued.
+ if (self.stop_here(frame) or self.break_here(frame)) and not (
+ self.cmdframe == frame and self.cmdlineno == frame.f_lineno
+ ):
self.user_line(frame)
self.restart_events()
if self.quitting: raise BdbQuit
@@ -526,7 +533,8 @@ def _set_trace_opcodes(self, trace_opcodes):
if self.monitoring_tracer:
self.monitoring_tracer.update_local_events()
- def _set_stopinfo(self, stopframe, returnframe, stoplineno=0, opcode=False):
+ def _set_stopinfo(self, stopframe, returnframe, stoplineno=0, opcode=False,
+ cmdframe=None, cmdlineno=None):
"""Set the attributes for stopping.
If stoplineno is greater than or equal to 0, then stop at line
@@ -539,6 +547,10 @@ def _set_stopinfo(self, stopframe, returnframe, stoplineno=0, opcode=False):
# stoplineno >= 0 means: stop at line >= the stoplineno
# stoplineno -1 means: don't stop at all
self.stoplineno = stoplineno
+ # cmdframe/cmdlineno is the frame/line number when the user issued
+ # step/next commands.
+ self.cmdframe = cmdframe
+ self.cmdlineno = cmdlineno
self._set_trace_opcodes(opcode)
def _set_caller_tracefunc(self, current_frame):
@@ -564,7 +576,9 @@ def set_until(self, frame, lineno=None):
def set_step(self):
"""Stop after one line of code."""
- self._set_stopinfo(None, None)
+ # set_step() could be called from signal handler so enterframe might be None
+ self._set_stopinfo(None, None, cmdframe=self.enterframe,
+ cmdlineno=getattr(self.enterframe, 'f_lineno', None))
def set_stepinstr(self):
"""Stop before the next instruction."""
@@ -572,7 +586,7 @@ def set_stepinstr(self):
def set_next(self, frame):
"""Stop on the next line in or below the given frame."""
- self._set_stopinfo(frame, None)
+ self._set_stopinfo(frame, None, cmdframe=frame, cmdlineno=frame.f_lineno)
def set_return(self, frame):
"""Stop when returning from the given frame."""
diff --git a/Lib/concurrent/futures/interpreter.py b/Lib/concurrent/futures/interpreter.py
index 53c6e757ded..85c1da2c722 100644
--- a/Lib/concurrent/futures/interpreter.py
+++ b/Lib/concurrent/futures/interpreter.py
@@ -2,7 +2,6 @@
from concurrent import interpreters
import sys
-import textwrap
from . import thread as _thread
import traceback
diff --git a/Lib/concurrent/futures/process.py b/Lib/concurrent/futures/process.py
index a14650bf5fa..a42afa68efc 100644
--- a/Lib/concurrent/futures/process.py
+++ b/Lib/concurrent/futures/process.py
@@ -474,9 +474,23 @@ def _terminate_broken(self, cause):
bpe = BrokenProcessPool("A process in the process pool was "
"terminated abruptly while the future was "
"running or pending.")
+ cause_str = None
if cause is not None:
- bpe.__cause__ = _RemoteTraceback(
- f"\n'''\n{''.join(cause)}'''")
+ cause_str = ''.join(cause)
+ else:
+ # No cause known, so report any processes that have
+ # terminated with nonzero exit codes, e.g. from a
+ # segfault. Multiple may terminate simultaneously,
+ # so include all of them in the traceback.
+ errors = []
+ for p in self.processes.values():
+ if p.exitcode is not None and p.exitcode != 0:
+ errors.append(f"Process {p.pid} terminated abruptly "
+ f"with exit code {p.exitcode}")
+ if errors:
+ cause_str = "\n".join(errors)
+ if cause_str:
+ bpe.__cause__ = _RemoteTraceback(f"\n'''\n{cause_str}'''")
# Mark pending tasks as failed.
for work_id, work_item in self.pending_work_items.items():
diff --git a/Lib/dataclasses.py b/Lib/dataclasses.py
index b98f21dcbe9..3ccb7246928 100644
--- a/Lib/dataclasses.py
+++ b/Lib/dataclasses.py
@@ -441,9 +441,11 @@ def __init__(self, globals):
self.locals = {}
self.overwrite_errors = {}
self.unconditional_adds = {}
+ self.method_annotations = {}
def add_fn(self, name, args, body, *, locals=None, return_type=MISSING,
- overwrite_error=False, unconditional_add=False, decorator=None):
+ overwrite_error=False, unconditional_add=False, decorator=None,
+ annotation_fields=None):
if locals is not None:
self.locals.update(locals)
@@ -464,16 +466,14 @@ def add_fn(self, name, args, body, *, locals=None, return_type=MISSING,
self.names.append(name)
- if return_type is not MISSING:
- self.locals[f'__dataclass_{name}_return_type__'] = return_type
- return_annotation = f'->__dataclass_{name}_return_type__'
- else:
- return_annotation = ''
+ if annotation_fields is not None:
+ self.method_annotations[name] = (annotation_fields, return_type)
+
args = ','.join(args)
body = '\n'.join(body)
# Compute the text of the entire function, add it to the text we're generating.
- self.src.append(f'{f' {decorator}\n' if decorator else ''} def {name}({args}){return_annotation}:\n{body}')
+ self.src.append(f'{f' {decorator}\n' if decorator else ''} def {name}({args}):\n{body}')
def add_fns_to_class(self, cls):
# The source to all of the functions we're generating.
@@ -509,6 +509,15 @@ def add_fns_to_class(self, cls):
# Now that we've generated the functions, assign them into cls.
for name, fn in zip(self.names, fns):
fn.__qualname__ = f"{cls.__qualname__}.{fn.__name__}"
+
+ try:
+ annotation_fields, return_type = self.method_annotations[name]
+ except KeyError:
+ pass
+ else:
+ annotate_fn = _make_annotate_function(cls, name, annotation_fields, return_type)
+ fn.__annotate__ = annotate_fn
+
if self.unconditional_adds.get(name, False):
setattr(cls, name, fn)
else:
@@ -524,6 +533,44 @@ def add_fns_to_class(self, cls):
raise TypeError(error_msg)
+def _make_annotate_function(__class__, method_name, annotation_fields, return_type):
+ # Create an __annotate__ function for a dataclass
+ # Try to return annotations in the same format as they would be
+ # from a regular __init__ function
+
+ def __annotate__(format, /):
+ Format = annotationlib.Format
+ match format:
+ case Format.VALUE | Format.FORWARDREF | Format.STRING:
+ cls_annotations = {}
+ for base in reversed(__class__.__mro__):
+ cls_annotations.update(
+ annotationlib.get_annotations(base, format=format)
+ )
+
+ new_annotations = {}
+ for k in annotation_fields:
+ new_annotations[k] = cls_annotations[k]
+
+ if return_type is not MISSING:
+ if format == Format.STRING:
+ new_annotations["return"] = annotationlib.type_repr(return_type)
+ else:
+ new_annotations["return"] = return_type
+
+ return new_annotations
+
+ case _:
+ raise NotImplementedError(format)
+
+ # This is a flag for _add_slots to know it needs to regenerate this method
+ # In order to remove references to the original class when it is replaced
+ __annotate__.__generated_by_dataclasses__ = True
+ __annotate__.__qualname__ = f"{__class__.__qualname__}.{method_name}.__annotate__"
+
+ return __annotate__
+
+
def _field_assign(frozen, name, value, self_name):
# If we're a frozen class, then assign to our fields in __init__
# via object.__setattr__. Otherwise, just use a simple
@@ -612,7 +659,7 @@ def _init_param(f):
elif f.default_factory is not MISSING:
# There's a factory function. Set a marker.
default = '=__dataclass_HAS_DEFAULT_FACTORY__'
- return f'{f.name}:__dataclass_type_{f.name}__{default}'
+ return f'{f.name}{default}'
def _init_fn(fields, std_fields, kw_only_fields, frozen, has_post_init,
@@ -635,11 +682,10 @@ def _init_fn(fields, std_fields, kw_only_fields, frozen, has_post_init,
raise TypeError(f'non-default argument {f.name!r} '
f'follows default argument {seen_default.name!r}')
- locals = {**{f'__dataclass_type_{f.name}__': f.type for f in fields},
- **{'__dataclass_HAS_DEFAULT_FACTORY__': _HAS_DEFAULT_FACTORY,
- '__dataclass_builtins_object__': object,
- }
- }
+ annotation_fields = [f.name for f in fields if f.init]
+
+ locals = {'__dataclass_HAS_DEFAULT_FACTORY__': _HAS_DEFAULT_FACTORY,
+ '__dataclass_builtins_object__': object}
body_lines = []
for f in fields:
@@ -670,7 +716,8 @@ def _init_fn(fields, std_fields, kw_only_fields, frozen, has_post_init,
[self_name] + _init_params,
body_lines,
locals=locals,
- return_type=None)
+ return_type=None,
+ annotation_fields=annotation_fields)
def _frozen_get_del_attr(cls, fields, func_builder):
@@ -1337,6 +1384,25 @@ def _add_slots(cls, is_frozen, weakref_slot, defined_fields):
or _update_func_cell_for__class__(member.fdel, cls, newcls)):
break
+ # Get new annotations to remove references to the original class
+ # in forward references
+ newcls_ann = annotationlib.get_annotations(
+ newcls, format=annotationlib.Format.FORWARDREF)
+
+ # Fix references in dataclass Fields
+ for f in getattr(newcls, _FIELDS).values():
+ try:
+ ann = newcls_ann[f.name]
+ except KeyError:
+ pass
+ else:
+ f.type = ann
+
+ # Fix the class reference in the __annotate__ method
+ init_annotate = newcls.__init__.__annotate__
+ if getattr(init_annotate, "__generated_by_dataclasses__", False):
+ _update_func_cell_for__class__(init_annotate, cls, newcls)
+
return newcls
diff --git a/Lib/doctest.py b/Lib/doctest.py
index 92a2ab4f7e6..ad8fb900f69 100644
--- a/Lib/doctest.py
+++ b/Lib/doctest.py
@@ -104,7 +104,7 @@ def _test():
import traceback
import types
import unittest
-from io import StringIO, IncrementalNewlineDecoder
+from io import StringIO, TextIOWrapper, BytesIO
from collections import namedtuple
import _colorize # Used in doctests
from _colorize import ANSIColors, can_colorize
@@ -237,10 +237,6 @@ def _normalize_module(module, depth=2):
else:
raise TypeError("Expected a module, string, or None")
-def _newline_convert(data):
- # The IO module provides a handy decoder for universal newline conversion
- return IncrementalNewlineDecoder(None, True).decode(data, True)
-
def _load_testfile(filename, package, module_relative, encoding):
if module_relative:
package = _normalize_module(package, 3)
@@ -252,10 +248,9 @@ def _load_testfile(filename, package, module_relative, encoding):
pass
if hasattr(loader, 'get_data'):
file_contents = loader.get_data(filename)
- file_contents = file_contents.decode(encoding)
# get_data() opens files as 'rb', so one must do the equivalent
# conversion as universal newlines would do.
- return _newline_convert(file_contents), filename
+ return TextIOWrapper(BytesIO(file_contents), encoding=encoding, newline=None).read(), filename
with open(filename, encoding=encoding) as f:
return f.read(), filename
diff --git a/Lib/email/_header_value_parser.py b/Lib/email/_header_value_parser.py
index 91243378dc0..c7f665b3990 100644
--- a/Lib/email/_header_value_parser.py
+++ b/Lib/email/_header_value_parser.py
@@ -796,6 +796,10 @@ def params(self):
value = urllib.parse.unquote(value, encoding='latin-1')
else:
try:
+ # Explicitly look up the codec for warning generation, see gh-140030
+ # Can be removed in 3.17
+ import codecs
+ codecs.lookup(charset)
value = value.decode(charset, 'surrogateescape')
except (LookupError, UnicodeEncodeError):
# XXX: there should really be a custom defect for
diff --git a/Lib/email/_parseaddr.py b/Lib/email/_parseaddr.py
index 84917038874..6a7c5fa06d2 100644
--- a/Lib/email/_parseaddr.py
+++ b/Lib/email/_parseaddr.py
@@ -146,8 +146,9 @@ def _parsedate_tz(data):
return None
# Check for a yy specified in two-digit format, then convert it to the
# appropriate four-digit format, according to the POSIX standard. RFC 822
- # calls for a two-digit yy, but RFC 2822 (which obsoletes RFC 822)
- # mandates a 4-digit yy. For more information, see the documentation for
+ # calls for a two-digit yy, but RFC 2822 (which obsoletes RFC 822) already
+ # mandated a 4-digit yy, and RFC 5322 (which obsoletes RFC 2822) continues
+ # this requirement. For more information, see the documentation for
# the time module.
if yy < 100:
# The year is between 1969 and 1999 (inclusive).
@@ -233,9 +234,11 @@ def __init__(self, field):
self.CR = '\r\n'
self.FWS = self.LWS + self.CR
self.atomends = self.specials + self.LWS + self.CR
- # Note that RFC 2822 now specifies '.' as obs-phrase, meaning that it
- # is obsolete syntax. RFC 2822 requires that we recognize obsolete
- # syntax, so allow dots in phrases.
+ # Note that RFC 2822 section 4.1 introduced '.' as obs-phrase to handle
+ # existing practice (periods in display names), even though it was not
+ # allowed in RFC 822. RFC 5322 section 4.1 (which obsoletes RFC 2822)
+ # continues this requirement. We must recognize obsolete syntax, so
+ # allow dots in phrases.
self.phraseends = self.atomends.replace('.', '')
self.field = field
self.commentlist = []
diff --git a/Lib/email/_policybase.py b/Lib/email/_policybase.py
index 95e79b8938b..e23843df448 100644
--- a/Lib/email/_policybase.py
+++ b/Lib/email/_policybase.py
@@ -380,7 +380,7 @@ def _fold(self, name, value, sanitize):
h = value
if h is not None:
# The Header class interprets a value of None for maxlinelen as the
- # default value of 78, as recommended by RFC 2822.
+ # default value of 78, as recommended by RFC 5322 section 2.1.1.
maxlinelen = 0
if self.max_line_length is not None:
maxlinelen = self.max_line_length
diff --git a/Lib/email/feedparser.py b/Lib/email/feedparser.py
index 9d80a5822af..6479b9bab7a 100644
--- a/Lib/email/feedparser.py
+++ b/Lib/email/feedparser.py
@@ -32,7 +32,7 @@
NLCRE_bol = re.compile(r'(\r\n|\r|\n)')
NLCRE_eol = re.compile(r'(\r\n|\r|\n)\z')
NLCRE_crack = re.compile(r'(\r\n|\r|\n)')
-# RFC 2822 $3.6.8 Optional fields. ftext is %d33-57 / %d59-126, Any character
+# RFC 5322 section 3.6.8 Optional fields. ftext is %d33-57 / %d59-126, Any character
# except controls, SP, and ":".
headerRE = re.compile(r'^(From |[\041-\071\073-\176]*:|[\t ])')
EMPTYSTRING = ''
@@ -294,7 +294,7 @@ def _parsegen(self):
return
if self._cur.get_content_maintype() == 'message':
# The message claims to be a message/* type, then what follows is
- # another RFC 2822 message.
+ # another RFC 5322 message.
for retval in self._parsegen():
if retval is NeedMoreData:
yield NeedMoreData
diff --git a/Lib/email/generator.py b/Lib/email/generator.py
index ab5bd0653e4..03524c96559 100644
--- a/Lib/email/generator.py
+++ b/Lib/email/generator.py
@@ -50,7 +50,7 @@ def __init__(self, outfp, mangle_from_=None, maxheaderlen=None, *,
expanded to 8 spaces) than maxheaderlen, the header will split as
defined in the Header class. Set maxheaderlen to zero to disable
header wrapping. The default is 78, as recommended (but not required)
- by RFC 2822.
+ by RFC 5322 section 2.1.1.
The policy keyword specifies a policy object that controls a number of
aspects of the generator's operation. If no policy is specified,
diff --git a/Lib/email/message.py b/Lib/email/message.py
index 4380e0ec50b..641fb2e944d 100644
--- a/Lib/email/message.py
+++ b/Lib/email/message.py
@@ -141,7 +141,7 @@ def _decode_uu(encoded):
class Message:
"""Basic message object.
- A message object is defined as something that has a bunch of RFC 2822
+ A message object is defined as something that has a bunch of RFC 5322
headers and a payload. It may optionally have an envelope header
(a.k.a. Unix-From or From_ header). If the message is a container (i.e. a
multipart or a message/rfc822), then the payload is a list of Message
diff --git a/Lib/email/parser.py b/Lib/email/parser.py
index 039f03cba74..c6a51dd8e37 100644
--- a/Lib/email/parser.py
+++ b/Lib/email/parser.py
@@ -2,7 +2,7 @@
# Author: Barry Warsaw, Thomas Wouters, Anthony Baxter
# Contact: email-sig@python.org
-"""A parser of RFC 2822 and MIME email messages."""
+"""A parser of RFC 5322 and MIME email messages."""
__all__ = ['Parser', 'HeaderParser', 'BytesParser', 'BytesHeaderParser',
'FeedParser', 'BytesFeedParser']
@@ -15,13 +15,13 @@
class Parser:
def __init__(self, _class=None, *, policy=compat32):
- """Parser of RFC 2822 and MIME email messages.
+ """Parser of RFC 5322 and MIME email messages.
Creates an in-memory object tree representing the email message, which
can then be manipulated and turned over to a Generator to return the
textual representation of the message.
- The string must be formatted as a block of RFC 2822 headers and header
+ The string must be formatted as a block of RFC 5322 headers and header
continuation lines, optionally preceded by a 'Unix-from' header. The
header block is terminated either by the end of the string or by a
blank line.
@@ -75,13 +75,13 @@ def parsestr(self, text, headersonly=True):
class BytesParser:
def __init__(self, *args, **kw):
- """Parser of binary RFC 2822 and MIME email messages.
+ """Parser of binary RFC 5322 and MIME email messages.
Creates an in-memory object tree representing the email message, which
can then be manipulated and turned over to a Generator to return the
textual representation of the message.
- The input must be formatted as a block of RFC 2822 headers and header
+ The input must be formatted as a block of RFC 5322 headers and header
continuation lines, optionally preceded by a 'Unix-from' header. The
header block is terminated either by the end of the input or by a
blank line.
diff --git a/Lib/email/utils.py b/Lib/email/utils.py
index 3de1f0d24a1..d4824dc3601 100644
--- a/Lib/email/utils.py
+++ b/Lib/email/utils.py
@@ -460,6 +460,10 @@ def collapse_rfc2231_value(value, errors='replace',
charset = fallback_charset
rawbytes = bytes(text, 'raw-unicode-escape')
try:
+ # Explicitly look up the codec for warning generation, see gh-140030
+ # Can be removed in 3.17
+ import codecs
+ codecs.lookup(charset)
return str(rawbytes, charset, errors)
except LookupError:
# charset is not a known codec.
diff --git a/Lib/encodings/__init__.py b/Lib/encodings/__init__.py
index e7e4ca3358e..e205ec32637 100644
--- a/Lib/encodings/__init__.py
+++ b/Lib/encodings/__init__.py
@@ -26,7 +26,7 @@
(c) Copyright CNRI, All Rights Reserved. NO WARRANTY.
-"""#"
+"""
import codecs
import sys
@@ -56,6 +56,12 @@ def normalize_encoding(encoding):
if isinstance(encoding, bytes):
encoding = str(encoding, "ascii")
+ if not encoding.isascii():
+ import warnings
+ warnings.warn(
+ "Support for non-ascii encoding names will be removed in 3.17",
+ DeprecationWarning, stacklevel=2)
+
return _normalize_encoding(encoding)
def search_function(encoding):
diff --git a/Lib/functools.py b/Lib/functools.py
index a92844ba722..8063eb5ffc3 100644
--- a/Lib/functools.py
+++ b/Lib/functools.py
@@ -1083,7 +1083,10 @@ def __call__(self, /, *args, **kwargs):
'singledispatchmethod method')
raise TypeError(f'{funcname} requires at least '
'1 positional argument')
- return self._dispatch(args[0].__class__).__get__(self._obj, self._cls)(*args, **kwargs)
+ method = self._dispatch(args[0].__class__)
+ if hasattr(method, "__get__"):
+ method = method.__get__(self._obj, self._cls)
+ return method(*args, **kwargs)
def __getattr__(self, name):
# Resolve these attributes lazily to speed up creation of
diff --git a/Lib/html/parser.py b/Lib/html/parser.py
index e50620de800..80fb8c3f929 100644
--- a/Lib/html/parser.py
+++ b/Lib/html/parser.py
@@ -24,6 +24,7 @@
entityref = re.compile('&([a-zA-Z][-.a-zA-Z0-9]*)[^a-zA-Z0-9]')
charref = re.compile('(?:[0-9]+|[xX][0-9a-fA-F]+)[^0-9a-fA-F]')
+incomplete_charref = re.compile('(?:[0-9]|[xX][0-9a-fA-F])')
attr_charref = re.compile(r'&(#[0-9]+|#[xX][0-9a-fA-F]+|[a-zA-Z][a-zA-Z0-9]*)[;=]?')
starttagopen = re.compile('<[a-zA-Z]')
@@ -304,10 +305,20 @@ def goahead(self, end):
k = k - 1
i = self.updatepos(i, k)
continue
+ match = incomplete_charref.match(rawdata, i)
+ if match:
+ if end:
+ self.handle_charref(rawdata[i+2:])
+ i = self.updatepos(i, n)
+ break
+ # incomplete
+ break
+ elif i + 3 < n: # larger than ""
+ # not the end of the buffer, and can't be confused
+ # with some other construct
+ self.handle_data("")
+ i = self.updatepos(i, i + 2)
else:
- if ";" in rawdata[i:]: # bail by consuming
- self.handle_data(rawdata[i:i+2])
- i = self.updatepos(i, i+2)
break
elif startswith('&', i):
match = entityref.match(rawdata, i)
@@ -321,15 +332,13 @@ def goahead(self, end):
continue
match = incomplete.match(rawdata, i)
if match:
- # match.group() will contain at least 2 chars
- if end and match.group() == rawdata[i:]:
- k = match.end()
- if k <= i:
- k = n
- i = self.updatepos(i, i + 1)
+ if end:
+ self.handle_entityref(rawdata[i+1:])
+ i = self.updatepos(i, n)
+ break
# incomplete
break
- elif (i + 1) < n:
+ elif i + 1 < n:
# not the end of the buffer, and can't be confused
# with some other construct
self.handle_data("&")
diff --git a/Lib/http/client.py b/Lib/http/client.py
index 425d9bdad8c..4b9a61cfc11 100644
--- a/Lib/http/client.py
+++ b/Lib/http/client.py
@@ -231,7 +231,7 @@ def _read_headers(fp, max_headers):
def _parse_header_lines(header_lines, _class=HTTPMessage):
"""
- Parses only RFC2822 headers from header lines.
+ Parses only RFC 5322 headers from header lines.
email Parser wants to see strings rather than bytes.
But a TextIOWrapper around self.rfile would buffer too many bytes
@@ -244,7 +244,7 @@ def _parse_header_lines(header_lines, _class=HTTPMessage):
return email.parser.Parser(_class=_class).parsestr(hstring)
def parse_headers(fp, _class=HTTPMessage, *, _max_headers=None):
- """Parses only RFC2822 headers from a file pointer."""
+ """Parses only RFC 5322 headers from a file pointer."""
headers = _read_headers(fp, _max_headers)
return _parse_header_lines(headers, _class)
diff --git a/Lib/idlelib/News3.txt b/Lib/idlelib/News3.txt
index 30784578cc6..53d83762f99 100644
--- a/Lib/idlelib/News3.txt
+++ b/Lib/idlelib/News3.txt
@@ -4,6 +4,9 @@ Released on 2025-10-07
=========================
+gh-129873: Simplify displaying the IDLE doc by only copying the text
+section of idle.html to idlelib/help.html. Patch by Stan Ulbrych.
+
gh-112936: IDLE - Include Shell menu in single-process mode,
though with Restart Shell and View Last Restart disabled.
Patch by Zhikang Yan.
@@ -26,9 +29,6 @@ Released on 2024-10-07
gh-120104: Fix padding in config and search dialog windows in IDLE.
-gh-129873: Simplify displaying the IDLE doc by only copying the text
-section of idle.html to idlelib/help.html. Patch by Stan Ulbrych.
-
gh-120083: Add explicit black IDLE Hovertip foreground color needed for
recent macOS. Fixes Sonoma showing unreadable white on pale yellow.
Patch by John Riggles.
diff --git a/Lib/idlelib/help.html b/Lib/idlelib/help.html
index ebff9a309d9..fc618ab727d 100644
--- a/Lib/idlelib/help.html
+++ b/Lib/idlelib/help.html
@@ -53,7 +53,7 @@ and after the window title. If there is no associated file,
do Save As instead.
Save As…
Save the current window with a Save As dialog. The file saved becomes the
-new associated file for the window. (If your file namager is set to hide
+new associated file for the window. (If your file manager is set to hide
extensions, the current extension will be omitted in the file name box.
If the new filename has no ‘.’, ‘.py’ and ‘.txt’ will be added for Python
and text files, except that on macOS Aqua,’.py’ is added for all files.)
@@ -143,8 +143,8 @@ paragraph will be formatted to less than N columns, where N defaults to 72.
New Indent Width
Open a dialog to change indent width. The accepted default by the Python
community is 4 spaces.
-
Strip Trailing Chitespace
Remove trailing space and other whitespace characters after the last
-non-whitespace character of a line by applying str.rstrip to each line,
+
Strip Trailing Whitespace
Remove trailing space and other whitespace characters after the last
+non-whitespace character of a line by applying str.rstrip() to each line,
including lines within multiline strings. Except for Shell windows,
remove extra newlines at the end of the file.
@@ -337,16 +337,16 @@ Unix and the Command key on
assume that the keys have not been re-bound to something else.)
Arrow keys move the cursor one character or line.
-
C-LeftArrow and C-RightArrow moves left or right one word.
+
C-LeftArrow and C-RightArrow moves left or right one word.
Home and End go to the beginning or end of the line.
Page Up and Page Down go up or down one screen.
-
C-Home and C-End go to beginning or end of the file.
-
Backspace and Del (or C-d) delete the previous
+
C-Home and C-End go to beginning or end of the file.
+
Backspace and Del (or C-d) delete the previous
or next character.
-
C-Backspace and C-Del delete one word left or right.
-
C-k deletes (‘kills’) everything to the right.
+
C-Backspace and C-Del delete one word left or right.
+
C-k deletes (‘kills’) everything to the right.
-
Standard keybindings (like C-c to copy and C-v to paste)
+
Standard keybindings (like C-c to copy and C-v to paste)
may work. Keybindings are selected in the Configure IDLE dialog.
@@ -390,7 +390,7 @@ one can specify a drive first.) Move into subdirectories by typing a
directory name and a separator.
Instead of waiting, or after a box is closed, open a completion box
immediately with Show Completions on the Edit menu. The default hot
-key is C-space. If one types a prefix for the desired name
+key is C-space. If one types a prefix for the desired name
before opening the box, the first match or near miss is made visible.
The result is the same as if one enters a prefix
after the box is displayed. Show Completions after a quote completes
@@ -473,9 +473,9 @@ in an editor window.
The editing features described in previous subsections work when entering
code interactively. IDLE’s Shell window also responds to the following:
-
C-c attempts to interrupt statement execution (but may fail).
-
C-d closes Shell if typed at a >>> prompt.
-
Alt-p and Alt-n (C-p and C-n on macOS)
+
C-c attempts to interrupt statement execution (but may fail).
+
C-d closes Shell if typed at a >>> prompt.
+
Alt-p and Alt-n (C-p and C-n on macOS)
retrieve to the current prompt the previous or next previously
entered statement that matches anything already typed.
Return while the cursor is on any previous statement
@@ -517,27 +517,73 @@ executed in the Tk namespace, so this file is not useful for importing
functions to be used from IDLE’s Python shell.
idle.py [-c command] [-d] [-e] [-h] [-i] [-r file] [-s] [-t title] [-] [arg] ...
-
--c command run command in the shell window
--d enable debugger and open shell window
--e open editor window
--h print help message with legal combinations and exit
--i open shell window
--r file run file in shell window
--s run $IDLESTARTUP or $PYTHONSTARTUP first, in shell window
--t title set title of shell window
-- run stdin in shell (- must be last option before args)
+
IDLE can be invoked from the command line with various options. The general syntax is:
Run the specified Python command in the shell window.
+For example, pass -c"print('Hello,World!')".
+On Windows, the outer quotes must be double quotes as shown.
Read and execute standard input in the shell window. This option must be the last one before any arguments.
+
+
+
If arguments are provided:
-
If -, -c, or r is used, all arguments are placed in
-sys.argv[1:...] and sys.argv[0] is set to '', '-c',
-or '-r'. No editor window is opened, even if that is the default
-set in the Options dialog.
-
Otherwise, arguments are files opened for editing and
-sys.argv reflects the arguments passed to IDLE itself.
+
If -, -c, or -r is used, all arguments are placed in sys.argv[1:],
+and sys.argv[0] is set to '', '-c', or '-r' respectively.
+No editor window is opened, even if that is the default set in the Options dialog.
+
Otherwise, arguments are treated as files to be opened for editing, and sys.argv reflects the arguments passed to IDLE itself.
@@ -798,7 +844,7 @@ of this page for how to use IDLE.
either in idlelib or click Help => About IDLE on the IDLE menu. This
file also maps IDLE menu items to the code that implements the item.
Except for files listed under ‘Startup’, the idlelib code is ‘private’ in
-sense that feature changes can be backported (see PEP 434).
+sense that feature changes can be backported (see PEP 434).
diff --git a/Lib/importlib/_bootstrap_external.py b/Lib/importlib/_bootstrap_external.py
index 035ae0fcae1..192c0261408 100644
--- a/Lib/importlib/_bootstrap_external.py
+++ b/Lib/importlib/_bootstrap_external.py
@@ -552,8 +552,7 @@ def decode_source(source_bytes):
import tokenize # To avoid bootstrap issues.
source_bytes_readline = _io.BytesIO(source_bytes).readline
encoding = tokenize.detect_encoding(source_bytes_readline)
- newline_decoder = _io.IncrementalNewlineDecoder(None, True)
- return newline_decoder.decode(source_bytes.decode(encoding[0]))
+ return _io.TextIOWrapper(_io.BytesIO(source_bytes), encoding=encoding[0], newline=None).read()
# Module specifications #######################################################
@@ -819,13 +818,14 @@ def get_source(self, fullname):
name=fullname) from exc
return decode_source(source_bytes)
- def source_to_code(self, data, path, *, _optimize=-1):
+ def source_to_code(self, data, path, fullname=None, *, _optimize=-1):
"""Return the code object compiled from source.
The 'data' argument can be any object type that compile() supports.
"""
return _bootstrap._call_with_frames_removed(compile, data, path, 'exec',
- dont_inherit=True, optimize=_optimize)
+ dont_inherit=True, optimize=_optimize,
+ module=fullname)
def get_code(self, fullname):
"""Concrete implementation of InspectLoader.get_code.
@@ -894,7 +894,7 @@ def get_code(self, fullname):
source_path=source_path)
if source_bytes is None:
source_bytes = self.get_data(source_path)
- code_object = self.source_to_code(source_bytes, source_path)
+ code_object = self.source_to_code(source_bytes, source_path, fullname)
_bootstrap._verbose_message('code object from {}', source_path)
if (not sys.dont_write_bytecode and bytecode_path is not None and
source_mtime is not None):
@@ -1186,7 +1186,7 @@ def get_source(self, fullname):
return ''
def get_code(self, fullname):
- return compile('', '', 'exec', dont_inherit=True)
+ return compile('', '', 'exec', dont_inherit=True, module=fullname)
def create_module(self, spec):
"""Use default semantics for module creation."""
diff --git a/Lib/importlib/abc.py b/Lib/importlib/abc.py
index 1e47495f65f..5c13432b5bd 100644
--- a/Lib/importlib/abc.py
+++ b/Lib/importlib/abc.py
@@ -108,7 +108,7 @@ def get_code(self, fullname):
source = self.get_source(fullname)
if source is None:
return None
- return self.source_to_code(source)
+ return self.source_to_code(source, '', fullname)
@abc.abstractmethod
def get_source(self, fullname):
@@ -120,12 +120,12 @@ def get_source(self, fullname):
raise ImportError
@staticmethod
- def source_to_code(data, path=''):
+ def source_to_code(data, path='', fullname=None):
"""Compile 'data' into a code object.
The 'data' argument can be anything that compile() can handle. The'path'
argument should be where the data was retrieved (when applicable)."""
- return compile(data, path, 'exec', dont_inherit=True)
+ return compile(data, path, 'exec', dont_inherit=True, module=fullname)
exec_module = _bootstrap_external._LoaderBasics.exec_module
load_module = _bootstrap_external._LoaderBasics.load_module
@@ -163,9 +163,8 @@ def get_code(self, fullname):
try:
path = self.get_filename(fullname)
except ImportError:
- return self.source_to_code(source)
- else:
- return self.source_to_code(source, path)
+ path = ''
+ return self.source_to_code(source, path, fullname)
_register(
ExecutionLoader,
diff --git a/Lib/inspect.py b/Lib/inspect.py
index bb22bab3040..8e7511b3af0 100644
--- a/Lib/inspect.py
+++ b/Lib/inspect.py
@@ -706,8 +706,8 @@ def _findclass(func):
return None
return cls
-def _finddoc(obj):
- if isclass(obj):
+def _finddoc(obj, *, search_in_class=True):
+ if search_in_class and isclass(obj):
for base in obj.__mro__:
if base is not object:
try:
@@ -747,6 +747,12 @@ def _finddoc(obj):
cls = _findclass(obj.fget)
if cls is None or getattr(cls, name) is not obj:
return None
+ # Should be tested before ismethoddescriptor()
+ elif isinstance(obj, functools.cached_property):
+ name = obj.attrname
+ cls = _findclass(obj.func)
+ if cls is None or getattr(cls, name) is not obj:
+ return None
elif ismethoddescriptor(obj) or isdatadescriptor(obj):
name = obj.__name__
cls = obj.__objclass__
@@ -767,19 +773,37 @@ def _finddoc(obj):
return doc
return None
-def getdoc(object):
+def _getowndoc(obj):
+ """Get the documentation string for an object if it is not
+ inherited from its class."""
+ try:
+ doc = object.__getattribute__(obj, '__doc__')
+ if doc is None:
+ return None
+ if obj is not type:
+ typedoc = type(obj).__doc__
+ if isinstance(typedoc, str) and typedoc == doc:
+ return None
+ return doc
+ except AttributeError:
+ return None
+
+def getdoc(object, *, fallback_to_class_doc=True, inherit_class_doc=True):
"""Get the documentation string for an object.
All tabs are expanded to spaces. To clean up docstrings that are
indented to line up with blocks of code, any whitespace than can be
uniformly removed from the second line onwards is removed."""
- try:
- doc = object.__doc__
- except AttributeError:
- return None
+ if fallback_to_class_doc:
+ try:
+ doc = object.__doc__
+ except AttributeError:
+ return None
+ else:
+ doc = _getowndoc(object)
if doc is None:
try:
- doc = _finddoc(object)
+ doc = _finddoc(object, search_in_class=inherit_class_doc)
except (AttributeError, TypeError):
return None
if not isinstance(doc, str):
diff --git a/Lib/ipaddress.py b/Lib/ipaddress.py
index aa0cf4a0620..f1062a8cd05 100644
--- a/Lib/ipaddress.py
+++ b/Lib/ipaddress.py
@@ -1546,7 +1546,7 @@ def __init__(self, address, strict=True):
if self._prefixlen == (self.max_prefixlen - 1):
self.hosts = self.__iter__
elif self._prefixlen == (self.max_prefixlen):
- self.hosts = lambda: [IPv4Address(addr)]
+ self.hosts = lambda: iter((IPv4Address(addr),))
@property
@functools.lru_cache()
@@ -2337,7 +2337,7 @@ def __init__(self, address, strict=True):
if self._prefixlen == (self.max_prefixlen - 1):
self.hosts = self.__iter__
elif self._prefixlen == self.max_prefixlen:
- self.hosts = lambda: [IPv6Address(addr)]
+ self.hosts = lambda: iter((IPv6Address(addr),))
def hosts(self):
"""Generate Iterator over usable hosts in a network.
diff --git a/Lib/json/__init__.py b/Lib/json/__init__.py
index c8fdd0d99a0..89396b25a2c 100644
--- a/Lib/json/__init__.py
+++ b/Lib/json/__init__.py
@@ -127,8 +127,9 @@ def dump(obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True,
instead of raising a ``TypeError``.
If ``ensure_ascii`` is false, then the strings written to ``fp`` can
- contain non-ASCII characters if they appear in strings contained in
- ``obj``. Otherwise, all such characters are escaped in JSON strings.
+ contain non-ASCII and non-printable characters if they appear in strings
+ contained in ``obj``. Otherwise, all such characters are escaped in JSON
+ strings.
If ``check_circular`` is false, then the circular reference check
for container types will be skipped and a circular reference will
@@ -144,10 +145,11 @@ def dump(obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True,
level of 0 will only insert newlines. ``None`` is the most compact
representation.
- If specified, ``separators`` should be an ``(item_separator, key_separator)``
- tuple. The default is ``(', ', ': ')`` if *indent* is ``None`` and
- ``(',', ': ')`` otherwise. To get the most compact JSON representation,
- you should specify ``(',', ':')`` to eliminate whitespace.
+ If specified, ``separators`` should be an ``(item_separator,
+ key_separator)`` tuple. The default is ``(', ', ': ')`` if *indent* is
+ ``None`` and ``(',', ': ')`` otherwise. To get the most compact JSON
+ representation, you should specify ``(',', ':')`` to eliminate
+ whitespace.
``default(obj)`` is a function that should return a serializable version
of obj or raise TypeError. The default simply raises TypeError.
@@ -188,9 +190,10 @@ def dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True,
(``str``, ``int``, ``float``, ``bool``, ``None``) will be skipped
instead of raising a ``TypeError``.
- If ``ensure_ascii`` is false, then the return value can contain non-ASCII
- characters if they appear in strings contained in ``obj``. Otherwise, all
- such characters are escaped in JSON strings.
+ If ``ensure_ascii`` is false, then the return value can contain
+ non-ASCII and non-printable characters if they appear in strings
+ contained in ``obj``. Otherwise, all such characters are escaped in
+ JSON strings.
If ``check_circular`` is false, then the circular reference check
for container types will be skipped and a circular reference will
@@ -206,10 +209,11 @@ def dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True,
level of 0 will only insert newlines. ``None`` is the most compact
representation.
- If specified, ``separators`` should be an ``(item_separator, key_separator)``
- tuple. The default is ``(', ', ': ')`` if *indent* is ``None`` and
- ``(',', ': ')`` otherwise. To get the most compact JSON representation,
- you should specify ``(',', ':')`` to eliminate whitespace.
+ If specified, ``separators`` should be an ``(item_separator,
+ key_separator)`` tuple. The default is ``(', ', ': ')`` if *indent* is
+ ``None`` and ``(',', ': ')`` otherwise. To get the most compact JSON
+ representation, you should specify ``(',', ':')`` to eliminate
+ whitespace.
``default(obj)`` is a function that should return a serializable version
of obj or raise TypeError. The default simply raises TypeError.
@@ -280,11 +284,12 @@ def load(fp, *, cls=None, object_hook=None, parse_float=None,
``object_hook`` will be used instead of the ``dict``. This feature
can be used to implement custom decoders (e.g. JSON-RPC class hinting).
- ``object_pairs_hook`` is an optional function that will be called with the
- result of any object literal decoded with an ordered list of pairs. The
- return value of ``object_pairs_hook`` will be used instead of the ``dict``.
- This feature can be used to implement custom decoders. If ``object_hook``
- is also defined, the ``object_pairs_hook`` takes priority.
+ ``object_pairs_hook`` is an optional function that will be called with
+ the result of any object literal decoded with an ordered list of pairs.
+ The return value of ``object_pairs_hook`` will be used instead of the
+ ``dict``. This feature can be used to implement custom decoders. If
+ ``object_hook`` is also defined, the ``object_pairs_hook`` takes
+ priority.
To use a custom ``JSONDecoder`` subclass, specify it with the ``cls``
kwarg; otherwise ``JSONDecoder`` is used.
@@ -305,11 +310,12 @@ def loads(s, *, cls=None, object_hook=None, parse_float=None,
``object_hook`` will be used instead of the ``dict``. This feature
can be used to implement custom decoders (e.g. JSON-RPC class hinting).
- ``object_pairs_hook`` is an optional function that will be called with the
- result of any object literal decoded with an ordered list of pairs. The
- return value of ``object_pairs_hook`` will be used instead of the ``dict``.
- This feature can be used to implement custom decoders. If ``object_hook``
- is also defined, the ``object_pairs_hook`` takes priority.
+ ``object_pairs_hook`` is an optional function that will be called with
+ the result of any object literal decoded with an ordered list of pairs.
+ The return value of ``object_pairs_hook`` will be used instead of the
+ ``dict``. This feature can be used to implement custom decoders. If
+ ``object_hook`` is also defined, the ``object_pairs_hook`` takes
+ priority.
``parse_float``, if specified, will be called with the string
of every JSON float to be decoded. By default this is equivalent to
diff --git a/Lib/json/decoder.py b/Lib/json/decoder.py
index ff4bfcdcc40..92ad6352557 100644
--- a/Lib/json/decoder.py
+++ b/Lib/json/decoder.py
@@ -297,10 +297,10 @@ def __init__(self, *, object_hook=None, parse_float=None,
place of the given ``dict``. This can be used to provide custom
deserializations (e.g. to support JSON-RPC class hinting).
- ``object_pairs_hook``, if specified will be called with the result of
- every JSON object decoded with an ordered list of pairs. The return
- value of ``object_pairs_hook`` will be used instead of the ``dict``.
- This feature can be used to implement custom decoders.
+ ``object_pairs_hook``, if specified will be called with the result
+ of every JSON object decoded with an ordered list of pairs. The
+ return value of ``object_pairs_hook`` will be used instead of the
+ ``dict``. This feature can be used to implement custom decoders.
If ``object_hook`` is also defined, the ``object_pairs_hook`` takes
priority.
diff --git a/Lib/json/encoder.py b/Lib/json/encoder.py
index bc446e0f377..4c70e8b75ed 100644
--- a/Lib/json/encoder.py
+++ b/Lib/json/encoder.py
@@ -111,9 +111,10 @@ def __init__(self, *, skipkeys=False, ensure_ascii=True,
encoding of keys that are not str, int, float, bool or None.
If skipkeys is True, such items are simply skipped.
- If ensure_ascii is true, the output is guaranteed to be str
- objects with all incoming non-ASCII characters escaped. If
- ensure_ascii is false, the output can contain non-ASCII characters.
+ If ensure_ascii is true, the output is guaranteed to be str objects
+ with all incoming non-ASCII and non-printable characters escaped.
+ If ensure_ascii is false, the output can contain non-ASCII and
+ non-printable characters.
If check_circular is true, then lists, dicts, and custom encoded
objects will be checked for circular references during encoding to
@@ -134,14 +135,15 @@ def __init__(self, *, skipkeys=False, ensure_ascii=True,
indent level. An indent level of 0 will only insert newlines.
None is the most compact representation.
- If specified, separators should be an (item_separator, key_separator)
- tuple. The default is (', ', ': ') if *indent* is ``None`` and
- (',', ': ') otherwise. To get the most compact JSON representation,
- you should specify (',', ':') to eliminate whitespace.
+ If specified, separators should be an (item_separator,
+ key_separator) tuple. The default is (', ', ': ') if *indent* is
+ ``None`` and (',', ': ') otherwise. To get the most compact JSON
+ representation, you should specify (',', ':') to eliminate
+ whitespace.
If specified, default is a function that gets called for objects
- that can't otherwise be serialized. It should return a JSON encodable
- version of the object or raise a ``TypeError``.
+ that can't otherwise be serialized. It should return a JSON
+ encodable version of the object or raise a ``TypeError``.
"""
@@ -262,17 +264,6 @@ def floatstr(o, allow_nan=self.allow_nan,
def _make_iterencode(markers, _default, _encoder, _indent, _floatstr,
_key_separator, _item_separator, _sort_keys, _skipkeys, _one_shot,
- ## HACK: hand-optimized bytecode; turn globals into locals
- ValueError=ValueError,
- dict=dict,
- float=float,
- id=id,
- int=int,
- isinstance=isinstance,
- list=list,
- str=str,
- tuple=tuple,
- _intstr=int.__repr__,
):
def _iterencode_list(lst, _current_indent_level):
@@ -309,7 +300,7 @@ def _iterencode_list(lst, _current_indent_level):
# Subclasses of int/float may override __repr__, but we still
# want to encode them as integers/floats in JSON. One example
# within the standard library is IntEnum.
- yield buf + _intstr(value)
+ yield buf + int.__repr__(value)
elif isinstance(value, float):
# see comment above for int
yield buf + _floatstr(value)
@@ -372,7 +363,7 @@ def _iterencode_dict(dct, _current_indent_level):
key = 'null'
elif isinstance(key, int):
# see comment for int/float in _make_iterencode
- key = _intstr(key)
+ key = int.__repr__(key)
elif _skipkeys:
continue
else:
@@ -397,7 +388,7 @@ def _iterencode_dict(dct, _current_indent_level):
yield 'false'
elif isinstance(value, int):
# see comment for int/float in _make_iterencode
- yield _intstr(value)
+ yield int.__repr__(value)
elif isinstance(value, float):
# see comment for int/float in _make_iterencode
yield _floatstr(value)
@@ -432,7 +423,7 @@ def _iterencode(o, _current_indent_level):
yield 'false'
elif isinstance(o, int):
# see comment for int/float in _make_iterencode
- yield _intstr(o)
+ yield int.__repr__(o)
elif isinstance(o, float):
# see comment for int/float in _make_iterencode
yield _floatstr(o)
@@ -456,4 +447,13 @@ def _iterencode(o, _current_indent_level):
raise
if markers is not None:
del markers[markerid]
- return _iterencode
+
+ def _iterencode_once(o, _current_indent_level):
+ nonlocal _iterencode, _iterencode_dict, _iterencode_list
+ try:
+ yield from _iterencode(o, _current_indent_level)
+ finally:
+ # Break reference cycles due to mutually recursive closures:
+ del _iterencode, _iterencode_dict, _iterencode_list
+
+ return _iterencode_once
diff --git a/Lib/linecache.py b/Lib/linecache.py
index ef3b2d9136b..b5bf9dbdd3c 100644
--- a/Lib/linecache.py
+++ b/Lib/linecache.py
@@ -224,21 +224,58 @@ def lazycache(filename, module_globals):
def _make_lazycache_entry(filename, module_globals):
if not filename or (filename.startswith('<') and filename.endswith('>')):
return None
- # Try for a __loader__, if available
- if module_globals and '__name__' in module_globals:
- spec = module_globals.get('__spec__')
- name = getattr(spec, 'name', None) or module_globals['__name__']
- loader = getattr(spec, 'loader', None)
- if loader is None:
- loader = module_globals.get('__loader__')
- get_source = getattr(loader, 'get_source', None)
- if name and get_source:
- def get_lines(name=name, *args, **kwargs):
- return get_source(name, *args, **kwargs)
- return (get_lines,)
- return None
+ if module_globals is not None and not isinstance(module_globals, dict):
+ raise TypeError(f'module_globals must be a dict, not {type(module_globals).__qualname__}')
+ if not module_globals or '__name__' not in module_globals:
+ return None
+ spec = module_globals.get('__spec__')
+ name = getattr(spec, 'name', None) or module_globals['__name__']
+ if name is None:
+ return None
+
+ loader = _bless_my_loader(module_globals)
+ if loader is None:
+ return None
+
+ get_source = getattr(loader, 'get_source', None)
+ if get_source is None:
+ return None
+
+ def get_lines(name=name, *args, **kwargs):
+ return get_source(name, *args, **kwargs)
+ return (get_lines,)
+
+def _bless_my_loader(module_globals):
+ # Similar to _bless_my_loader() in importlib._bootstrap_external,
+ # but always emits warnings instead of errors.
+ loader = module_globals.get('__loader__')
+ if loader is None and '__spec__' not in module_globals:
+ return None
+ spec = module_globals.get('__spec__')
+
+ # The __main__ module has __spec__ = None.
+ if spec is None and module_globals.get('__name__') == '__main__':
+ return loader
+
+ spec_loader = getattr(spec, 'loader', None)
+ if spec_loader is None:
+ import warnings
+ warnings.warn(
+ 'Module globals is missing a __spec__.loader',
+ DeprecationWarning)
+ return loader
+
+ assert spec_loader is not None
+ if loader is not None and loader != spec_loader:
+ import warnings
+ warnings.warn(
+ 'Module globals; __loader__ != __spec__.loader',
+ DeprecationWarning)
+ return loader
+
+ return spec_loader
def _register_code(code, string, name):
diff --git a/Lib/mailbox.py b/Lib/mailbox.py
index b00d9e8634c..4a44642765c 100644
--- a/Lib/mailbox.py
+++ b/Lib/mailbox.py
@@ -2090,8 +2090,6 @@ def closed(self):
return False
return self._file.closed
- __class_getitem__ = classmethod(GenericAlias)
-
class _PartialFile(_ProxyFile):
"""A read-only wrapper of part of a file."""
diff --git a/Lib/mimetypes.py b/Lib/mimetypes.py
index 48a9f430d45..07ac079186f 100644
--- a/Lib/mimetypes.py
+++ b/Lib/mimetypes.py
@@ -486,26 +486,28 @@ def _default_mime_types():
'.wiz' : 'application/msword',
'.nq' : 'application/n-quads',
'.nt' : 'application/n-triples',
+ '.cjs' : 'application/node',
'.bin' : 'application/octet-stream',
'.a' : 'application/octet-stream',
- '.dll' : 'application/octet-stream',
- '.exe' : 'application/octet-stream',
'.o' : 'application/octet-stream',
'.obj' : 'application/octet-stream',
'.so' : 'application/octet-stream',
'.oda' : 'application/oda',
'.ogx' : 'application/ogg',
'.pdf' : 'application/pdf',
+ '.ai' : 'application/pdf',
'.p7c' : 'application/pkcs7-mime',
'.ps' : 'application/postscript',
- '.ai' : 'application/postscript',
'.eps' : 'application/postscript',
+ '.rtf' : 'application/rtf',
'.texi' : 'application/texinfo',
'.texinfo': 'application/texinfo',
'.toml' : 'application/toml',
'.trig' : 'application/trig',
'.m3u' : 'application/vnd.apple.mpegurl',
'.m3u8' : 'application/vnd.apple.mpegurl',
+ '.dll' : 'application/vnd.microsoft.portable-executable',
+ '.exe' : 'application/vnd.microsoft.portable-executable',
'.xls' : 'application/vnd.ms-excel',
'.xlb' : 'application/vnd.ms-excel',
'.eot' : 'application/vnd.ms-fontobject',
@@ -648,7 +650,6 @@ def _default_mime_types():
'.pl' : 'text/plain',
'.srt' : 'text/plain',
'.rtx' : 'text/richtext',
- '.rtf' : 'text/rtf',
'.tsv' : 'text/tab-separated-values',
'.vtt' : 'text/vtt',
'.py' : 'text/x-python',
@@ -681,11 +682,9 @@ def _default_mime_types():
# Please sort these too
common_types = _common_types_default = {
- '.rtf' : 'application/rtf',
'.apk' : 'application/vnd.android.package-archive',
'.midi': 'audio/midi',
'.mid' : 'audio/midi',
- '.jpg' : 'image/jpg',
'.pict': 'image/pict',
'.pct' : 'image/pict',
'.pic' : 'image/pict',
diff --git a/Lib/modulefinder.py b/Lib/modulefinder.py
index ac478ee7f51..b115d99ab30 100644
--- a/Lib/modulefinder.py
+++ b/Lib/modulefinder.py
@@ -334,7 +334,7 @@ def load_module(self, fqname, fp, pathname, file_info):
self.msgout(2, "load_module ->", m)
return m
if type == _PY_SOURCE:
- co = compile(fp.read(), pathname, 'exec')
+ co = compile(fp.read(), pathname, 'exec', module=fqname)
elif type == _PY_COMPILED:
try:
data = fp.read()
diff --git a/Lib/multiprocessing/heap.py b/Lib/multiprocessing/heap.py
index 6217dfe1268..5c835648395 100644
--- a/Lib/multiprocessing/heap.py
+++ b/Lib/multiprocessing/heap.py
@@ -324,10 +324,6 @@ class BufferWrapper(object):
_heap = Heap()
def __init__(self, size):
- if size < 0:
- raise ValueError("Size {0:n} out of range".format(size))
- if sys.maxsize <= size:
- raise OverflowError("Size {0:n} too large".format(size))
block = BufferWrapper._heap.malloc(size)
self._state = (block, size)
util.Finalize(self, BufferWrapper._heap.free, args=(block,))
diff --git a/Lib/multiprocessing/resource_tracker.py b/Lib/multiprocessing/resource_tracker.py
index c53092f6e34..b0f9099f4a5 100644
--- a/Lib/multiprocessing/resource_tracker.py
+++ b/Lib/multiprocessing/resource_tracker.py
@@ -15,6 +15,7 @@
# this resource tracker process, "killall python" would probably leave unlinked
# resources.
+import base64
import os
import signal
import sys
@@ -22,6 +23,8 @@
import warnings
from collections import deque
+import json
+
from . import spawn
from . import util
@@ -111,7 +114,12 @@ def _stop_locked(
close(self._fd)
self._fd = None
- _, status = waitpid(self._pid, 0)
+ try:
+ _, status = waitpid(self._pid, 0)
+ except ChildProcessError:
+ self._pid = None
+ self._exitcode = None
+ return
self._pid = None
@@ -191,6 +199,17 @@ def _launch(self):
finally:
os.close(r)
+ def _make_probe_message(self):
+ """Return a JSON-encoded probe message."""
+ return (
+ json.dumps(
+ {"cmd": "PROBE", "rtype": "noop"},
+ ensure_ascii=True,
+ separators=(",", ":"),
+ )
+ + "\n"
+ ).encode("ascii")
+
def _ensure_running_and_write(self, msg=None):
with self._lock:
if self._lock._recursion_count() > 1:
@@ -202,7 +221,7 @@ def _ensure_running_and_write(self, msg=None):
if self._fd is not None:
# resource tracker was launched before, is it still running?
if msg is None:
- to_send = b'PROBE:0:noop\n'
+ to_send = self._make_probe_message()
else:
to_send = msg
try:
@@ -229,7 +248,7 @@ def _check_alive(self):
try:
# We cannot use send here as it calls ensure_running, creating
# a cycle.
- os.write(self._fd, b'PROBE:0:noop\n')
+ os.write(self._fd, self._make_probe_message())
except OSError:
return False
else:
@@ -248,11 +267,25 @@ def _write(self, msg):
assert nbytes == len(msg), f"{nbytes=} != {len(msg)=}"
def _send(self, cmd, name, rtype):
- msg = f"{cmd}:{name}:{rtype}\n".encode("ascii")
- if len(msg) > 512:
- # posix guarantees that writes to a pipe of less than PIPE_BUF
- # bytes are atomic, and that PIPE_BUF >= 512
- raise ValueError('msg too long')
+ # POSIX guarantees that writes to a pipe of less than PIPE_BUF (512 on Linux)
+ # bytes are atomic. Therefore, we want the message to be shorter than 512 bytes.
+ # POSIX shm_open() and sem_open() require the name, including its leading slash,
+ # to be at most NAME_MAX bytes (255 on Linux)
+ # With json.dump(..., ensure_ascii=True) every non-ASCII byte becomes a 6-char
+ # escape like \uDC80.
+ # As we want the overall message to be kept atomic and therefore smaller than 512,
+ # we encode encode the raw name bytes with URL-safe Base64 - so a 255 long name
+ # will not exceed 340 bytes.
+ b = name.encode('utf-8', 'surrogateescape')
+ if len(b) > 255:
+ raise ValueError('shared memory name too long (max 255 bytes)')
+ b64 = base64.urlsafe_b64encode(b).decode('ascii')
+
+ payload = {"cmd": cmd, "rtype": rtype, "base64_name": b64}
+ msg = (json.dumps(payload, ensure_ascii=True, separators=(",", ":")) + "\n").encode("ascii")
+
+ # The entire JSON message is guaranteed < PIPE_BUF (512 bytes) by construction.
+ assert len(msg) <= 512, f"internal error: message too long ({len(msg)} bytes)"
self._ensure_running_and_write(msg)
@@ -285,7 +318,23 @@ def main(fd):
with open(fd, 'rb') as f:
for line in f:
try:
- cmd, name, rtype = line.strip().decode('ascii').split(':')
+ try:
+ obj = json.loads(line.decode('ascii'))
+ except Exception as e:
+ raise ValueError("malformed resource_tracker message: %r" % (line,)) from e
+
+ cmd = obj["cmd"]
+ rtype = obj["rtype"]
+ b64 = obj.get("base64_name", "")
+
+ if not isinstance(cmd, str) or not isinstance(rtype, str) or not isinstance(b64, str):
+ raise ValueError("malformed resource_tracker fields: %r" % (obj,))
+
+ try:
+ name = base64.urlsafe_b64decode(b64).decode('utf-8', 'surrogateescape')
+ except ValueError as e:
+ raise ValueError("malformed resource_tracker base64_name: %r" % (b64,)) from e
+
cleanup_func = _CLEANUP_FUNCS.get(rtype, None)
if cleanup_func is None:
raise ValueError(
diff --git a/Lib/multiprocessing/util.py b/Lib/multiprocessing/util.py
index a1a537dd48d..549fb07c275 100644
--- a/Lib/multiprocessing/util.py
+++ b/Lib/multiprocessing/util.py
@@ -126,12 +126,14 @@ def is_abstract_socket_namespace(address):
# Function returning a temp directory which will be removed on exit
#
-# Maximum length of a socket file path is usually between 92 and 108 [1],
-# but Linux is known to use a size of 108 [2]. BSD-based systems usually
-# use a size of 104 or 108 and Windows does not create AF_UNIX sockets.
+# Maximum length of a NULL-terminated [1] socket file path is usually
+# between 92 and 108 [2], but Linux is known to use a size of 108 [3].
+# BSD-based systems usually use a size of 104 or 108 and Windows does
+# not create AF_UNIX sockets.
#
-# [1]: https://pubs.opengroup.org/onlinepubs/9799919799/basedefs/sys_un.h.html
-# [2]: https://man7.org/linux/man-pages/man7/unix.7.html.
+# [1]: https://github.com/python/cpython/issues/140734
+# [2]: https://pubs.opengroup.org/onlinepubs/9799919799/basedefs/sys_un.h.html
+# [3]: https://man7.org/linux/man-pages/man7/unix.7.html
if sys.platform == 'linux':
_SUN_PATH_MAX = 108
@@ -171,11 +173,13 @@ def _get_base_temp_dir(tempfile):
# generated by tempfile._RandomNameSequence, which, by design,
# is 8 characters long.
#
- # Thus, the length of socket filename will be:
+ # Thus, the socket file path length (without NULL terminator) will be:
#
# len(base_tempdir + '/pymp-XXXXXXXX' + '/sock-XXXXXXXX')
sun_path_len = len(base_tempdir) + 14 + 14
- if sun_path_len <= _SUN_PATH_MAX:
+ # Strict inequality to account for the NULL terminator.
+ # See https://github.com/python/cpython/issues/140734.
+ if sun_path_len < _SUN_PATH_MAX:
return base_tempdir
# Fallback to the default system-wide temporary directory.
# This ignores user-defined environment variables.
@@ -201,7 +205,7 @@ def _get_base_temp_dir(tempfile):
return base_tempdir
warn("Ignoring user-defined temporary directory: %s", base_tempdir)
# at most max(map(len, dirlist)) + 14 + 14 = 36 characters
- assert len(base_system_tempdir) + 14 + 14 <= _SUN_PATH_MAX
+ assert len(base_system_tempdir) + 14 + 14 < _SUN_PATH_MAX
return base_system_tempdir
def get_temp_dir():
diff --git a/Lib/pdb.py b/Lib/pdb.py
index 4ee12d17a61..8e9502cb9e6 100644
--- a/Lib/pdb.py
+++ b/Lib/pdb.py
@@ -346,8 +346,8 @@ def __init__(self, completekey='tab', stdin=None, stdout=None, skip=None,
bdb.Bdb.__init__(self, skip=skip, backend=backend if backend else get_default_backend())
cmd.Cmd.__init__(self, completekey, stdin, stdout)
sys.audit("pdb.Pdb")
- if stdout:
- self.use_rawinput = 0
+ if stdin:
+ self.use_rawinput = False
self.prompt = '(Pdb) '
self.aliases = {}
self.displaying = {}
@@ -398,6 +398,12 @@ def __init__(self, completekey='tab', stdin=None, stdout=None, skip=None,
self._current_task = None
+ self.lineno = None
+ self.stack = []
+ self.curindex = 0
+ self.curframe = None
+ self._user_requested_quit = False
+
def set_trace(self, frame=None, *, commands=None):
Pdb._last_pdb_instance = self
if frame is None:
@@ -474,7 +480,7 @@ def forget(self):
self.lineno = None
self.stack = []
self.curindex = 0
- if hasattr(self, 'curframe') and self.curframe:
+ if self.curframe:
self.curframe.f_globals.pop('__pdb_convenience_variables', None)
self.curframe = None
self.tb_lineno.clear()
@@ -1493,7 +1499,7 @@ def checkline(self, filename, lineno, module_globals=None):
"""
# this method should be callable before starting debugging, so default
# to "no globals" if there is no current frame
- frame = getattr(self, 'curframe', None)
+ frame = self.curframe
if module_globals is None:
module_globals = frame.f_globals if frame else None
line = linecache.getline(filename, lineno, module_globals)
@@ -3542,7 +3548,15 @@ def exit_with_permission_help_text():
sys.exit(1)
-def main():
+def parse_args():
+ # We want pdb to be as intuitive as possible to users, so we need to do some
+ # heuristic parsing to deal with ambiguity.
+ # For example:
+ # "python -m pdb -m foo -p 1" should pass "-p 1" to "foo".
+ # "python -m pdb foo.py -m bar" should pass "-m bar" to "foo.py".
+ # "python -m pdb -m foo -m bar" should pass "-m bar" to "foo".
+ # This require some customized parsing logic to find the actual debug target.
+
import argparse
parser = argparse.ArgumentParser(
@@ -3553,28 +3567,48 @@ def main():
color=True,
)
- # We need to maunally get the script from args, because the first positional
- # arguments could be either the script we need to debug, or the argument
- # to the -m module
+ # Get all the commands out first. For backwards compatibility, we allow
+ # -c commands to be after the target.
parser.add_argument('-c', '--command', action='append', default=[], metavar='command', dest='commands',
help='pdb commands to execute as if given in a .pdbrc file')
- parser.add_argument('-m', metavar='module', dest='module')
- parser.add_argument('-p', '--pid', type=int, help="attach to the specified PID", default=None)
-
- if len(sys.argv) == 1:
- # If no arguments were given (python -m pdb), print the whole help message.
- # Without this check, argparse would only complain about missing required arguments.
- parser.print_help()
- sys.exit(2)
opts, args = parser.parse_known_args()
- if opts.pid:
- # If attaching to a remote pid, unrecognized arguments are not allowed.
- # This will raise an error if there are extra unrecognized arguments.
- opts = parser.parse_args()
- if opts.module:
- parser.error("argument -m: not allowed with argument --pid")
+ if not args:
+ # If no arguments were given (python -m pdb), print the whole help message.
+ # Without this check, argparse would only complain about missing required arguments.
+ # We need to add the arguments definitions here to get a proper help message.
+ parser.add_argument('-m', metavar='module', dest='module')
+ parser.add_argument('-p', '--pid', type=int, help="attach to the specified PID", default=None)
+ parser.print_help()
+ sys.exit(2)
+ elif args[0] == '-p' or args[0] == '--pid':
+ # Attach to a pid
+ parser.add_argument('-p', '--pid', type=int, help="attach to the specified PID", default=None)
+ opts, args = parser.parse_known_args()
+ if args:
+ # For --pid, any extra arguments are invalid.
+ parser.error(f"unrecognized arguments: {' '.join(args)}")
+ elif args[0] == '-m':
+ # Debug a module, we only need the first -m module argument.
+ # The rest is passed to the module itself.
+ parser.add_argument('-m', metavar='module', dest='module')
+ opt_module = parser.parse_args(args[:2])
+ opts.module = opt_module.module
+ args = args[2:]
+ elif args[0].startswith('-'):
+ # Invalid argument before the script name.
+ invalid_args = list(itertools.takewhile(lambda a: a.startswith('-'), args))
+ parser.error(f"unrecognized arguments: {' '.join(invalid_args)}")
+
+ # Otherwise it's debugging a script and we already parsed all -c commands.
+
+ return opts, args
+
+def main():
+ opts, args = parse_args()
+
+ if getattr(opts, 'pid', None) is not None:
try:
attach(opts.pid, opts.commands)
except RuntimeError:
@@ -3586,31 +3620,10 @@ def main():
except PermissionError:
exit_with_permission_help_text()
return
- elif opts.module:
- # If a module is being debugged, we consider the arguments after "-m module" to
- # be potential arguments to the module itself. We need to parse the arguments
- # before "-m" to check if there is any invalid argument.
- # e.g. "python -m pdb -m foo --spam" means passing "--spam" to "foo"
- # "python -m pdb --spam -m foo" means passing "--spam" to "pdb" and is invalid
- idx = sys.argv.index('-m')
- args_to_pdb = sys.argv[1:idx]
- # This will raise an error if there are invalid arguments
- parser.parse_args(args_to_pdb)
- else:
- # If a script is being debugged, then pdb expects the script name as the first argument.
- # Anything before the script is considered an argument to pdb itself, which would
- # be invalid because it's not parsed by argparse.
- invalid_args = list(itertools.takewhile(lambda a: a.startswith('-'), args))
- if invalid_args:
- parser.error(f"unrecognized arguments: {' '.join(invalid_args)}")
- sys.exit(2)
-
- if opts.module:
+ elif getattr(opts, 'module', None) is not None:
file = opts.module
target = _ModuleTarget(file)
else:
- if not args:
- parser.error("no module or script to run")
file = args.pop(0)
if file.endswith('.pyz'):
target = _ZipTarget(file)
diff --git a/Lib/pickletools.py b/Lib/pickletools.py
index 254b6c7fcc9..29baf3be7eb 100644
--- a/Lib/pickletools.py
+++ b/Lib/pickletools.py
@@ -2839,7 +2839,7 @@ def __init__(self, value):
}
-if __name__ == "__main__":
+def _main(args=None):
import argparse
parser = argparse.ArgumentParser(
description='disassemble one or more pickle files',
@@ -2864,7 +2864,7 @@ def __init__(self, value):
'-p', '--preamble', default="==> {name} <==",
help='if more than one pickle file is specified, print this before'
' each disassembly')
- args = parser.parse_args()
+ args = parser.parse_args(args)
annotate = 30 if args.annotate else 0
memo = {} if args.memo else None
if args.output is None:
@@ -2885,3 +2885,7 @@ def __init__(self, value):
finally:
if output is not sys.stdout:
output.close()
+
+
+if __name__ == "__main__":
+ _main()
diff --git a/Lib/platform.py b/Lib/platform.py
index 4db93bea2a3..b5017dbdb02 100644
--- a/Lib/platform.py
+++ b/Lib/platform.py
@@ -197,7 +197,7 @@ def libc_ver(executable=None, lib='', version='', chunksize=16384):
| (GLIBC_([0-9.]+))
| (libc(_\w+)?\.so(?:\.(\d[0-9.]*))?)
| (musl-([0-9.]+))
- | (libc.musl(?:-\w+)?.so(?:\.(\d[0-9.]*))?)
+ | ((?:libc\.|ld-)musl(?:-\w+)?.so(?:\.(\d[0-9.]*))?)
""",
re.ASCII | re.VERBOSE)
@@ -236,7 +236,7 @@ def libc_ver(executable=None, lib='', version='', chunksize=16384):
elif V(glibcversion) > V(ver):
ver = glibcversion
elif so:
- if lib != 'glibc':
+ if lib not in ('glibc', 'musl'):
lib = 'libc'
if soversion and (not ver or V(soversion) > V(ver)):
ver = soversion
diff --git a/Lib/profiling/sampling/__main__.py b/Lib/profiling/sampling/__main__.py
index a76ca62e2cd..cd1425b8b9c 100644
--- a/Lib/profiling/sampling/__main__.py
+++ b/Lib/profiling/sampling/__main__.py
@@ -15,7 +15,7 @@
"""
LINUX_PERMISSION_ERROR = """
-🔒 Tachyon was unable to acess process memory. This could be because tachyon
+🔒 Tachyon was unable to access process memory. This could be because tachyon
has insufficient privileges (the required capability is CAP_SYS_PTRACE).
Unprivileged processes cannot trace processes that they cannot send signals
to or those running set-user-ID/set-group-ID programs, for security reasons.
diff --git a/Lib/profiling/sampling/_sync_coordinator.py b/Lib/profiling/sampling/_sync_coordinator.py
index 8716e654104..be63dbe3e90 100644
--- a/Lib/profiling/sampling/_sync_coordinator.py
+++ b/Lib/profiling/sampling/_sync_coordinator.py
@@ -10,6 +10,7 @@
import socket
import runpy
import time
+import types
from typing import List, NoReturn
@@ -175,15 +176,21 @@ def _execute_script(script_path: str, script_args: List[str], cwd: str) -> None:
try:
with open(script_path, 'rb') as f:
source_code = f.read()
+
except FileNotFoundError as e:
raise TargetError(f"Script file not found: {script_path}") from e
except PermissionError as e:
raise TargetError(f"Permission denied reading script: {script_path}") from e
try:
- # Compile and execute the script
- code = compile(source_code, script_path, 'exec')
- exec(code, {'__name__': '__main__', '__file__': script_path})
+ main_module = types.ModuleType("__main__")
+ main_module.__file__ = script_path
+ main_module.__builtins__ = __builtins__
+ # gh-140729: Create a __mp_main__ module to allow pickling
+ sys.modules['__main__'] = sys.modules['__mp_main__'] = main_module
+
+ code = compile(source_code, script_path, 'exec', module='__main__')
+ exec(code, main_module.__dict__)
except SyntaxError as e:
raise TargetError(f"Syntax error in script {script_path}: {e}") from e
except SystemExit:
diff --git a/Lib/profiling/sampling/collector.py b/Lib/profiling/sampling/collector.py
index b7a033ac0a6..27d40156d1f 100644
--- a/Lib/profiling/sampling/collector.py
+++ b/Lib/profiling/sampling/collector.py
@@ -1,23 +1,19 @@
from abc import ABC, abstractmethod
-
-# Enums are slow
-THREAD_STATE_RUNNING = 0
-THREAD_STATE_IDLE = 1
-THREAD_STATE_GIL_WAIT = 2
-THREAD_STATE_UNKNOWN = 3
-
-STATUS = {
- THREAD_STATE_RUNNING: "running",
- THREAD_STATE_IDLE: "idle",
- THREAD_STATE_GIL_WAIT: "gil_wait",
- THREAD_STATE_UNKNOWN: "unknown",
-}
+from .constants import (
+ THREAD_STATUS_HAS_GIL,
+ THREAD_STATUS_ON_CPU,
+ THREAD_STATUS_UNKNOWN,
+ THREAD_STATUS_GIL_REQUESTED,
+)
class Collector(ABC):
@abstractmethod
def collect(self, stack_frames):
"""Collect profiling data from stack frames."""
+ def collect_failed_sample(self):
+ """Collect data about a failed sample attempt."""
+
@abstractmethod
def export(self, filename):
"""Export collected data to a file."""
@@ -26,8 +22,14 @@ def _iter_all_frames(self, stack_frames, skip_idle=False):
"""Iterate over all frame stacks from all interpreters and threads."""
for interpreter_info in stack_frames:
for thread_info in interpreter_info.threads:
- if skip_idle and thread_info.status != THREAD_STATE_RUNNING:
- continue
+ # skip_idle now means: skip if thread is not actively running
+ # A thread is "active" if it has the GIL OR is on CPU
+ if skip_idle:
+ status_flags = thread_info.status
+ has_gil = bool(status_flags & THREAD_STATUS_HAS_GIL)
+ on_cpu = bool(status_flags & THREAD_STATUS_ON_CPU)
+ if not (has_gil or on_cpu):
+ continue
frames = thread_info.frame_info
if frames:
yield frames, thread_info.thread_id
diff --git a/Lib/profiling/sampling/constants.py b/Lib/profiling/sampling/constants.py
new file mode 100644
index 00000000000..be2ae60a88f
--- /dev/null
+++ b/Lib/profiling/sampling/constants.py
@@ -0,0 +1,30 @@
+"""Constants for the sampling profiler."""
+
+# Profiling mode constants
+PROFILING_MODE_WALL = 0
+PROFILING_MODE_CPU = 1
+PROFILING_MODE_GIL = 2
+PROFILING_MODE_ALL = 3 # Combines GIL + CPU checks
+
+# Sort mode constants
+SORT_MODE_NSAMPLES = 0
+SORT_MODE_TOTTIME = 1
+SORT_MODE_CUMTIME = 2
+SORT_MODE_SAMPLE_PCT = 3
+SORT_MODE_CUMUL_PCT = 4
+SORT_MODE_NSAMPLES_CUMUL = 5
+
+# Thread status flags
+try:
+ from _remote_debugging import (
+ THREAD_STATUS_HAS_GIL,
+ THREAD_STATUS_ON_CPU,
+ THREAD_STATUS_UNKNOWN,
+ THREAD_STATUS_GIL_REQUESTED,
+ )
+except ImportError:
+ # Fallback for tests or when module is not available
+ THREAD_STATUS_HAS_GIL = (1 << 0)
+ THREAD_STATUS_ON_CPU = (1 << 1)
+ THREAD_STATUS_UNKNOWN = (1 << 2)
+ THREAD_STATUS_GIL_REQUESTED = (1 << 3)
diff --git a/Lib/profiling/sampling/flamegraph.js b/Lib/profiling/sampling/flamegraph.js
index 95ad7ca6184..670ca22d442 100644
--- a/Lib/profiling/sampling/flamegraph.js
+++ b/Lib/profiling/sampling/flamegraph.js
@@ -151,17 +151,22 @@ function createPythonTooltip(data) {
const funcname = resolveString(d.data.funcname) || resolveString(d.data.name);
const filename = resolveString(d.data.filename) || "";
+ // Don't show file location for special frames like and
+ const isSpecialFrame = filename === "~";
+ const fileLocationHTML = isSpecialFrame ? "" : `
+