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/CODEOWNERS b/.github/CODEOWNERS
index 1086b426204..6acc156ebff 100644
--- a/.github/CODEOWNERS
+++ b/.github/CODEOWNERS
@@ -126,6 +126,9 @@ Doc/howto/clinic.rst @erlend-aasland @AA-Turner
# C Analyser
Tools/c-analyzer/ @ericsnowcurrently
+# C API Documentation Checks
+Tools/check-c-api-docs/ @ZeroIntensity
+
# Fuzzing
Modules/_xxtestfuzz/ @ammaraskar
diff --git a/.github/CONTRIBUTING.rst b/.github/CONTRIBUTING.rst
index 224061f2c5a..94b67ce3dbe 100644
--- a/.github/CONTRIBUTING.rst
+++ b/.github/CONTRIBUTING.rst
@@ -28,13 +28,12 @@ Please be aware that our workflow does deviate slightly from the typical GitHub
project. Details on how to properly submit a pull request are covered in
`Lifecycle of a Pull Request `_.
We utilize various bots and status checks to help with this, so do follow the
-comments they leave and their "Details" links, respectively. The key points of
-our workflow that are not covered by a bot or status check are:
+comments they leave and their "Details" links, respectively.
-- All discussions that are not directly related to the code in the pull request
- should happen on `GitHub Issues `_.
-- Upon your first non-trivial pull request (which includes documentation changes),
- feel free to add yourself to ``Misc/ACKS``.
+The final key part of our workflow is that all discussions that are not
+directly related to the code in the pull request should happen on
+`GitHub Issues `__, generally in the
+pull request's parent issue.
Setting Expectations
diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml
index 75d174307ce..de6e8756b03 100644
--- a/.github/ISSUE_TEMPLATE/config.yml
+++ b/.github/ISSUE_TEMPLATE/config.yml
@@ -5,3 +5,6 @@ contact_links:
- name: "Proposing new features"
about: "Submit major feature proposal (e.g. syntax changes) to an ideas forum first."
url: "https://discuss.python.org/c/ideas/6"
+ - name: "Python Install Manager issues"
+ about: "Report issues with the Python Install Manager (for Windows)"
+ url: "https://github.com/python/pymanager/issues"
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..3d889fa128e 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
@@ -152,6 +142,9 @@ jobs:
- name: Check for unsupported C global variables
if: github.event_name == 'pull_request' # $GITHUB_EVENT_NAME
run: make check-c-globals
+ - name: Check for undocumented C APIs
+ run: make check-c-api-docs
+
build-windows:
name: >-
@@ -215,7 +208,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 +239,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 +269,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 +290,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 +321,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 +347,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 +415,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 +450,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 +460,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 +543,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 +568,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 +599,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 +613,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 151b17e8442..62325250bd3 100644
--- a/.github/workflows/jit.yml
+++ b/.github/workflows/jit.yml
@@ -68,7 +68,7 @@ jobs:
- true
- false
llvm:
- - 20
+ - 21
include:
- target: i686-pc-windows-msvc/msvc
architecture: Win32
@@ -138,7 +138,7 @@ jobs:
fail-fast: false
matrix:
llvm:
- - 20
+ - 21
steps:
- uses: actions/checkout@v4
with:
@@ -166,7 +166,7 @@ jobs:
fail-fast: false
matrix:
llvm:
- - 20
+ - 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/Android/android.py b/Android/android.py
index 25bb4ca70b5..d1a10be776e 100755
--- a/Android/android.py
+++ b/Android/android.py
@@ -29,6 +29,7 @@
ANDROID_DIR.name == "Android" and (PYTHON_DIR / "pyconfig.h.in").exists()
)
+ENV_SCRIPT = ANDROID_DIR / "android-env.sh"
TESTBED_DIR = ANDROID_DIR / "testbed"
CROSS_BUILD_DIR = PYTHON_DIR / "cross-build"
@@ -129,12 +130,11 @@ def android_env(host):
sysconfig_filename = next(sysconfig_files).name
host = re.fullmatch(r"_sysconfigdata__android_(.+).py", sysconfig_filename)[1]
- env_script = ANDROID_DIR / "android-env.sh"
env_output = subprocess.run(
f"set -eu; "
f"HOST={host}; "
f"PREFIX={prefix}; "
- f". {env_script}; "
+ f". {ENV_SCRIPT}; "
f"export",
check=True, shell=True, capture_output=True, encoding='utf-8',
).stdout
@@ -151,7 +151,7 @@ def android_env(host):
env[key] = value
if not env:
- raise ValueError(f"Found no variables in {env_script.name} output:\n"
+ raise ValueError(f"Found no variables in {ENV_SCRIPT.name} output:\n"
+ env_output)
return env
@@ -281,15 +281,30 @@ def clean_all(context):
def setup_ci():
- # https://github.blog/changelog/2024-04-02-github-actions-hardware-accelerated-android-virtualization-now-available/
- if "GITHUB_ACTIONS" in os.environ and platform.system() == "Linux":
- run(
- ["sudo", "tee", "/etc/udev/rules.d/99-kvm4all.rules"],
- input='KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS+="static_node=kvm"\n',
- text=True,
- )
- run(["sudo", "udevadm", "control", "--reload-rules"])
- run(["sudo", "udevadm", "trigger", "--name-match=kvm"])
+ if "GITHUB_ACTIONS" in os.environ:
+ # Enable emulator hardware acceleration
+ # (https://github.blog/changelog/2024-04-02-github-actions-hardware-accelerated-android-virtualization-now-available/).
+ if platform.system() == "Linux":
+ run(
+ ["sudo", "tee", "/etc/udev/rules.d/99-kvm4all.rules"],
+ input='KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS+="static_node=kvm"\n',
+ text=True,
+ )
+ run(["sudo", "udevadm", "control", "--reload-rules"])
+ run(["sudo", "udevadm", "trigger", "--name-match=kvm"])
+
+ # Free up disk space by deleting unused versions of the NDK
+ # (https://github.com/freakboy3742/pyspamsum/pull/108).
+ for line in ENV_SCRIPT.read_text().splitlines():
+ if match := re.fullmatch(r"ndk_version=(.+)", line):
+ ndk_version = match[1]
+ break
+ else:
+ raise ValueError(f"Failed to find NDK version in {ENV_SCRIPT.name}")
+
+ for item in (android_home / "ndk").iterdir():
+ if item.name[0].isdigit() and item.name != ndk_version:
+ delete_glob(item)
def setup_sdk():
diff --git a/Android/testbed/app/build.gradle.kts b/Android/testbed/app/build.gradle.kts
index 4de628a279c..14d43d8c4d5 100644
--- a/Android/testbed/app/build.gradle.kts
+++ b/Android/testbed/app/build.gradle.kts
@@ -79,7 +79,7 @@ android {
val androidEnvFile = file("../../android-env.sh").absoluteFile
namespace = "org.python.testbed"
- compileSdk = 34
+ compileSdk = 35
defaultConfig {
applicationId = "org.python.testbed"
@@ -92,7 +92,7 @@ android {
}
throw GradleException("Failed to find API level in $androidEnvFile")
}
- targetSdk = 34
+ targetSdk = 35
versionCode = 1
versionName = "1.0"
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/about.rst b/Doc/about.rst
index 8f635d7f743..5c1b497ca6b 100644
--- a/Doc/about.rst
+++ b/Doc/about.rst
@@ -32,8 +32,9 @@ Contributors to the Python documentation
----------------------------------------
Many people have contributed to the Python language, the Python standard
-library, and the Python documentation. See :source:`Misc/ACKS` in the Python
-source distribution for a partial list of contributors.
+library, and the Python documentation. See the `CPython
+GitHub repository `__
+for a partial list of contributors.
It is only with the input and contributions of the Python community
that Python has such wonderful documentation -- Thank You!
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..96078d22710 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
@@ -152,13 +162,85 @@ The following functions provide locale-independent string to number conversions.
.. versionadded:: 3.1
-.. c:function:: int PyOS_stricmp(const char *s1, const char *s2)
+.. c:function:: int PyOS_mystricmp(const char *str1, const char *str2)
+ int PyOS_mystrnicmp(const char *str1, const char *str2, Py_ssize_t size)
- Case insensitive comparison of strings. The function works almost
- identically to :c:func:`!strcmp` except that it ignores the case.
+ Case insensitive comparison of strings. These functions work almost
+ identically to :c:func:`!strcmp` and :c:func:`!strncmp` (respectively),
+ except that they ignore the case of ASCII characters.
+
+ Return ``0`` if the strings are equal, a negative value if *str1* sorts
+ lexicographically before *str2*, or a positive value if it sorts after.
+
+ In the *str1* or *str2* arguments, a NUL byte marks the end of the string.
+ For :c:func:`!PyOS_mystrnicmp`, the *size* argument gives the maximum size
+ of the string, as if NUL was present at the index given by *size*.
+
+ These functions do not use the locale.
-.. c:function:: int PyOS_strnicmp(const char *s1, const char *s2, Py_ssize_t size)
+.. c:function:: int PyOS_stricmp(const char *str1, const char *str2)
+ int PyOS_strnicmp(const char *str1, const char *str2, Py_ssize_t size)
- Case insensitive comparison of strings. The function works almost
- identically to :c:func:`!strncmp` except that it ignores the case.
+ Case insensitive comparison of strings.
+
+ On Windows, these are aliases of :c:func:`!stricmp` and :c:func:`!strnicmp`,
+ respectively.
+
+ On other platforms, they are aliases of :c:func:`PyOS_mystricmp` and
+ :c:func:`PyOS_mystrnicmp`, respectively.
+
+
+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..313c534545a 100644
--- a/Doc/c-api/descriptor.rst
+++ b/Doc/c-api/descriptor.rst
@@ -21,20 +21,104 @@ found in the dictionary of type objects.
.. c:function:: PyObject* PyDescr_NewMember(PyTypeObject *type, struct PyMemberDef *meth)
+.. c:var:: PyTypeObject PyMemberDescr_Type
+
+ The type object for member descriptor objects created from
+ :c:type:`PyMemberDef` structures. These descriptors expose fields of a
+ C struct as attributes on a type, and correspond
+ to :class:`types.MemberDescriptorType` objects in Python.
+
+
+
+.. c:var:: PyTypeObject PyGetSetDescr_Type
+
+ The type object for get/set descriptor objects created from
+ :c:type:`PyGetSetDef` structures. These descriptors implement attributes
+ whose value is computed by C getter and setter functions, and are used
+ for many built-in type attributes.
+
+
.. c:function:: PyObject* PyDescr_NewMethod(PyTypeObject *type, struct PyMethodDef *meth)
+.. c:var:: PyTypeObject PyMethodDescr_Type
+
+ The type object for method descriptor objects created from
+ :c:type:`PyMethodDef` structures. These descriptors expose C functions as
+ methods on a type, and correspond to :class:`types.MemberDescriptorType`
+ objects in Python.
+
+
.. c:function:: PyObject* PyDescr_NewWrapper(PyTypeObject *type, struct wrapperbase *wrapper, void *wrapped)
+.. c:var:: PyTypeObject PyWrapperDescr_Type
+
+ The type object for wrapper descriptor objects created by
+ :c:func:`PyDescr_NewWrapper` and :c:func:`PyWrapper_New`. Wrapper
+ descriptors are used internally to expose special methods implemented
+ via wrapper structures, and appear in Python as
+ :class:`types.WrapperDescriptorType` objects.
+
+
.. c:function:: PyObject* PyDescr_NewClassMethod(PyTypeObject *type, PyMethodDef *method)
.. 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:var:: PyTypeObject PyClassMethodDescr_Type
+
+ The type object for C-level class method descriptor objects.
+ This is the type of the descriptors created for :func:`classmethod` defined in
+ C extension types, and is the same object as :class:`classmethod`
+ in Python.
+
+
+.. 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..9c4428ced41 100644
--- a/Doc/c-api/dict.rst
+++ b/Doc/c-api/dict.rst
@@ -43,6 +43,17 @@ Dictionary Objects
prevent modification of the dictionary for non-dynamic class types.
+.. c:var:: PyTypeObject PyDictProxy_Type
+
+ The type object for mapping proxy objects created by
+ :c:func:`PyDictProxy_New` and for the read-only ``__dict__`` attribute
+ of many built-in types. A :c:type:`PyDictProxy_Type` instance provides a
+ dynamic, read-only view of an underlying dictionary: changes to the
+ underlying dictionary are reflected in the proxy, but the proxy itself
+ does not support mutation operations. This corresponds to
+ :class:`types.MappingProxyType` in Python.
+
+
.. c:function:: void PyDict_Clear(PyObject *p)
Empty an existing dictionary of all key-value pairs.
@@ -245,6 +256,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 +442,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/extension-modules.rst b/Doc/c-api/extension-modules.rst
index 3d331e6ec12..0ce173b4bfe 100644
--- a/Doc/c-api/extension-modules.rst
+++ b/Doc/c-api/extension-modules.rst
@@ -8,7 +8,8 @@ Defining extension modules
A C extension for CPython is a shared library (for example, a ``.so`` file
on Linux, ``.pyd`` DLL on Windows), which is loadable into the Python process
(for example, it is compiled with compatible compiler settings), and which
-exports an :ref:`initialization function `.
+exports an :dfn:`export hook` function (or an
+old-style :ref:`initialization function `).
To be importable by default (that is, by
:py:class:`importlib.machinery.ExtensionFileLoader`),
@@ -23,25 +24,127 @@ and must be named after the module name plus an extension listed in
One suitable tool is Setuptools, whose documentation can be found at
https://setuptools.pypa.io/en/latest/setuptools.html.
-Normally, the initialization function returns a module definition initialized
-using :c:func:`PyModuleDef_Init`.
-This allows splitting the creation process into several phases:
+.. _extension-export-hook:
+Extension export hook
+.....................
+
+.. versionadded:: next
+
+ Support for the :samp:`PyModExport_{}` export hook was added in Python
+ 3.15. The older way of defining modules is still available: consult either
+ the :ref:`extension-pyinit` section or earlier versions of this
+ documentation if you plan to support earlier Python versions.
+
+The export hook must be an exported function with the following signature:
+
+.. c:function:: PyModuleDef_Slot *PyModExport_modulename(void)
+
+For modules with ASCII-only names, the :ref:`export hook `
+must be named :samp:`PyModExport_{}`,
+with ```` replaced by the module's name.
+
+For non-ASCII module names, the export hook must instead be named
+:samp:`PyModExportU_{}` (note the ``U``), with ```` encoded using
+Python's *punycode* encoding with hyphens replaced by underscores. In Python:
+
+.. code-block:: python
+
+ def hook_name(name):
+ try:
+ suffix = b'_' + name.encode('ascii')
+ except UnicodeEncodeError:
+ suffix = b'U_' + name.encode('punycode').replace(b'-', b'_')
+ return b'PyModExport' + suffix
+
+The export hook returns an array of :c:type:`PyModuleDef_Slot` entries,
+terminated by an entry with a slot ID of ``0``.
+These slots describe how the module should be created and initialized.
+
+This array must remain valid and constant until interpreter shutdown.
+Typically, it should use ``static`` storage.
+Prefer using the :c:macro:`Py_mod_create` and :c:macro:`Py_mod_exec` slots
+for any dynamic behavior.
+
+The export hook may return ``NULL`` with an exception set to signal failure.
+
+It is recommended to define the export hook function using a helper macro:
+
+.. c:macro:: PyMODEXPORT_FUNC
+
+ Declare an extension module export hook.
+ This macro:
+
+ * specifies the :c:expr:`PyModuleDef_Slot*` return type,
+ * adds any special linkage declarations required by the platform, and
+ * for C++, declares the function as ``extern "C"``.
+
+For example, a module called ``spam`` would be defined like this::
+
+ PyABIInfo_VAR(abi_info);
+
+ static PyModuleDef_Slot spam_slots[] = {
+ {Py_mod_abi, &abi_info},
+ {Py_mod_name, "spam"},
+ {Py_mod_init, spam_init_function},
+ ...
+ {0, NULL},
+ };
+
+ PyMODEXPORT_FUNC
+ PyModExport_spam(void)
+ {
+ return spam_slots;
+ }
+
+The export hook is typically the only non-\ ``static``
+item defined in the module's C source.
+
+The hook should be kept short -- ideally, one line as above.
+If you do need to use Python C API in this function, it is recommended to call
+``PyABIInfo_Check(&abi_info, "modulename")`` first to raise an exception,
+rather than crash, in common cases of ABI mismatch.
+
+
+.. note::
+
+ It is possible to export multiple modules from a single shared library by
+ defining multiple export hooks.
+ However, importing them requires a custom importer or suitably named
+ copies/links of the extension file, because Python's import machinery only
+ finds the function corresponding to the filename.
+ See the `Multiple modules in one library `__
+ section in :pep:`489` for details.
+
+
+.. _multi-phase-initialization:
+
+Multi-phase initialization
+..........................
+
+The process of creating an extension module follows several phases:
+
+- Python finds and calls the export hook to get information on how to
+ create the module.
- Before any substantial code is executed, Python can determine which
capabilities the module supports, and it can adjust the environment or
refuse loading an incompatible extension.
-- By default, Python itself creates the module object -- that is, it does
- the equivalent of :py:meth:`object.__new__` for classes.
- It also sets initial attributes like :attr:`~module.__package__` and
- :attr:`~module.__loader__`.
-- Afterwards, the module object is initialized using extension-specific
- code -- the equivalent of :py:meth:`~object.__init__` on classes.
+ Slots like :c:data:`Py_mod_abi`, :c:data:`Py_mod_gil` and
+ :c:data:`Py_mod_multiple_interpreters` influence this step.
+- By default, Python itself then creates the module object -- that is, it does
+ the equivalent of calling :py:meth:`~object.__new__` when creating an object.
+ This step can be overridden using the :c:data:`Py_mod_create` slot.
+- Python sets initial module attributes like :attr:`~module.__package__` and
+ :attr:`~module.__loader__`, and inserts the module object into
+ :py:attr:`sys.modules`.
+- Afterwards, the module object is initialized in an extension-specific way
+ -- the equivalent of :py:meth:`~object.__init__` when creating an object,
+ or of executing top-level code in a Python-language module.
+ The behavior is specified using the :c:data:`Py_mod_exec` slot.
This is called *multi-phase initialization* to distinguish it from the legacy
-(but still supported) *single-phase initialization* scheme,
-where the initialization function returns a fully constructed module.
-See the :ref:`single-phase-initialization section below `
-for details.
+(but still supported) :ref:`single-phase initialization `,
+where an initialization function returns a fully constructed module.
.. versionchanged:: 3.5
@@ -53,7 +156,7 @@ Multiple module instances
By default, extension modules are not singletons.
For example, if the :py:attr:`sys.modules` entry is removed and the module
-is re-imported, a new module object is created, and typically populated with
+is re-imported, a new module object is created and, typically, populated with
fresh method and type objects.
The old module is subject to normal garbage collection.
This mirrors the behavior of pure-Python modules.
@@ -83,36 +186,34 @@ A module may also be limited to the main interpreter using
the :c:data:`Py_mod_multiple_interpreters` slot.
-.. _extension-export-hook:
+.. _extension-pyinit:
-Initialization function
-.......................
+``PyInit`` function
+...................
-The initialization function defined by an extension module has the
-following signature:
+.. deprecated:: next
+
+ This functionality is :term:`soft deprecated`.
+ It will not get new features, but there are no plans to remove it.
+
+Instead of :c:func:`PyModExport_modulename`, an extension module can define
+an older-style :dfn:`initialization function` with the signature:
.. c:function:: PyObject* PyInit_modulename(void)
Its name should be :samp:`PyInit_{}`, with ```` replaced by the
name of the module.
+For non-ASCII module names, use :samp:`PyInitU_{}` instead, with
+```` encoded in the same way as for the
+:ref:`export hook ` (that is, using Punycode
+with underscores).
-For modules with ASCII-only names, the function must instead be named
-:samp:`PyInit_{}`, with ```` replaced by the name of the module.
-When using :ref:`multi-phase-initialization`, non-ASCII module names
-are allowed. In this case, the initialization function name is
-:samp:`PyInitU_{}`, with ```` encoded using Python's
-*punycode* encoding with hyphens replaced by underscores. In Python:
+If a module exports both :samp:`PyInit_{}` and
+:samp:`PyModExport_{}`, the :samp:`PyInit_{}` function
+is ignored.
-.. code-block:: python
-
- def initfunc_name(name):
- try:
- suffix = b'_' + name.encode('ascii')
- except UnicodeEncodeError:
- suffix = b'U_' + name.encode('punycode').replace(b'-', b'_')
- return b'PyInit' + suffix
-
-It is recommended to define the initialization function using a helper macro:
+Like with :c:macro:`PyMODEXPORT_FUNC`, it is recommended to define the
+initialization function using a helper macro:
.. c:macro:: PyMODINIT_FUNC
@@ -123,6 +224,34 @@ It is recommended to define the initialization function using a helper macro:
* adds any special linkage declarations required by the platform, and
* for C++, declares the function as ``extern "C"``.
+
+Normally, the initialization function (``PyInit_modulename``) returns
+a :c:type:`PyModuleDef` instance with non-``NULL``
+:c:member:`~PyModuleDef.m_slots`. This allows Python to use
+:ref:`multi-phase initialization `.
+
+Before it is returned, the ``PyModuleDef`` instance must be initialized
+using the following function:
+
+.. c:function:: PyObject* PyModuleDef_Init(PyModuleDef *def)
+
+ Ensure a module definition is a properly initialized Python object that
+ correctly reports its type and a reference count.
+
+ Return *def* cast to ``PyObject*``, or ``NULL`` if an error occurred.
+
+ Calling this function is required before returning a :c:type:`PyModuleDef`
+ from a module initialization function.
+ It should not be used in other contexts.
+
+ Note that Python assumes that ``PyModuleDef`` structures are statically
+ allocated.
+ This function may return either a new reference or a borrowed one;
+ this reference must not be released.
+
+ .. versionadded:: 3.5
+
+
For example, a module called ``spam`` would be defined like this::
static struct PyModuleDef spam_module = {
@@ -137,59 +266,23 @@ For example, a module called ``spam`` would be defined like this::
return PyModuleDef_Init(&spam_module);
}
-It is possible to export multiple modules from a single shared library by
-defining multiple initialization functions. However, importing them requires
-using symbolic links or a custom importer, because by default only the
-function corresponding to the filename is found.
-See the `Multiple modules in one library `__
-section in :pep:`489` for details.
-
-The initialization function is typically the only non-\ ``static``
-item defined in the module's C source.
-
-
-.. _multi-phase-initialization:
-
-Multi-phase initialization
-..........................
-
-Normally, the :ref:`initialization function `
-(``PyInit_modulename``) returns a :c:type:`PyModuleDef` instance with
-non-``NULL`` :c:member:`~PyModuleDef.m_slots`.
-Before it is returned, the ``PyModuleDef`` instance must be initialized
-using the following function:
-
-
-.. c:function:: PyObject* PyModuleDef_Init(PyModuleDef *def)
-
- Ensure a module definition is a properly initialized Python object that
- correctly reports its type and a reference count.
-
- Return *def* cast to ``PyObject*``, or ``NULL`` if an error occurred.
-
- Calling this function is required for :ref:`multi-phase-initialization`.
- It should not be used in other contexts.
-
- Note that Python assumes that ``PyModuleDef`` structures are statically
- allocated.
- This function may return either a new reference or a borrowed one;
- this reference must not be released.
-
- .. versionadded:: 3.5
-
.. _single-phase-initialization:
Legacy single-phase initialization
-..................................
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
-.. attention::
- Single-phase initialization is a legacy mechanism to initialize extension
+.. deprecated:: next
+
+ Single-phase initialization is :term:`soft deprecated`.
+ It is a legacy mechanism to initialize extension
modules, with known drawbacks and design flaws. Extension module authors
are encouraged to use multi-phase initialization instead.
-In single-phase initialization, the
-:ref:`initialization function ` (``PyInit_modulename``)
+ However, there are no plans to remove support for it.
+
+In single-phase initialization, the old-style
+:ref:`initializaton function ` (``PyInit_modulename``)
should create, populate and return a module object.
This is typically done using :c:func:`PyModule_Create` and functions like
:c:func:`PyModule_AddObjectRef`.
@@ -242,6 +335,8 @@ in the following ways:
* Single-phase modules support module lookup functions like
:c:func:`PyState_FindModule`.
+* The module's :c:member:`PyModuleDef.m_slots` must be NULL.
+
.. [#testsinglephase] ``_testsinglephase`` is an internal module used
in CPython's self-test suite; your installation may or may not
include it.
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 440e4239cca..f60cadab534 100644
--- a/Doc/c-api/import.rst
+++ b/Doc/c-api/import.rst
@@ -314,6 +314,13 @@ Importing Modules
initialization.
+.. c:var:: struct _inittab *PyImport_Inittab
+
+ The table of built-in modules used by Python initialization. Do not use this directly;
+ use :c:func:`PyImport_AppendInittab` and :c:func:`PyImport_ExtendInittab`
+ instead.
+
+
.. c:function:: PyObject* PyImport_ImportModuleAttr(PyObject *mod_name, PyObject *attr_name)
Import the module *mod_name* and get its attribute *attr_name*.
@@ -370,3 +377,24 @@ Importing Modules
- ``PyImport_LAZY_NONE``
.. versionadded:: 3.12
+
+.. 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..7411644f9e1 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.
@@ -1680,7 +1717,8 @@ function. You can create and destroy them using the following functions:
Only C-level static and global variables are shared between these
module objects.
- * For modules using single-phase initialization,
+ * For modules using legacy
+ :ref:`single-phase initialization `,
e.g. :c:func:`PyModule_Create`, the first time a particular extension
is imported, it is initialized normally, and a (shallow) copy of its
module's dictionary is squirreled away.
@@ -1854,6 +1892,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
@@ -2483,3 +2540,220 @@ code triggered by the finalizer blocks and calls :c:func:`PyEval_SaveThread`.
In the default build, this macro expands to ``}``.
.. versionadded:: 3.13
+
+
+Legacy Locking APIs
+-------------------
+
+These APIs are obsolete since Python 3.13 with the introduction of
+:c:type:`PyMutex`.
+
+.. versionchanged:: 3.15
+ These APIs are now a simple wrapper around ``PyMutex``.
+
+
+.. c:type:: PyThread_type_lock
+
+ A pointer to a mutual exclusion lock.
+
+
+.. c:type:: PyLockStatus
+
+ The result of acquiring a lock with a timeout.
+
+ .. c:namespace:: NULL
+
+ .. c:enumerator:: PY_LOCK_FAILURE
+
+ Failed to acquire the lock.
+
+ .. c:enumerator:: PY_LOCK_ACQUIRED
+
+ The lock was successfully acquired.
+
+ .. c:enumerator:: PY_LOCK_INTR
+
+ The lock was interrupted by a signal.
+
+
+.. c:function:: PyThread_type_lock PyThread_allocate_lock(void)
+
+ Allocate a new lock.
+
+ On success, this function returns a lock; on failure, this
+ function returns ``0`` without an exception set.
+
+ The caller does not need to hold an :term:`attached thread state`.
+
+ .. versionchanged:: 3.15
+ This function now always uses :c:type:`PyMutex`. In prior versions, this
+ would use a lock provided by the operating system.
+
+
+.. c:function:: void PyThread_free_lock(PyThread_type_lock lock)
+
+ Destroy *lock*. The lock should not be held by any thread when calling
+ this.
+
+ The caller does not need to hold an :term:`attached thread state`.
+
+
+.. c:function:: PyLockStatus PyThread_acquire_lock_timed(PyThread_type_lock lock, long long microseconds, int intr_flag)
+
+ Acquire *lock* with a timeout.
+
+ This will wait for *microseconds* microseconds to acquire the lock. If the
+ timeout expires, this function returns :c:enumerator:`PY_LOCK_FAILURE`.
+ If *microseconds* is ``-1``, this will wait indefinitely until the lock has
+ been released.
+
+ If *intr_flag* is ``1``, acquiring the lock may be interrupted by a signal,
+ in which case this function returns :c:enumerator:`PY_LOCK_INTR`. Upon
+ interruption, it's generally expected that the caller makes a call to
+ :c:func:`Py_MakePendingCalls` to propagate an exception to Python code.
+
+ If the lock is successfully acquired, this function returns
+ :c:enumerator:`PY_LOCK_ACQUIRED`.
+
+ The caller does not need to hold an :term:`attached thread state`.
+
+
+.. c:function:: int PyThread_acquire_lock(PyThread_type_lock lock, int waitflag)
+
+ Acquire *lock*.
+
+ If *waitflag* is ``1`` and another thread currently holds the lock, this
+ function will wait until the lock can be acquired and will always return
+ ``1``.
+
+ If *waitflag* is ``0`` and another thread holds the lock, this function will
+ not wait and instead return ``0``. If the lock is not held by any other
+ thread, then this function will acquire it and return ``1``.
+
+ Unlike :c:func:`PyThread_acquire_lock_timed`, acquiring the lock cannot be
+ interrupted by a signal.
+
+ The caller does not need to hold an :term:`attached thread state`.
+
+
+.. c:function:: int PyThread_release_lock(PyThread_type_lock lock)
+
+ Release *lock*. If *lock* is not held, then this function issues a
+ fatal error.
+
+ The caller does not need to hold an :term:`attached thread state`.
+
+
+Operating System Thread APIs
+============================
+
+.. c:macro:: PYTHREAD_INVALID_THREAD_ID
+
+ Sentinel value for an invalid thread ID.
+
+ This is currently equivalent to ``(unsigned long)-1``.
+
+
+.. c:function:: unsigned long PyThread_start_new_thread(void (*func)(void *), void *arg)
+
+ Start function *func* in a new thread with argument *arg*.
+ The resulting thread is not intended to be joined.
+
+ *func* must not be ``NULL``, but *arg* may be ``NULL``.
+
+ On success, this function returns the identifier of the new thread; on failure,
+ this returns :c:macro:`PYTHREAD_INVALID_THREAD_ID`.
+
+ The caller does not need to hold an :term:`attached thread state`.
+
+
+.. c:function:: unsigned long PyThread_get_thread_ident(void)
+
+ Return the identifier of the current thread, which will never be zero.
+
+ This function cannot fail, and the caller does not need to hold an
+ :term:`attached thread state`.
+
+ .. seealso::
+ :py:func:`threading.get_ident`
+
+
+.. c:function:: PyObject *PyThread_GetInfo(void)
+
+ Get general information about the current thread in the form of a
+ :ref:`struct sequence ` object. This information is
+ accessible as :py:attr:`sys.thread_info` in Python.
+
+ On success, this returns a new :term:`strong reference` to the thread
+ information; on failure, this returns ``NULL`` with an exception set.
+
+ The caller must hold an :term:`attached thread state`.
+
+
+.. c:macro:: PY_HAVE_THREAD_NATIVE_ID
+
+ This macro is defined when the system supports native thread IDs.
+
+
+.. c:function:: unsigned long PyThread_get_thread_native_id(void)
+
+ Get the native identifier of the current thread as it was assigned by the operating
+ system's kernel, which will never be less than zero.
+
+ This function is only available when :c:macro:`PY_HAVE_THREAD_NATIVE_ID` is
+ defined.
+
+ This function cannot fail, and the caller does not need to hold an
+ :term:`attached thread state`.
+
+ .. seealso::
+ :py:func:`threading.get_native_id`
+
+
+.. c:function:: void PyThread_exit_thread(void)
+
+ Terminate the current thread. This function is generally considered unsafe
+ and should be avoided. It is kept solely for backwards compatibility.
+
+ This function is only safe to call if all functions in the full call
+ stack are written to safely allow it.
+
+ .. warning::
+
+ If the current system uses POSIX threads (also known as "pthreads"),
+ this calls :manpage:`pthread_exit(3)`, which attempts to unwind the stack
+ and call C++ destructors on some libc implementations. However, if a
+ ``noexcept`` function is reached, it may terminate the process.
+ Other systems, such as macOS, do unwinding.
+
+ On Windows, this function calls ``_endthreadex()``, which kills the thread
+ without calling C++ destructors.
+
+ In any case, there is a risk of corruption on the thread's stack.
+
+ .. deprecated:: 3.14
+
+
+.. c:function:: void PyThread_init_thread(void)
+
+ Initialize ``PyThread*`` APIs. Python executes this function automatically,
+ so there's little need to call it from an extension module.
+
+
+.. c:function:: int PyThread_set_stacksize(size_t size)
+
+ Set the stack size of the current thread to *size* bytes.
+
+ This function returns ``0`` on success, ``-1`` if *size* is invalid, or
+ ``-2`` if the system does not support changing the stack size. This function
+ does not set exceptions.
+
+ The caller does not need to hold an :term:`attached thread state`.
+
+
+.. c:function:: size_t PyThread_get_stacksize(void)
+
+ Return the stack size of the current thread in bytes, or ``0`` if the system's
+ default stack size is in use.
+
+ The caller does not need to hold an :term:`attached thread state`.
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..bb94bcb86a7 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,28 @@ 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.");
+
+.. c:macro:: Py_ARRAY_LENGTH(array)
+
+ Compute the length of a statically allocated C array at compile time.
+
+ The *array* argument must be a C array with a size known at compile time.
+ Passing an array with an unknown size, such as a heap-allocated array,
+ will result in a compilation error on some compilers, or otherwise produce
+ incorrect results.
+
+ This is roughly equivalent to::
+
+ sizeof(array) / sizeof((array)[0])
+
.. _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..a12f6331c85 100644
--- a/Doc/c-api/module.rst
+++ b/Doc/c-api/module.rst
@@ -3,17 +3,16 @@
.. _moduleobjects:
Module Objects
---------------
+==============
.. index:: pair: object; module
-
.. c:var:: PyTypeObject PyModule_Type
.. 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 +70,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,12 +92,9 @@ Module Objects
Similar to :c:func:`PyModule_GetNameObject` but return the name encoded to
``'utf-8'``.
-.. c:function:: void* PyModule_GetState(PyObject *module)
-
- Return the "state" of the module, that is, a pointer to the block of memory
- allocated at module creation time, or ``NULL``. See
- :c:member:`PyModuleDef.m_size`.
-
+ 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:: PyModuleDef* PyModule_GetDef(PyObject *module)
@@ -103,7 +102,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,215 +125,116 @@ 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.
-.. _pymoduledef:
+.. _pymoduledef_slot:
-Module definitions
-------------------
+Module definition
+-----------------
-The functions in the previous section work on any module object, including
-modules imported from Python code.
+Modules created using the C API are typically defined using an
+array of :dfn:`slots`.
+The slots provide a "description" of how a module should be created.
-Modules defined using the C API typically use a *module definition*,
-:c:type:`PyModuleDef` -- a statically allocated, constant “description" of
-how a module should be created.
+.. versionchanged:: next
-The definition is usually used to define an extension's “main” module object
-(see :ref:`extension-modules` for details).
-It is also used to
-:ref:`create extension modules dynamically `.
+ Previously, a :c:type:`PyModuleDef` struct was necessary to define modules.
+ The older way of defining modules is still available: consult either the
+ :ref:`pymoduledef` section or earlier versions of this documentation
+ if you plan to support earlier Python versions.
-Unlike :c:func:`PyModule_New`, the definition allows management of
-*module state* -- a piece of memory that is allocated and cleared together
-with the module object.
-Unlike the module's Python attributes, Python code cannot replace or delete
-data stored in module state.
+The slots array is usually used to define an extension module's “main”
+module object (see :ref:`extension-modules` for details).
+It can also be used to
+:ref:`create extension modules dynamically `.
-.. c:type:: PyModuleDef
+Unless specified otherwise, the same slot ID may not be repeated
+in an array of slots.
- The module definition struct, which holds all information needed to create
- a module object.
- This structure must be statically allocated (or be otherwise guaranteed
- to be valid while any modules created from it exist).
- Usually, there is only one variable of this type for each extension module.
-
- .. c:member:: PyModuleDef_Base m_base
-
- Always initialize this member to :c:macro:`PyModuleDef_HEAD_INIT`.
-
- .. c:member:: const char *m_name
-
- Name for the new module.
-
- .. c:member:: const char *m_doc
-
- Docstring for the module; usually a docstring variable created with
- :c:macro:`PyDoc_STRVAR` is used.
-
- .. c:member:: Py_ssize_t m_size
-
- Module state may be kept in a per-module memory area that can be
- retrieved with :c:func:`PyModule_GetState`, rather than in static globals.
- This makes modules safe for use in multiple sub-interpreters.
-
- This memory area is allocated based on *m_size* on module creation,
- and freed when the module object is deallocated, after the
- :c:member:`~PyModuleDef.m_free` function has been called, if present.
-
- Setting it to a non-negative value means that the module can be
- re-initialized and specifies the additional amount of memory it requires
- for its state.
-
- Setting ``m_size`` to ``-1`` means that the module does not support
- sub-interpreters, because it has global state.
- Negative ``m_size`` is only allowed when using
- :ref:`legacy single-phase initialization `
- or when :ref:`creating modules dynamically `.
-
- See :PEP:`3121` for more details.
-
- .. c:member:: PyMethodDef* m_methods
-
- A pointer to a table of module-level functions, described by
- :c:type:`PyMethodDef` values. Can be ``NULL`` if no functions are present.
-
- .. c:member:: PyModuleDef_Slot* m_slots
-
- An array of slot definitions for multi-phase initialization, terminated by
- a ``{0, NULL}`` entry.
- When using legacy single-phase initialization, *m_slots* must be ``NULL``.
-
- .. versionchanged:: 3.5
-
- Prior to version 3.5, this member was always set to ``NULL``,
- and was defined as:
-
- .. c:member:: inquiry m_reload
-
- .. c:member:: traverseproc m_traverse
-
- A traversal function to call during GC traversal of the module object, or
- ``NULL`` if not needed.
-
- This function is not called if the module state was requested but is not
- allocated yet. This is the case immediately after the module is created
- and before the module is executed (:c:data:`Py_mod_exec` function). More
- precisely, this function is not called if :c:member:`~PyModuleDef.m_size` is greater
- than 0 and the module state (as returned by :c:func:`PyModule_GetState`)
- is ``NULL``.
-
- .. versionchanged:: 3.9
- No longer called before the module state is allocated.
-
- .. c:member:: inquiry m_clear
-
- A clear function to call during GC clearing of the module object, or
- ``NULL`` if not needed.
-
- This function is not called if the module state was requested but is not
- allocated yet. This is the case immediately after the module is created
- and before the module is executed (:c:data:`Py_mod_exec` function). More
- precisely, this function is not called if :c:member:`~PyModuleDef.m_size` is greater
- than 0 and the module state (as returned by :c:func:`PyModule_GetState`)
- is ``NULL``.
-
- Like :c:member:`PyTypeObject.tp_clear`, this function is not *always*
- called before a module is deallocated. For example, when reference
- counting is enough to determine that an object is no longer used,
- the cyclic garbage collector is not involved and
- :c:member:`~PyModuleDef.m_free` is called directly.
-
- .. versionchanged:: 3.9
- No longer called before the module state is allocated.
-
- .. c:member:: freefunc m_free
-
- A function to call during deallocation of the module object, or ``NULL``
- if not needed.
-
- This function is not called if the module state was requested but is not
- allocated yet. This is the case immediately after the module is created
- and before the module is executed (:c:data:`Py_mod_exec` function). More
- precisely, this function is not called if :c:member:`~PyModuleDef.m_size` is greater
- than 0 and the module state (as returned by :c:func:`PyModule_GetState`)
- is ``NULL``.
-
- .. versionchanged:: 3.9
- No longer called before the module state is allocated.
-
-
-Module slots
-............
.. c:type:: PyModuleDef_Slot
.. c:member:: int slot
- A slot ID, chosen from the available values explained below.
+ A slot ID, chosen from the available ``Py_mod_*`` values explained below.
+
+ An ID of 0 marks the end of a :c:type:`!PyModuleDef_Slot` array.
.. c:member:: void* value
Value of the slot, whose meaning depends on the slot ID.
+ The value may not be NULL.
+ To leave a slot out, omit the :c:type:`PyModuleDef_Slot` entry entirely.
+
.. versionadded:: 3.5
-The available slot types are:
-.. c:macro:: Py_mod_create
+Metadata slots
+..............
- Specifies a function that is called to create the module object itself.
- The *value* pointer of this slot must point to a function of the signature:
+.. c:macro:: Py_mod_name
- .. c:function:: PyObject* create_module(PyObject *spec, PyModuleDef *def)
- :no-index-entry:
- :no-contents-entry:
+ :c:type:`Slot ID ` for the name of the new module,
+ as a NUL-terminated UTF8-encoded ``const char *``.
- The function receives a :py:class:`~importlib.machinery.ModuleSpec`
- instance, as defined in :PEP:`451`, and the module definition.
- It should return a new module object, or set an error
- and return ``NULL``.
+ Note that modules are typically created using a
+ :py:class:`~importlib.machinery.ModuleSpec`, and when they are, the
+ name from the spec will be used instead of :c:data:`!Py_mod_name`.
+ However, it is still recommended to include this slot for introspection
+ and debugging purposes.
- This function should be kept minimal. In particular, it should not
- call arbitrary Python code, as trying to import the same module again may
- result in an infinite loop.
+ .. versionadded:: next
- Multiple ``Py_mod_create`` slots may not be specified in one module
- definition.
+ Use :c:member:`PyModuleDef.m_name` instead to support previous versions.
- If ``Py_mod_create`` is not specified, the import machinery will create
- a normal module object using :c:func:`PyModule_New`. The name is taken from
- *spec*, not the definition, to allow extension modules to dynamically adjust
- to their place in the module hierarchy and be imported under different
- names through symlinks, all while sharing a single module definition.
+.. c:macro:: Py_mod_doc
- There is no requirement for the returned object to be an instance of
- :c:type:`PyModule_Type`. Any type can be used, as long as it supports
- setting and getting import-related attributes.
- However, only ``PyModule_Type`` instances may be returned if the
- ``PyModuleDef`` has non-``NULL`` ``m_traverse``, ``m_clear``,
- ``m_free``; non-zero ``m_size``; or slots other than ``Py_mod_create``.
+ :c:type:`Slot ID ` for the docstring of the new
+ module, as a NUL-terminated UTF8-encoded ``const char *``.
-.. c:macro:: Py_mod_exec
+ Usually it is set to a variable created with :c:macro:`PyDoc_STRVAR`.
- Specifies a function that is called to *execute* the module.
- This is equivalent to executing the code of a Python module: typically,
- this function adds classes and constants to the module.
- The signature of the function is:
+ .. versionadded:: next
- .. c:function:: int exec_module(PyObject* module)
- :no-index-entry:
- :no-contents-entry:
+ Use :c:member:`PyModuleDef.m_doc` instead to support previous versions.
- If multiple ``Py_mod_exec`` slots are specified, they are processed in the
- order they appear in the *m_slots* array.
+
+Feature slots
+.............
+
+.. c:macro:: Py_mod_abi
+
+ :c:type:`Slot ID ` whose value points to
+ a :c:struct:`PyABIInfo` structure describing the ABI that
+ the extension is using.
+
+ A suitable :c:struct:`!PyABIInfo` variable can be defined using the
+ :c:macro:`PyABIInfo_VAR` macro, as in:
+
+ .. code-block:: c
+
+ PyABIInfo_VAR(abi_info);
+
+ static PyModuleDef_Slot mymodule_slots[] = {
+ {Py_mod_abi, &abi_info},
+ ...
+ };
+
+ When creating a module, Python checks the value of this slot
+ using :c:func:`PyABIInfo_Check`.
+
+ .. versionadded:: 3.15
.. c:macro:: Py_mod_multiple_interpreters
- Specifies one of the following values:
+ :c:type:`Slot ID ` whose value is one of:
.. c:namespace:: NULL
@@ -357,9 +257,6 @@ The available slot types are:
This slot determines whether or not importing this module
in a subinterpreter will fail.
- Multiple ``Py_mod_multiple_interpreters`` slots may not be specified
- in one module definition.
-
If ``Py_mod_multiple_interpreters`` is not specified, the import
machinery defaults to ``Py_MOD_MULTIPLE_INTERPRETERS_SUPPORTED``.
@@ -367,7 +264,7 @@ The available slot types are:
.. c:macro:: Py_mod_gil
- Specifies one of the following values:
+ :c:type:`Slot ID ` whose value is one of:
.. c:namespace:: NULL
@@ -385,45 +282,482 @@ The available slot types are:
this module will cause the GIL to be automatically enabled. See
:ref:`whatsnew313-free-threaded-cpython` for more detail.
- Multiple ``Py_mod_gil`` slots may not be specified in one module definition.
-
If ``Py_mod_gil`` is not specified, the import machinery defaults to
``Py_MOD_GIL_USED``.
.. versionadded:: 3.13
-.. c:macro:: Py_mod_abi
- A pointer to a :c:struct:`PyABIInfo` structure that describes the ABI that
- the extension is using.
+Creation and initialization slots
+.................................
- When the module is loaded, the :c:struct:`!PyABIInfo` in this slot is checked
- using :c:func:`PyABIInfo_Check`.
+.. c:macro:: Py_mod_create
- A suitable :c:struct:`!PyABIInfo` variable can be defined using the
- :c:macro:`PyABIInfo_VAR` macro, as in:
+ :c:type:`Slot ID ` for a function that creates
+ the module object itself.
+ The function must have the signature:
- .. code-block:: c
+ .. c:function:: PyObject* create_module(PyObject *spec, PyModuleDef *def)
+ :no-index-entry:
+ :no-contents-entry:
- PyABIInfo_VAR(abi_info);
+ The function will be called with:
- static PyModuleDef_Slot mymodule_slots[] = {
- {Py_mod_abi, &abi_info},
- ...
- };
+ - *spec*: a ``ModuleSpec``-like object, meaning that any attributes defined
+ for :py:class:`importlib.machinery.ModuleSpec` have matching semantics.
+ However, any of the attributes may be missing.
+ - *def*: ``NULL``, or the module definition if the module is created from one.
- .. versionadded:: 3.15
+ The function should return a new module object, or set an error
+ and return ``NULL``.
+
+ This function should be kept minimal. In particular, it should not
+ call arbitrary Python code, as trying to import the same module again may
+ result in an infinite loop.
+
+ If ``Py_mod_create`` is not specified, the import machinery will create
+ a normal module object using :c:func:`PyModule_New`. The name is taken from
+ *spec*, not the definition, to allow extension modules to dynamically adjust
+ to their place in the module hierarchy and be imported under different
+ names through symlinks, all while sharing a single module definition.
+
+ There is no requirement for the returned object to be an instance of
+ :c:type:`PyModule_Type`.
+ However, some slots may only be used with
+ :c:type:`!PyModule_Type` instances; in particular:
+
+ - :c:macro:`Py_mod_exec`,
+ - :ref:`module state slots ` (``Py_mod_state_*``),
+ - :c:macro:`Py_mod_token`.
+
+ .. versionadded:: 3.5
+
+ .. versionchanged:: next
+
+ The *slots* argument may be a ``ModuleSpec``-like object, rather than
+ a true :py:class:`~importlib.machinery.ModuleSpec` instance.
+ Note that previous versions of CPython did not enforce this.
+
+ The *def* argument may now be ``NULL``, since modules are not necessarily
+ made from definitions.
+
+.. c:macro:: Py_mod_exec
+
+ :c:type:`Slot ID ` for a function that will
+ :dfn:`execute`, or initialize, the module.
+ This function does the equivalent to executing the code of a Python module:
+ typically, it adds classes and constants to the module.
+ The signature of the function is:
+
+ .. c:function:: int exec_module(PyObject* module)
+ :no-index-entry:
+ :no-contents-entry:
+
+ See the :ref:`capi-module-support-functions` section for some useful
+ functions to call.
+
+ For backwards compatibility, the :c:type:`PyModuleDef.m_slots` array may
+ contain multiple :c:macro:`!Py_mod_exec` slots; these are processed in the
+ order they appear in the array.
+ Elsewhere (that is, in arguments to :c:func:`PyModule_FromSlotsAndSpec`
+ and in return values of :samp:`PyModExport_{}`), repeating the slot
+ is not allowed.
+
+ .. versionadded:: 3.5
+
+ .. versionchanged:: next
+
+ Repeated ``Py_mod_exec`` slots are disallowed, except in
+ :c:type:`PyModuleDef.m_slots`.
+
+.. c:macro:: Py_mod_methods
+
+ :c:type:`Slot ID ` for a table of module-level
+ functions, as an array of :c:type:`PyMethodDef` values suitable as the
+ *functions* argument to :c:func:`PyModule_AddFunctions`.
+
+ Like other slot IDs, a slots array may only contain one
+ :c:macro:`!Py_mod_methods` entry.
+ To add functions from multiple :c:type:`PyMethodDef` arrays, call
+ :c:func:`PyModule_AddFunctions` in the :c:macro:`Py_mod_exec` function.
+
+ The table must be statically allocated (or otherwise guaranteed to outlive
+ the module object).
+
+ .. versionadded:: next
+
+ Use :c:member:`PyModuleDef.m_methods` instead to support previous versions.
+
+.. _ext-module-state:
+
+Module state
+------------
+
+Extension modules can have *module state* -- a
+piece of memory that is allocated on module creation,
+and freed when the module object is deallocated.
+The module state is specified using :ref:`dedicated slots `.
+
+A typical use of module state is storing an exception type -- or indeed *any*
+type object defined by the module --
+
+Unlike the module's Python attributes, Python code cannot replace or delete
+data stored in module state.
+
+Keeping per-module information in attributes and module state, rather than in
+static globals, makes module objects *isolated* and safer for use in
+multiple sub-interpreters.
+It also helps Python do an orderly clean-up when it shuts down.
+
+Extensions that keep references to Python objects as part of module state must
+implement :c:macro:`Py_mod_state_traverse` and :c:macro:`Py_mod_state_clear`
+functions to avoid reference leaks.
+
+To retrieve the state from a given module, use the following functions:
+
+.. c:function:: void* PyModule_GetState(PyObject *module)
+
+ Return the "state" of the module, that is, a pointer to the block of memory
+ allocated at module creation time, or ``NULL``. See
+ :c:macro:`Py_mod_state_size`.
+
+ On error, return ``NULL`` with an exception set.
+ Use :c:func:`PyErr_Occurred` to tell this case apart from missing
+ module state.
-.. _moduledef-dynamic:
+.. c:function:: int PyModule_GetStateSize(PyObject *, Py_ssize_t *result)
+
+ Set *\*result* to the size of the module's state, as specified using
+ :c:macro:`Py_mod_state_size` (or :c:member:`PyModuleDef.m_size`),
+ and return 0.
+
+ On error, set *\*result* to -1, and return -1 with an exception set.
+
+ .. versionadded:: next
+
+
+
+.. _ext-module-state-slots:
+
+Slots for defining module state
+...............................
+
+The following :c:member:`PyModuleDef_Slot.slot` IDs are available for
+defining the module state.
+
+.. c:macro:: Py_mod_state_size
+
+ :c:type:`Slot ID ` for the size of the module state,
+ in bytes.
+
+ Setting the value to a non-negative value means that the module can be
+ re-initialized and specifies the additional amount of memory it requires
+ for its state.
+
+ See :PEP:`3121` for more details.
+
+ Use :c:func:`PyModule_GetStateSize` to retrieve the size of a given module.
+
+ .. versionadded:: next
+
+ Use :c:member:`PyModuleDef.m_size` instead to support previous versions.
+
+.. c:macro:: Py_mod_state_traverse
+
+ :c:type:`Slot ID ` for a traversal function to call
+ during GC traversal of the module object.
+
+ The signature of the function, and meanings of the arguments,
+ is similar as for :c:member:`PyTypeObject.tp_traverse`:
+
+ .. c:function:: int traverse_module_state(PyObject *module, visitproc visit, void *arg)
+ :no-index-entry:
+ :no-contents-entry:
+
+ This function is not called if the module state was requested but is not
+ allocated yet. This is the case immediately after the module is created
+ and before the module is executed (:c:data:`Py_mod_exec` function). More
+ precisely, this function is not called if the state size
+ (:c:data:`Py_mod_state_size`) is greater than 0 and the module state
+ (as returned by :c:func:`PyModule_GetState`) is ``NULL``.
+
+ .. versionadded:: next
+
+ Use :c:member:`PyModuleDef.m_size` instead to support previous versions.
+
+.. c:macro:: Py_mod_state_clear
+
+ :c:type:`Slot ID ` for a clear function to call
+ during GC clearing of the module object.
+
+ The signature of the function is:
+
+ .. c:function:: int clear_module_state(PyObject* module)
+ :no-index-entry:
+ :no-contents-entry:
+
+ This function is not called if the module state was requested but is not
+ allocated yet. This is the case immediately after the module is created
+ and before the module is executed (:c:data:`Py_mod_exec` function). More
+ precisely, this function is not called if the state size
+ (:c:data:`Py_mod_state_size`) is greater than 0 and the module state
+ (as returned by :c:func:`PyModule_GetState`) is ``NULL``.
+
+ Like :c:member:`PyTypeObject.tp_clear`, this function is not *always*
+ called before a module is deallocated. For example, when reference
+ counting is enough to determine that an object is no longer used,
+ the cyclic garbage collector is not involved and
+ the :c:macro:`Py_mod_state_free` function is called directly.
+
+ .. versionadded:: next
+
+ Use :c:member:`PyModuleDef.m_clear` instead to support previous versions.
+
+.. c:macro:: Py_mod_state_free
+
+ :c:type:`Slot ID ` for a function to call during
+ deallocation of the module object.
+
+ The signature of the function is:
+
+ .. c:function:: int free_module_state(PyObject* module)
+ :no-index-entry:
+ :no-contents-entry:
+
+ This function is not called if the module state was requested but is not
+ allocated yet. This is the case immediately after the module is created
+ and before the module is executed (:c:data:`Py_mod_exec` function). More
+ precisely, this function is not called if the state size
+ (:c:data:`Py_mod_state_size`) is greater than 0 and the module state
+ (as returned by :c:func:`PyModule_GetState`) is ``NULL``.
+
+ .. versionadded:: next
+
+ Use :c:member:`PyModuleDef.m_free` instead to support previous versions.
+
+
+.. _ext-module-token:
+
+Module token
+............
+
+Each module may have an associated *token*: a pointer-sized value intended to
+identify of the module state's memory layout.
+This means that if you have a module object, but you are not sure if it
+“belongs” to your extension, you can check using code like this:
+
+.. code-block:: c
+
+ PyObject *module =
+
+ void *module_token;
+ if (PyModule_GetToken(module, &module_token) < 0) {
+ return NULL;
+ }
+ if (module_token != your_token) {
+ PyErr_SetString(PyExc_ValueError, "unexpected module")
+ return NULL;
+ }
+
+ // This module's state has the expected memory layout; it's safe to cast
+ struct my_state state = (struct my_state*)PyModule_GetState(module)
+
+A module's token -- and the *your_token* value to use in the above code -- is:
+
+- For modules created with :c:type:`PyModuleDef`: the address of that
+ :c:type:`PyModuleDef`;
+- For modules defined with the :c:macro:`Py_mod_token` slot: the value
+ of that slot;
+- For modules created from an ``PyModExport_*``
+ :ref:`export hook `: the slots array that the export
+ hook returned (unless overriden with :c:macro:`Py_mod_token`).
+
+.. c:macro:: Py_mod_token
+
+ :c:type:`Slot ID ` for the module token.
+
+ If you use this slot to set the module token (rather than rely on the
+ default), you must ensure that:
+
+ * The pointer outlives the class, so it's not reused for something else
+ while the class exists.
+ * It "belongs" to the extension module where the class lives, so it will not
+ clash with other extensions.
+ * If the token points to a :c:type:`PyModuleDef` struct, the module should
+ behave as if it was created from that :c:type:`PyModuleDef`.
+ In particular, the module state must have matching layout and semantics.
+
+ Modules created from :c:type:`PyModuleDef` allways use the address of
+ the :c:type:`PyModuleDef` as the token.
+ This means that :c:macro:`!Py_mod_token` cannot be used in
+ :c:member:`PyModuleDef.m_slots`.
+
+ .. versionadded:: next
+
+.. c:function:: int PyModule_GetToken(PyObject *module, void** result)
+
+ Set *\*result* to the module's token and return 0.
+
+ On error, set *\*result* to NULL, and return -1 with an exception set.
+
+ .. versionadded:: next
+
+See also :c:func:`PyType_GetModuleByToken`.
+
+
+.. _module-from-slots:
Creating extension modules dynamically
--------------------------------------
-The following functions may be used to create a module outside of an
-extension's :ref:`initialization function `.
-They are also used in
-:ref:`single-phase initialization `.
+The following functions may be used to create an extension module dynamically,
+rather than from an extension's :ref:`export hook `.
+
+.. c:function:: PyObject *PyModule_FromSlotsAndSpec(const PyModuleDef_Slot *slots, PyObject *spec)
+
+ Create a new module object, given an array of :ref:`slots `
+ and the :py:class:`~importlib.machinery.ModuleSpec` *spec*.
+
+ The *slots* argument must point to an array of :c:type:`PyModuleDef_Slot`
+ structures, terminated by an entry slot with slot ID of 0
+ (typically written as ``{0}`` or ``{0, NULL}`` in C).
+ The *slots* argument may not be ``NULL``.
+
+ The *spec* argument may be any ``ModuleSpec``-like object, as described
+ in :c:macro:`Py_mod_create` documentation.
+ Currently, the *spec* must have a ``name`` attribute.
+
+ On success, return the new module.
+ On error, return ``NULL`` with an exception set.
+
+ Note that this does not process the module's execution slot
+ (:c:data:`Py_mod_exec`).
+ Both :c:func:`!PyModule_FromSlotsAndSpec` and :c:func:`PyModule_Exec`
+ must be called to fully initialize a module.
+ (See also :ref:`multi-phase-initialization`.)
+
+ The *slots* array only needs to be valid for the duration of the
+ :c:func:`!PyModule_FromSlotsAndSpec` call.
+ In particular, it may be heap-allocated.
+
+ .. versionadded:: next
+
+.. c:function:: int PyModule_Exec(PyObject *module)
+
+ Execute the :c:data:`Py_mod_exec` slot(s) of the given *module*.
+
+ On success, return 0.
+ On error, return -1 with an exception set.
+
+ For clarity: If *module* has no slots, for example if it uses
+ :ref:`legacy single-phase initialization `,
+ this function does nothing and returns 0.
+
+ .. versionadded:: next
+
+
+
+.. _pymoduledef:
+
+Module definition struct
+------------------------
+
+Traditionally, extension modules were defined using a *module definition*
+as the “description" of how a module should be created.
+Rather than using an array of :ref:`slots ` directly,
+the definition has dedicated members for most common functionality,
+and allows additional slots as an extension mechanism.
+
+This way of defining modules is still available and there are no plans to
+remove it.
+
+.. c:type:: PyModuleDef
+
+ The module definition struct, which holds information needed to create
+ a module object.
+
+ This structure must be statically allocated (or be otherwise guaranteed
+ to be valid while any modules created from it exist).
+ Usually, there is only one variable of this type for each extension module
+ defined this way.
+
+ .. c:member:: PyModuleDef_Base m_base
+
+ Always initialize this member to :c:macro:`PyModuleDef_HEAD_INIT`:
+
+ .. c:namespace:: NULL
+
+ .. c:type:: PyModuleDef_Base
+
+ The type of :c:member:`!PyModuleDef.m_base`.
+
+ .. c:macro:: PyModuleDef_HEAD_INIT
+
+ The required initial value for :c:member:`!PyModuleDef.m_base`.
+
+ .. c:member:: const char *m_name
+
+ Corresponds to the :c:macro:`Py_mod_name` slot.
+
+ .. c:member:: const char *m_doc
+
+ These members correspond to the :c:macro:`Py_mod_doc` slot.
+ Setting this to NULL is equivalent to omitting the slot.
+
+ .. c:member:: Py_ssize_t m_size
+
+ Corresponds to the :c:macro:`Py_mod_state_size` slot.
+ Setting this to zero is equivalent to omitting the slot.
+
+ When using :ref:`legacy single-phase initialization `
+ or when creating modules dynamically using :c:func:`PyModule_Create`
+ or :c:func:`PyModule_Create2`, :c:member:`!m_size` may be set to -1.
+ This indicates that the module does not support sub-interpreters,
+ because it has global state.
+
+ .. c:member:: PyMethodDef *m_methods
+
+ Corresponds to the :c:macro:`Py_mod_methods` slot.
+ Setting this to NULL is equivalent to omitting the slot.
+
+ .. c:member:: PyModuleDef_Slot* m_slots
+
+ An array of additional slots, terminated by a ``{0, NULL}`` entry.
+
+ This array may not contain slots corresponding to :c:type:`PyModuleDef`
+ members.
+ For example, you cannot use :c:macro:`Py_mod_name` in :c:member:`!m_slots`;
+ the module name must be given as :c:member:`PyModuleDef.m_name`.
+
+ .. versionchanged:: 3.5
+
+ Prior to version 3.5, this member was always set to ``NULL``,
+ and was defined as:
+
+ .. c:member:: inquiry m_reload
+
+ .. c:member:: traverseproc m_traverse
+ inquiry m_clear
+ freefunc m_free
+
+ These members correspond to the :c:macro:`Py_mod_state_traverse`,
+ :c:macro:`Py_mod_state_clear`, and :c:macro:`Py_mod_state_free` slots,
+ respectively.
+
+ Setting these members to NULL is equivalent to omitting the
+ corresponding slots.
+
+ .. versionchanged:: 3.9
+
+ :c:member:`m_traverse`, :c:member:`m_clear` and :c:member:`m_free`
+ functions are longer called before the module state is allocated.
+
+
+.. _moduledef-dynamic:
+
+The following API can be used to create modules from a :c:type:`!PyModuleDef`
+struct:
.. c:function:: PyObject* PyModule_Create(PyModuleDef *def)
@@ -500,12 +834,13 @@ They are also used in
useful for versioning. This may change in the future.
+.. _capi-module-support-functions:
+
Support functions
-----------------
-The following functions are provided to help initialize a module
-state.
-They are intended for a module's execution slots (:c:data:`Py_mod_exec`),
+The following functions are provided to help initialize a module object.
+They are intended for a module's execution slot (:c:data:`Py_mod_exec`),
the initialization function for legacy :ref:`single-phase initialization `,
or code that creates modules dynamically.
@@ -671,6 +1006,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/set.rst b/Doc/c-api/set.rst
index cba823aa027..09c0fb6b9c5 100644
--- a/Doc/c-api/set.rst
+++ b/Doc/c-api/set.rst
@@ -147,7 +147,7 @@ subtypes but not for instances of :class:`frozenset` or its subtypes.
Return ``1`` if found and removed, ``0`` if not found (no action taken), and ``-1`` if an
error is encountered. Does not raise :exc:`KeyError` for missing keys. Raise a
- :exc:`TypeError` if the *key* is unhashable. Unlike the Python :meth:`~frozenset.discard`
+ :exc:`TypeError` if the *key* is unhashable. Unlike the Python :meth:`~set.discard`
method, this function does not automatically convert unhashable sets into
temporary frozensets. Raise :exc:`SystemError` if *set* is not an
instance of :class:`set` or its subtype.
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..62f45def04f 100644
--- a/Doc/c-api/structures.rst
+++ b/Doc/c-api/structures.rst
@@ -280,6 +280,8 @@ Implementing functions and methods
Name of the method.
+ A ``NULL`` *ml_name* marks the end of a :c:type:`!PyMethodDef` array.
+
.. c:member:: PyCFunction ml_meth
Pointer to the C implementation.
@@ -447,6 +449,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 +493,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 +521,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 +700,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..1f57cc04f5d 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
@@ -250,11 +283,12 @@ Type Objects
``Py_TYPE(self)`` may be a *subclass* of the intended class, and subclasses
are not necessarily defined in the same module as their superclass.
See :c:type:`PyCMethod` to get the class that defines the method.
- See :c:func:`PyType_GetModuleByDef` for cases when :c:type:`!PyCMethod` cannot
- be used.
+ See :c:func:`PyType_GetModuleByToken` for cases when :c:type:`!PyCMethod`
+ cannot be used.
.. versionadded:: 3.9
+
.. c:function:: void* PyType_GetModuleState(PyTypeObject *type)
Return the state of the module object associated with the given type.
@@ -269,10 +303,11 @@ Type Objects
.. versionadded:: 3.9
-.. c:function:: PyObject* PyType_GetModuleByDef(PyTypeObject *type, struct PyModuleDef *def)
- Find the first superclass whose module was created from
- the given :c:type:`PyModuleDef` *def*, and return that module.
+.. c:function:: PyObject* PyType_GetModuleByToken(PyTypeObject *type, const void *mod_token)
+
+ Find the first superclass whose module has the given
+ :ref:`module token `, and return that module.
If no module is found, raises a :py:class:`TypeError` and returns ``NULL``.
@@ -282,16 +317,34 @@ Type Objects
and other places where a method's defining class cannot be passed using the
:c:type:`PyCMethod` calling convention.
+ .. versionadded:: next
+
+
+.. c:function:: PyObject* PyType_GetModuleByDef(PyTypeObject *type, struct PyModuleDef *def)
+
+ Find the first superclass whose module was created from the given
+ :c:type:`PyModuleDef` *def*, or whose :ref:`module token `
+ is equal to *def*, and return that module.
+
+ Note that modules created from a :c:type:`PyModuleDef` always have their
+ token set to the :c:type:`PyModuleDef`'s address.
+ In other words, this function is equivalent to
+ :c:func:`PyType_GetModuleByToken`, except that it:
+
+ - returns a borrowed reference, and
+ - has a non-``void*`` argument type (which is a cosmetic difference in C).
+
The returned reference is :term:`borrowed ` from *type*,
and will be valid as long as you hold a reference to *type*.
Do not release it with :c:func:`Py_DECREF` or similar.
.. versionadded:: 3.11
-.. c:function:: int PyType_GetBaseByToken(PyTypeObject *type, void *token, PyTypeObject **result)
+
+.. c:function:: int PyType_GetBaseByToken(PyTypeObject *type, void *tp_token, PyTypeObject **result)
Find the first superclass in *type*'s :term:`method resolution order` whose
- :c:macro:`Py_tp_token` token is equal to the given one.
+ :c:macro:`Py_tp_token` token is equal to *tp_token*.
* If found, set *\*result* to a new :term:`strong reference`
to it and return ``1``.
@@ -302,10 +355,11 @@ Type Objects
The *result* argument may be ``NULL``, in which case *\*result* is not set.
Use this if you need only the return value.
- The *token* argument may not be ``NULL``.
+ The *tp_token* argument may not be ``NULL``.
.. versionadded:: 3.14
+
.. c:function:: int PyUnstable_Type_AssignVersionTag(PyTypeObject *type)
Attempt to assign a version tag to the given type.
@@ -316,6 +370,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 +400,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 +428,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 +455,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 +477,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 +498,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 +607,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 +628,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 +655,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 +666,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..7eb9f0b54ab 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,92 @@ 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
+
+
+Stack Effects
+^^^^^^^^^^^^^
+
+.. seealso::
+ :py:func:`dis.stack_effect`
+
+
+.. c:macro:: PY_INVALID_STACK_EFFECT
+
+ Sentinel value representing an invalid stack effect.
+
+ This is currently equivalent to ``INT_MAX``.
+
+ .. versionadded:: 3.8
+
+
+.. c:function:: int PyCompile_OpcodeStackEffect(int opcode, int oparg)
+
+ Compute the stack effect of *opcode* with argument *oparg*.
+
+ On success, this function returns the stack effect; on failure, this
+ returns :c:macro:`PY_INVALID_STACK_EFFECT`.
+
+ .. versionadded:: 3.4
+
+
+.. c:function:: int PyCompile_OpcodeStackEffectWithJump(int opcode, int oparg, int jump)
+
+ Similar to :c:func:`PyCompile_OpcodeStackEffect`, but don't include the
+ stack effect of jumping if *jump* is zero.
+
+ If *jump* is ``0``, this will not include the stack effect of jumping, but
+ if *jump* is ``1`` or ``-1``, this will include it.
+
+ On success, this function returns the stack effect; on failure, this
+ returns :c:macro:`PY_INVALID_STACK_EFFECT`.
+
+ .. 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/refcounts.dat b/Doc/data/refcounts.dat
index 48f4f4919e8..64399f6ab1f 100644
--- a/Doc/data/refcounts.dat
+++ b/Doc/data/refcounts.dat
@@ -1472,6 +1472,9 @@ PyModule_Create2:PyObject*::+1:
PyModule_Create2:PyModuleDef*:def::
PyModule_Create2:int:module_api_version::
+PyModule_Exec:int:::
+PyModule_ExecDef:PyObject*:module:0:
+
PyModule_ExecDef:int:::
PyModule_ExecDef:PyObject*:module:0:
PyModule_ExecDef:PyModuleDef*:def::
@@ -1485,6 +1488,10 @@ PyModule_FromDefAndSpec2:PyModuleDef*:def::
PyModule_FromDefAndSpec2:PyObject*:spec:0:
PyModule_FromDefAndSpec2:int:module_api_version::
+PyModule_FromSlotsAndSpec:PyObject*::+1:
+PyModule_FromSlotsAndSpec:const PyModuleDef_Slot *:slots::
+PyModule_FromSlotsAndSpec:PyObject*:spec:0:
+
PyModule_GetDef:PyModuleDef*::0:
PyModule_GetDef:PyObject*:module:0:
@@ -1506,6 +1513,14 @@ PyModule_GetNameObject:PyObject*:module:0:
PyModule_GetState:void*:::
PyModule_GetState:PyObject*:module:0:
+PyModule_GetStateSize:int:::
+PyModule_GetStateSize:PyObject*:module:0:
+PyModule_GetToken:Py_ssize_t**:result::
+
+PyModule_GetToken:int:::
+PyModule_GetToken:PyObject*:module:0:
+PyModule_GetToken:void**:result::
+
PyModule_New:PyObject*::+1:
PyModule_New:char*:name::
@@ -2412,6 +2427,10 @@ PyType_GetFlags:PyTypeObject*:type:0:
PyType_GetName:PyObject*::+1:
PyType_GetName:PyTypeObject*:type:0:
+PyType_GetModuleByToken:PyObject*::+1:
+PyType_GetModuleByToken:PyTypeObject*:type:0:
+PyType_GetModuleByToken:PyModuleDef*:def::
+
PyType_GetModuleByDef:PyObject*::0:
PyType_GetModuleByDef:PyTypeObject*:type:0:
PyType_GetModuleByDef:PyModuleDef*:def::
diff --git a/Doc/data/stable_abi.dat b/Doc/data/stable_abi.dat
index 7ad5f3ecfab..9c5fdcefaf8 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,,
@@ -428,6 +464,7 @@ data,PyMethodDescr_Type,3.2,,
type,PyModuleDef,3.2,,full-abi
type,PyModuleDef_Base,3.2,,full-abi
func,PyModuleDef_Init,3.5,,
+type,PyModuleDef_Slot,3.5,,full-abi
data,PyModuleDef_Type,3.5,,
func,PyModule_Add,3.13,,
func,PyModule_AddFunctions,3.7,,
@@ -437,8 +474,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 +485,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 +745,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 +878,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,,
@@ -866,6 +916,7 @@ func,Py_GetPlatform,3.2,,
func,Py_GetRecursionLimit,3.2,,
func,Py_GetVersion,3.2,,
data,Py_HasFileSystemDefaultEncoding,3.2,,
+func,Py_IS_TYPE,3.15,,
func,Py_IncRef,3.2,,
func,Py_Initialize,3.2,,
func,Py_InitializeEx,3.2,,
@@ -882,22 +933,147 @@ 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_SET_SIZE,3.15,,
+func,Py_SIZE,3.15,,
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_create,3.5,,
+macro,Py_mod_doc,3.15,,
+macro,Py_mod_exec,3.5,,
+macro,Py_mod_gil,3.13,,
+macro,Py_mod_methods,3.15,,
+macro,Py_mod_multiple_interpreters,3.12,,
+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.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/extending/extending.rst b/Doc/extending/extending.rst
index dee92312169..f9b65643dfe 100644
--- a/Doc/extending/extending.rst
+++ b/Doc/extending/extending.rst
@@ -426,7 +426,7 @@ A pointer to the module definition must be returned via :c:func:`PyModuleDef_Ini
so that the import machinery can create the module and store it in ``sys.modules``.
When embedding Python, the :c:func:`!PyInit_spam` function is not called
-automatically unless there's an entry in the :c:data:`!PyImport_Inittab` table.
+automatically unless there's an entry in the :c:data:`PyImport_Inittab` table.
To add the module to the initialization table, use :c:func:`PyImport_AppendInittab`,
optionally followed by an import of the module::
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..3adfedbf410 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,17 @@ 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.
+:mod:`!asyncio` automatically associates tasks with the event loop for you.
+This automatic association was purposely designed into :mod:`!asyncio` for
+the sake of simplicity.
+Without it, you'd have to keep track of the event loop object and pass it to
+any coroutine function that wants to create tasks, adding redundant clutter
+to your code.
::
@@ -250,6 +253,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 +288,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 +358,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 +377,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 +462,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..83eba8cfea3 100644
--- a/Doc/howto/free-threading-extensions.rst
+++ b/Doc/howto/free-threading-extensions.rst
@@ -45,9 +45,12 @@ single-phase initialization.
Multi-Phase Initialization
..........................
-Extensions that use multi-phase initialization (i.e.,
-:c:func:`PyModuleDef_Init`) should add a :c:data:`Py_mod_gil` slot in the
-module definition. If your extension supports older versions of CPython,
+Extensions that use :ref:`multi-phase initialization `
+(functions like :c:func:`PyModuleDef_Init`,
+:c:func:`PyModExport_* ` export hook,
+:c:func:`PyModule_FromSlotsAndSpec`) should add a
+:c:data:`Py_mod_gil` slot in the module definition.
+If your extension supports older versions of CPython,
you should guard the slot with a :c:data:`PY_VERSION_HEX` check.
::
@@ -60,18 +63,12 @@ you should guard the slot with a :c:data:`PY_VERSION_HEX` check.
{0, NULL}
};
- static struct PyModuleDef moduledef = {
- PyModuleDef_HEAD_INIT,
- .m_slots = module_slots,
- ...
- };
-
Single-Phase Initialization
...........................
-Extensions that use single-phase initialization (i.e.,
-:c:func:`PyModule_Create`) should call :c:func:`PyUnstable_Module_SetGIL` to
+Extensions that use legacy :ref:`single-phase initialization `
+(that is, :c:func:`PyModule_Create`) should call :c:func:`PyUnstable_Module_SetGIL` to
indicate that they support running with the GIL disabled. The function is
only defined in the free-threaded build, so you should guard the call with
``#ifdef Py_GIL_DISABLED`` to avoid compilation errors in the regular build.
@@ -203,7 +200,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 +341,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 +394,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..380c2be0495 100644
--- a/Doc/howto/free-threading-python.rst
+++ b/Doc/howto/free-threading-python.rst
@@ -11,9 +11,7 @@ available processing power by running threads in parallel on available CPU cores
While not all software will benefit from this automatically, programs
designed with threading in mind will run faster on multi-core hardware.
-The free-threaded mode is working and continues to be improved, but
-there is some additional overhead in single-threaded workloads compared
-to the regular build. Additionally, third-party packages, in particular ones
+Some third-party packages, in particular ones
with an :term:`extension module`, may not be ready for use in a
free-threaded build, and will re-enable the :term:`GIL`.
@@ -101,60 +99,42 @@ This section describes known limitations of the free-threaded CPython build.
Immortalization
---------------
-The free-threaded build of the 3.13 release makes some objects :term:`immortal`.
+In the free-threaded build, some objects are :term:`immortal`.
Immortal objects are not deallocated and have reference counts that are
never modified. This is done to avoid reference count contention that would
prevent efficient multi-threaded scaling.
-An object will be made immortal when a new thread is started for the first time
-after the main thread is running. The following objects are immortalized:
+As of the 3.14 release, immortalization is limited to:
-* :ref:`function ` objects declared at the module level
-* :ref:`method ` descriptors
-* :ref:`code ` objects
-* :term:`module` objects and their dictionaries
-* :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.
-
-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.
+* Code constants: numeric literals, string literals, and tuple literals
+ composed of other constants.
+* Strings interned by :func:`sys.intern`.
Frame objects
-------------
-It is not safe to access :ref:`frame ` objects from other
-threads and doing so may cause your program to crash . This means that
-:func:`sys._current_frames` is generally not safe to use in a free-threaded
-build. Functions like :func:`inspect.currentframe` and :func:`sys._getframe`
-are generally safe as long as the resulting frame object is not passed to
-another thread.
+It is not safe to access :attr:`frame.f_locals` from a :ref:`frame `
+object if that frame is currently executing in another thread, and doing so may
+crash the interpreter.
+
Iterators
---------
-Sharing the same iterator object between multiple threads is generally not
-safe and threads may see duplicate or missing elements when iterating or crash
-the interpreter.
+It is generally not thread-safe to access the same iterator object from
+multiple threads concurrently, and threads may see duplicate or missing
+elements.
Single-threaded performance
---------------------------
The free-threaded build has additional overhead when executing Python code
-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.
+compared to the default GIL-enabled build. The amount of overhead depends
+on the workload and hardware. On the pyperformance benchmark suite, the
+average overhead ranges from about 1% on macOS aarch64 to 8% on x86-64 Linux
+systems.
Behavioral changes
diff --git a/Doc/howto/functional.rst b/Doc/howto/functional.rst
index 053558e3890..552514063c9 100644
--- a/Doc/howto/functional.rst
+++ b/Doc/howto/functional.rst
@@ -4,7 +4,7 @@
Functional Programming HOWTO
********************************
-:Author: A. M. Kuchling
+:Author: \A. M. Kuchling
:Release: 0.32
In this document, we'll take a tour of Python's features suitable for
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/howto/unicode.rst b/Doc/howto/unicode.rst
index 254fe729355..243cc27bac7 100644
--- a/Doc/howto/unicode.rst
+++ b/Doc/howto/unicode.rst
@@ -352,6 +352,8 @@ If you don't include such a comment, the default encoding used will be UTF-8 as
already mentioned. See also :pep:`263` for more information.
+.. _unicode-properties:
+
Unicode Properties
------------------
diff --git a/Doc/howto/urllib2.rst b/Doc/howto/urllib2.rst
index d79d1abe8d0..4e77d2cb407 100644
--- a/Doc/howto/urllib2.rst
+++ b/Doc/howto/urllib2.rst
@@ -15,7 +15,7 @@ Introduction
You may also find useful the following article on fetching web resources
with Python:
- * `Basic Authentication `_
+ * `Basic Authentication `__
A tutorial on *Basic Authentication*, with examples in Python.
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 9655db4f301..71c4f094886 100644
--- a/Doc/library/argparse.rst
+++ b/Doc/library/argparse.rst
@@ -767,9 +767,9 @@ how the command-line arguments should be handled. The supplied actions are:
Namespace(foo=42)
* ``'store_true'`` and ``'store_false'`` - These are special cases of
- ``'store_const'`` used for storing the values ``True`` and ``False``
- respectively. In addition, they create default values of ``False`` and
- ``True`` respectively::
+ ``'store_const'`` that respectively store the values ``True`` and ``False``
+ with default values of ``False`` and
+ ``True``::
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', action='store_true')
@@ -789,8 +789,8 @@ how the command-line arguments should be handled. The supplied actions are:
>>> parser.parse_args('--foo 1 --foo 2'.split())
Namespace(foo=['0', '1', '2'])
-* ``'append_const'`` - This stores a list, and appends the value specified by
- the const_ keyword argument to the list; note that the const_ keyword
+* ``'append_const'`` - This appends the value specified by
+ the const_ keyword argument to a list; note that the const_ keyword
argument defaults to ``None``. The ``'append_const'`` action is typically
useful when multiple arguments need to store constants to the same list. For
example::
@@ -801,8 +801,8 @@ how the command-line arguments should be handled. The supplied actions are:
>>> parser.parse_args('--str --int'.split())
Namespace(types=[, ])
-* ``'extend'`` - This stores a list and appends each item from the multi-value
- argument list to it.
+* ``'extend'`` - This appends each item from a multi-value
+ argument to a list.
The ``'extend'`` action is typically used with the nargs_ keyword argument
value ``'+'`` or ``'*'``.
Note that when nargs_ is ``None`` (the default) or ``'?'``, each
@@ -816,7 +816,7 @@ how the command-line arguments should be handled. The supplied actions are:
.. versionadded:: 3.8
-* ``'count'`` - This counts the number of times a keyword argument occurs. For
+* ``'count'`` - This counts the number of times an argument occurs. For
example, this is useful for increasing verbosity levels::
>>> parser = argparse.ArgumentParser()
@@ -1322,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
@@ -1331,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::
@@ -1344,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:
@@ -1437,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
-----------------------
@@ -2070,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/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..621aa23ecc8 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
@@ -2109,20 +2109,20 @@ to work with the :class:`Decimal` class::
Decimal FAQ
-----------
-Q. It is cumbersome to type ``decimal.Decimal('1234.5')``. Is there a way to
+Q: It is cumbersome to type ``decimal.Decimal('1234.5')``. Is there a way to
minimize typing when using the interactive interpreter?
-A. Some users abbreviate the constructor to just a single letter:
+A: Some users abbreviate the constructor to just a single letter:
>>> D = decimal.Decimal
>>> D('1.23') + D('3.45')
Decimal('4.68')
-Q. In a fixed-point application with two decimal places, some inputs have many
+Q: In a fixed-point application with two decimal places, some inputs have many
places and need to be rounded. Others are not supposed to have excess digits
and need to be validated. What methods should be used?
-A. The :meth:`~Decimal.quantize` method rounds to a fixed number of decimal places. If
+A: The :meth:`~Decimal.quantize` method rounds to a fixed number of decimal places. If
the :const:`Inexact` trap is set, it is also useful for validation:
>>> TWOPLACES = Decimal(10) ** -2 # same as Decimal('0.01')
@@ -2140,10 +2140,10 @@ the :const:`Inexact` trap is set, it is also useful for validation:
...
Inexact: None
-Q. Once I have valid two place inputs, how do I maintain that invariant
+Q: Once I have valid two place inputs, how do I maintain that invariant
throughout an application?
-A. Some operations like addition, subtraction, and multiplication by an integer
+A: Some operations like addition, subtraction, and multiplication by an integer
will automatically preserve fixed point. Others operations, like division and
non-integer multiplication, will change the number of decimal places and need to
be followed-up with a :meth:`~Decimal.quantize` step:
@@ -2175,21 +2175,21 @@ to handle the :meth:`~Decimal.quantize` step:
>>> div(b, a)
Decimal('0.03')
-Q. There are many ways to express the same value. The numbers ``200``,
+Q: There are many ways to express the same value. The numbers ``200``,
``200.000``, ``2E2``, and ``.02E+4`` all have the same value at
various precisions. Is there a way to transform them to a single recognizable
canonical value?
-A. The :meth:`~Decimal.normalize` method maps all equivalent values to a single
+A: The :meth:`~Decimal.normalize` method maps all equivalent values to a single
representative:
>>> values = map(Decimal, '200 200.000 2E2 .02E+4'.split())
>>> [v.normalize() for v in values]
[Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2')]
-Q. When does rounding occur in a computation?
+Q: When does rounding occur in a computation?
-A. It occurs *after* the computation. The philosophy of the decimal
+A: It occurs *after* the computation. The philosophy of the decimal
specification is that numbers are considered exact and are created
independent of the current context. They can even have greater
precision than current context. Computations process with those
@@ -2207,10 +2207,10 @@ applied to the *result* of the computation::
>>> pi + 0 - Decimal('0.00005'). # Intermediate values are rounded
Decimal('3.1416')
-Q. Some decimal values always print with exponential notation. Is there a way
+Q: Some decimal values always print with exponential notation. Is there a way
to get a non-exponential representation?
-A. For some values, exponential notation is the only way to express the number
+A: For some values, exponential notation is the only way to express the number
of significant places in the coefficient. For example, expressing
``5.0E+3`` as ``5000`` keeps the value constant but cannot show the
original's two-place significance.
@@ -2225,9 +2225,9 @@ value unchanged:
>>> remove_exponent(Decimal('5E+3'))
Decimal('5000')
-Q. Is there a way to convert a regular float to a :class:`Decimal`?
+Q: Is there a way to convert a regular float to a :class:`Decimal`?
-A. Yes, any binary floating-point number can be exactly expressed as a
+A: Yes, any binary floating-point number can be exactly expressed as a
Decimal though an exact conversion may take more precision than intuition would
suggest:
@@ -2236,19 +2236,19 @@ suggest:
>>> Decimal(math.pi)
Decimal('3.141592653589793115997963468544185161590576171875')
-Q. Within a complex calculation, how can I make sure that I haven't gotten a
+Q: Within a complex calculation, how can I make sure that I haven't gotten a
spurious result because of insufficient precision or rounding anomalies.
-A. The decimal module makes it easy to test results. A best practice is to
+A: The decimal module makes it easy to test results. A best practice is to
re-run calculations using greater precision and with various rounding modes.
Widely differing results indicate insufficient precision, rounding mode issues,
ill-conditioned inputs, or a numerically unstable algorithm.
-Q. I noticed that context precision is applied to the results of operations but
+Q: I noticed that context precision is applied to the results of operations but
not to the inputs. Is there anything to watch out for when mixing values of
different precisions?
-A. Yes. The principle is that all values are considered to be exact and so is
+A: Yes. The principle is that all values are considered to be exact and so is
the arithmetic on those values. Only the results are rounded. The advantage
for inputs is that "what you type is what you get". A disadvantage is that the
results can look odd if you forget that the inputs haven't been rounded:
@@ -2276,9 +2276,9 @@ Alternatively, inputs can be rounded upon creation using the
>>> Context(prec=5, rounding=ROUND_DOWN).create_decimal('1.2345678')
Decimal('1.2345')
-Q. Is the CPython implementation fast for large numbers?
+Q: Is the CPython implementation fast for large numbers?
-A. Yes. In the CPython and PyPy3 implementations, the C/CFFI versions of
+A: Yes. In the CPython and PyPy3 implementations, the C/CFFI versions of
the decimal module integrate the high speed `libmpdec
`_ library for
arbitrary precision correctly rounded decimal floating-point arithmetic [#]_.
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..221c0712c7c 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
@@ -57,6 +57,10 @@ The :mod:`functools` module defines the following functions:
another thread makes an additional call before the initial call has been
completed and cached.
+ Call-once behavior is not guaranteed because locks are not held during the
+ function call. Potentially another call with the same arguments could
+ occur while the first call is still running.
+
.. versionadded:: 3.9
@@ -672,7 +676,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 +720,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 e547c96b580..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.)
@@ -206,7 +210,7 @@ New Indent Width
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..92605c57527 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::
@@ -829,8 +832,8 @@ raising an exception.
One difference from other Python queue implementations, is that :mod:`multiprocessing`
queues serializes all objects that are put into them using :mod:`pickle`.
-The object return by the get method is a re-created object that does not share memory
-with the original object.
+The object returned by the get method is a re-created object that does not share
+memory with the original object.
Note that one can also create a shared queue by using a manager object -- see
:ref:`multiprocessing-managers`.
@@ -887,7 +890,7 @@ For an example of the usage of queues for interprocess communication see
:ref:`multiprocessing-examples`.
-.. function:: Pipe([duplex])
+.. function:: Pipe(duplex=True)
Returns a pair ``(conn1, conn2)`` of
:class:`~multiprocessing.connection.Connection` objects representing the
@@ -1574,12 +1577,22 @@ object -- see :ref:`multiprocessing-managers`.
A solitary difference from its close analog exists: its ``acquire`` method's
first argument is named *block*, as is consistent with :meth:`Lock.acquire`.
+
+ .. method:: get_value()
+
+ Return the current value of semaphore.
+
+ Note that this may raise :exc:`NotImplementedError` on platforms like
+ macOS where ``sem_getvalue()`` is not implemented.
+
+
.. method:: locked()
Return a boolean indicating whether this object is locked right now.
.. versionadded:: 3.14
+
.. note::
On macOS, ``sem_timedwait`` is unsupported, so calling ``acquire()`` with
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..03ad50b2c5e 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
@@ -339,79 +347,6 @@ The statistical profiler produces output similar to deterministic profilers but
.. _profile-cli:
-:mod:`!profiling.sampling` Module Reference
-=======================================================
-
-.. module:: profiling.sampling
- :synopsis: Python statistical profiler.
-
-This section documents the programmatic interface for the :mod:`!profiling.sampling` module.
-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)
-
- Sample a Python process and generate profiling data.
-
- This is the main entry point for statistical profiling. It creates a
- :class:`SampleProfiler`, collects stack traces from the target process, and
- outputs the results in the specified format.
-
- :param int pid: Process ID of the target Python process
- :param int sort: Sort order for pstats output (default: 2 for cumulative time)
- :param int sample_interval_usec: Sampling interval in microseconds (default: 100)
- :param int duration_sec: Duration to sample in seconds (default: 10)
- :param str filename: Output filename (None for stdout/default naming)
- :param bool all_threads: Whether to sample all threads (default: False)
- :param int limit: Maximum number of functions to display (default: None)
- :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)
-
- :raises ValueError: If output_format is not 'pstats' or 'collapsed'
-
- Examples::
-
- # Basic usage - profile process 1234 for 10 seconds
- import profiling.sampling
- profiling.sampling.sample(1234)
-
- # Profile with custom settings
- profiling.sampling.sample(1234, duration_sec=30, sample_interval_usec=50, all_threads=True)
-
- # Generate collapsed stack traces for flamegraph.pl
- profiling.sampling.sample(1234, output_format='collapsed', filename='profile.collapsed')
-
-.. class:: SampleProfiler(pid, sample_interval_usec, all_threads)
-
- Low-level API for the statistical profiler.
-
- This profiler uses periodic stack sampling to collect performance data
- from running Python processes with minimal overhead. It can attach to
- any Python process by PID and collect stack traces at regular intervals.
-
- :param int pid: Process ID of the target Python process
- :param int sample_interval_usec: Sampling interval in microseconds
- :param bool all_threads: Whether to sample all threads or just the main thread
-
- .. method:: sample(collector, duration_sec=10)
-
- Sample the target process for the specified duration.
-
- Collects stack traces from the target process at regular intervals
- and passes them to the provided collector for processing.
-
- :param collector: Object that implements ``collect()`` method to process stack traces
- :param int duration_sec: Duration to sample in seconds (default: 10)
-
- The method tracks sampling statistics and can display real-time
- information if realtime_stats is enabled.
-
-.. seealso::
-
- :ref:`sampling-profiler-cli`
- Command-line interface documentation for the statistical profiler.
-
Deterministic Profiler Command Line Interface
=============================================
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..780cc773403 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
@@ -244,6 +246,15 @@ Startup hooks
if Python was compiled for a version of the library that supports it.
+.. function:: get_pre_input_hook()
+
+ Get the current pre-input hook function, or ``None`` if no pre-input hook
+ function has been set. This function only exists if Python was compiled
+ for a version of the library that supports it.
+
+ .. versionadded:: next
+
+
.. _readline-completion:
Completion
diff --git a/Doc/library/select.rst b/Doc/library/select.rst
index e821cb01d94..62b5161fb80 100644
--- a/Doc/library/select.rst
+++ b/Doc/library/select.rst
@@ -115,7 +115,7 @@ The module defines the following:
:ref:`kevent-objects` below for the methods supported by kevent objects.
-.. function:: select(rlist, wlist, xlist[, timeout])
+.. function:: select(rlist, wlist, xlist, timeout=None)
This is a straightforward interface to the Unix :c:func:`!select` system call.
The first three arguments are iterables of 'waitable objects': either
@@ -131,7 +131,7 @@ The module defines the following:
platform-dependent. (It is known to work on Unix but not on Windows.) The
optional *timeout* argument specifies a time-out in seconds; it may be
a non-integer to specify fractions of seconds.
- When the *timeout* argument is omitted the function blocks until
+ When the *timeout* argument is omitted or ``None``, the function blocks until
at least one file descriptor is ready. A time-out value of zero specifies a
poll and never blocks.
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..b16cde34ec1 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
@@ -2092,11 +2095,8 @@ to sockets.
Accepts any real number, not only integer or float.
-.. method:: socket.setsockopt(level, optname, value: int)
-.. method:: socket.setsockopt(level, optname, value: buffer)
- :noindex:
-.. method:: socket.setsockopt(level, optname, None, optlen: int)
- :noindex:
+.. method:: socket.setsockopt(level, optname, value: int | Buffer)
+ socket.setsockopt(level, optname, None, optlen: int)
.. index:: pair: module; struct
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..7d30094963d 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::
@@ -2958,16 +2959,16 @@ of TLS/SSL. Some new TLS 1.3 features are not yet available.
Steve Kent
:rfc:`RFC 4086: Randomness Requirements for Security <4086>`
- Donald E., Jeffrey I. Schiller
+ Donald E. Eastlake, Jeffrey I. Schiller, Steve Crocker
:rfc:`RFC 5280: Internet X.509 Public Key Infrastructure Certificate and Certificate Revocation List (CRL) Profile <5280>`
- D. Cooper
+ David Cooper et al.
:rfc:`RFC 5246: The Transport Layer Security (TLS) Protocol Version 1.2 <5246>`
- T. Dierks et. al.
+ Tim Dierks and Eric Rescorla.
:rfc:`RFC 6066: Transport Layer Security (TLS) Extensions <6066>`
- D. Eastlake
+ Donald E. Eastlake
`IANA TLS: Transport Layer Security (TLS) Parameters `_
IANA
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..3899e5b59d8 100644
--- a/Doc/library/stdtypes.rst
+++ b/Doc/library/stdtypes.rst
@@ -1994,10 +1994,16 @@ expression support in the :mod:`re` module).
``{}``. Each replacement field contains either the numeric index of a
positional argument, or the name of a keyword argument. Returns a copy of
the string where each replacement field is replaced with the string value of
- the corresponding argument.
+ the corresponding argument. For example:
+
+ .. doctest::
>>> "The sum of 1 + 2 is {0}".format(1+2)
'The sum of 1 + 2 is 3'
+ >>> "The sum of {a} + {b} is {answer}".format(answer=1+2, a=1, b=2)
+ 'The sum of 1 + 2 is 3'
+ >>> "{1} expects the {0} Inquisition!".format("Spanish", "Nobody")
+ 'Nobody expects the Spanish Inquisition!'
See :ref:`formatstrings` for a description of the various formatting options
that can be specified in format strings.
@@ -2057,13 +2063,32 @@ expression support in the :mod:`re` module).
from the `Alphabetic property defined in the section 4.10 'Letters, Alphabetic, and
Ideographic' of the Unicode Standard
`__.
+ For example:
+
+ .. doctest::
+
+ >>> 'Letters and spaces'.isalpha()
+ False
+ >>> 'LettersOnly'.isalpha()
+ True
+ >>> 'µ'.isalpha() # non-ASCII characters can be considered alphabetical too
+ True
+
+ See :ref:`unicode-properties`.
.. method:: str.isascii()
Return ``True`` if the string is empty or all characters in the string are ASCII,
``False`` otherwise.
- ASCII characters have code points in the range U+0000-U+007F.
+ ASCII characters have code points in the range U+0000-U+007F. For example:
+
+ .. doctest::
+
+ >>> 'ASCII characters'.isascii()
+ True
+ >>> 'µ'.isascii()
+ False
.. versionadded:: 3.7
@@ -2073,9 +2098,18 @@ expression support in the :mod:`re` module).
Return ``True`` if all characters in the string are decimal
characters and there is at least one character, ``False``
otherwise. Decimal characters are those that can be used to form
- numbers in base 10, e.g. U+0660, ARABIC-INDIC DIGIT
+ numbers in base 10, such as U+0660, ARABIC-INDIC DIGIT
ZERO. Formally a decimal character is a character in the Unicode
- General Category "Nd".
+ General Category "Nd". For example:
+
+ .. doctest::
+
+ >>> '0123456789'.isdecimal()
+ True
+ >>> '٠١٢٣٤٥٦٧٨٩'.isdecimal() # Arabic-Indic digits zero to nine
+ True
+ >>> 'alphabetic'.isdecimal()
+ False
.. method:: str.isdigit()
@@ -2194,7 +2228,16 @@ expression support in the :mod:`re` module).
Return a string which is the concatenation of the strings in *iterable*.
A :exc:`TypeError` will be raised if there are any non-string values in
*iterable*, including :class:`bytes` objects. The separator between
- elements is the string providing this method.
+ elements is the string providing this method. For example:
+
+ .. doctest::
+
+ >>> ', '.join(['spam', 'spam', 'spam'])
+ 'spam, spam, spam'
+ >>> '-'.join('Python')
+ 'P-y-t-h-o-n'
+
+ See also :meth:`split`.
.. method:: str.ljust(width, fillchar=' ', /)
@@ -2408,6 +2451,8 @@ expression support in the :mod:`re` module).
>>> " foo ".split(maxsplit=0)
['foo ']
+ See also :meth:`join`.
+
.. index::
single: universal newlines; str.splitlines method
@@ -2611,6 +2656,8 @@ expression support in the :mod:`re` module).
single: : (colon); in formatted string literal
single: = (equals); for help in debugging using string literals
+.. _stdtypes-fstrings:
+
Formatted String Literals (f-strings)
-------------------------------------
@@ -2619,123 +2666,147 @@ Formatted String Literals (f-strings)
The :keyword:`await` and :keyword:`async for` can be used in expressions
within f-strings.
.. versionchanged:: 3.8
- Added the debugging operator (``=``)
+ Added the debug specifier (``=``)
.. versionchanged:: 3.12
Many restrictions on expressions within f-strings have been removed.
Notably, nested strings, comments, and backslashes are now permitted.
An :dfn:`f-string` (formally a :dfn:`formatted string literal`) is
a string literal that is prefixed with ``f`` or ``F``.
-This type of string literal allows embedding arbitrary Python expressions
-within *replacement fields*, which are delimited by curly brackets (``{}``).
-These expressions are evaluated at runtime, similarly to :meth:`str.format`,
-and are converted into regular :class:`str` objects.
-For example:
+This type of string literal allows embedding the results of arbitrary Python
+expressions within *replacement fields*, which are delimited by curly
+brackets (``{}``).
+Each replacement field must contain an expression, optionally followed by:
-.. doctest::
+* a *debug specifier* -- an equal sign (``=``);
+* a *conversion specifier* -- ``!s``, ``!r`` or ``!a``; and/or
+* a *format specifier* prefixed with a colon (``:``).
- >>> who = 'nobody'
- >>> nationality = 'Spanish'
- >>> f'{who.title()} expects the {nationality} Inquisition!'
- 'Nobody expects the Spanish Inquisition!'
+See the :ref:`Lexical Analysis section on f-strings ` for details
+on the syntax of these fields.
-It is also possible to use a multi line f-string:
+Debug specifier
+^^^^^^^^^^^^^^^
-.. doctest::
+.. versionadded:: 3.8
- >>> f'''This is a string
- ... on two lines'''
- 'This is a string\non two lines'
+If a debug specifier -- an equal sign (``=``) -- appears after the replacement
+field expression, the resulting f-string will contain the expression's source,
+the equal sign, and the value of the expression.
+This is often useful for debugging::
-A single opening curly bracket, ``'{'``, marks a *replacement field* that
-can contain any Python expression:
+ >>> number = 14.3
+ >>> f'{number=}'
+ 'number=14.3'
-.. doctest::
+Whitespace before, inside and after the expression, as well as whitespace
+after the equal sign, is significant --- it is retained in the result::
- >>> nationality = 'Spanish'
- >>> f'The {nationality} Inquisition!'
- 'The Spanish Inquisition!'
+ >>> f'{ number - 4 = }'
+ ' number - 4 = 10.3'
-To include a literal ``{`` or ``}``, use a double bracket:
-.. doctest::
+Conversion specifier
+^^^^^^^^^^^^^^^^^^^^
- >>> x = 42
- >>> f'{{x}} is {x}'
- '{x} is 42'
-
-Functions can also be used, and :ref:`format specifiers `:
-
-.. doctest::
-
- >>> from math import sqrt
- >>> f'√2 \N{ALMOST EQUAL TO} {sqrt(2):.5f}'
- '√2 ≈ 1.41421'
-
-Any non-string expression is converted using :func:`str`, by default:
-
-.. doctest::
+By default, the value of a replacement field expression is converted to
+a string using :func:`str`::
>>> from fractions import Fraction
- >>> f'{Fraction(1, 3)}'
+ >>> one_third = Fraction(1, 3)
+ >>> f'{one_third}'
'1/3'
-To use an explicit conversion, use the ``!`` (exclamation mark) operator,
-followed by any of the valid formats, which are:
+When a debug specifier but no format specifier is used, the default conversion
+instead uses :func:`repr`::
-========== ==============
-Conversion Meaning
-========== ==============
-``!a`` :func:`ascii`
-``!r`` :func:`repr`
-``!s`` :func:`str`
-========== ==============
+ >>> f'{one_third = }'
+ 'one_third = Fraction(1, 3)'
-For example:
+The conversion can be specified explicitly using one of these specifiers:
-.. doctest::
+* ``!s`` for :func:`str`
+* ``!r`` for :func:`repr`
+* ``!a`` for :func:`ascii`
- >>> from fractions import Fraction
- >>> f'{Fraction(1, 3)!s}'
+For example::
+
+ >>> str(one_third)
'1/3'
- >>> f'{Fraction(1, 3)!r}'
+ >>> repr(one_third)
'Fraction(1, 3)'
- >>> question = '¿Dónde está el Presidente?'
- >>> print(f'{question!a}')
- '\xbfD\xf3nde est\xe1 el Presidente?'
-While debugging it may be helpful to see both the expression and its value,
-by using the equals sign (``=``) after the expression.
-This preserves spaces within the brackets, and can be used with a converter.
-By default, the debugging operator uses the :func:`repr` (``!r``) conversion.
-For example:
+ >>> f'{one_third!s} is {one_third!r}'
+ '1/3 is Fraction(1, 3)'
-.. doctest::
+ >>> string = "¡kočka 😸!"
+ >>> ascii(string)
+ "'\\xa1ko\\u010dka \\U0001f638!'"
+
+ >>> f'{string = !a}'
+ "string = '\\xa1ko\\u010dka \\U0001f638!'"
+
+
+Format specifier
+^^^^^^^^^^^^^^^^
+
+After the expression has been evaluated, and possibly converted using an
+explicit conversion specifier, it is formatted using the :func:`format` function.
+If the replacement field includes a *format specifier* introduced by a colon
+(``:``), the specifier is passed to :func:`!format` as the second argument.
+The result of :func:`!format` is then used as the final value for the
+replacement field. For example::
>>> from fractions import Fraction
- >>> calculation = Fraction(1, 3)
- >>> f'{calculation=}'
- 'calculation=Fraction(1, 3)'
- >>> f'{calculation = }'
- 'calculation = Fraction(1, 3)'
- >>> f'{calculation = !s}'
- 'calculation = 1/3'
+ >>> one_third = Fraction(1, 3)
+ >>> f'{one_third:.6f}'
+ '0.333333'
+ >>> f'{one_third:_^+10}'
+ '___+1/3___'
+ >>> >>> f'{one_third!r:_^20}'
+ '___Fraction(1, 3)___'
+ >>> f'{one_third = :~>10}~'
+ 'one_third = ~~~~~~~1/3~'
-Once the output has been evaluated, it can be formatted using a
-:ref:`format specifier ` following a colon (``':'``).
-After the expression has been evaluated, and possibly converted to a string,
-the :meth:`!__format__` method of the result is called with the format specifier,
-or the empty string if no format specifier is given.
-The formatted result is then used as the final value for the replacement field.
-For example:
+.. _stdtypes-tstrings:
-.. doctest::
+Template String Literals (t-strings)
+------------------------------------
- >>> from fractions import Fraction
- >>> f'{Fraction(1, 7):.6f}'
- '0.142857'
- >>> f'{Fraction(1, 7):_^+10}'
- '___+1/7___'
+An :dfn:`t-string` (formally a :dfn:`template string literal`) is
+a string literal that is prefixed with ``t`` or ``T``.
+
+These strings follow the same syntax and evaluation rules as
+:ref:`formatted string literals `,
+with for the following differences:
+
+* Rather than evaluating to a ``str`` object, template string literals evaluate
+ to a :class:`string.templatelib.Template` object.
+
+* The :func:`format` protocol is not used.
+ Instead, the format specifier and conversions (if any) are passed to
+ a new :class:`~string.templatelib.Interpolation` object that is created
+ for each evaluated expression.
+ It is up to code that processes the resulting :class:`~string.templatelib.Template`
+ object to decide how to handle format specifiers and conversions.
+
+* Format specifiers containing nested replacement fields are evaluated eagerly,
+ prior to being passed to the :class:`~string.templatelib.Interpolation` object.
+ For instance, an interpolation of the form ``{amount:.{precision}f}`` will
+ evaluate the inner expression ``{precision}`` to determine the value of the
+ ``format_spec`` attribute.
+ If ``precision`` were to be ``2``, the resulting format specifier
+ would be ``'.2f'``.
+
+* When the equals sign ``'='`` is provided in an interpolation expression,
+ the text of the expression is appended to the literal string that precedes
+ the relevant interpolation.
+ This includes the equals sign and any surrounding whitespace.
+ The :class:`!Interpolation` instance for the expression will be created as
+ normal, except that :attr:`~string.templatelib.Interpolation.conversion` will
+ be set to '``r``' (:func:`repr`) by default.
+ If an explicit conversion or format specifier are provided,
+ this will override the default behaviour.
.. _old-string-formatting:
@@ -3173,6 +3244,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
+ :meth:`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
@@ -4580,7 +4675,7 @@ copying.
.. versionadded:: 3.14
- .. method:: index(value, start=0, stop=sys.maxsize, /)
+ .. method:: index(value, start=0, stop=sys.maxsize, /)
Return the index of the first occurrence of *value* (at or after
index *start* and before index *stop*).
@@ -4731,11 +4826,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:`~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.
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
@@ -4752,164 +4848,172 @@ The constructors for both classes work the same:
objects. If *iterable* is not specified, a new empty set is
returned.
- Sets can be created by several means:
+Sets can be created by several means:
- * Use a comma-separated list of elements within braces: ``{'jack', 'sjoerd'}``
- * Use a set comprehension: ``{c for c in 'abracadabra' if c not in 'abc'}``
- * Use the type constructor: ``set()``, ``set('foobar')``, ``set(['a', 'b', 'foo'])``
+* Use a comma-separated list of elements within braces: ``{'jack', 'sjoerd'}``
+* Use a set comprehension: ``{c for c in 'abracadabra' if c not in 'abc'}``
+* Use the type constructor: ``set()``, ``set('foobar')``, ``set(['a', 'b', 'foo'])``
- Instances of :class:`set` and :class:`frozenset` provide the following
- operations:
+Instances of :class:`set` and :class:`frozenset` provide the following
+operations:
- .. describe:: len(s)
+.. describe:: len(s)
- Return the number of elements in set *s* (cardinality of *s*).
+ Return the number of elements in set *s* (cardinality of *s*).
- .. describe:: x in s
+.. describe:: x in s
- Test *x* for membership in *s*.
+ Test *x* for membership in *s*.
- .. describe:: x not in s
+.. describe:: x not in s
- Test *x* for non-membership in *s*.
+ Test *x* for non-membership in *s*.
- .. method:: isdisjoint(other, /)
+.. method:: frozenset.isdisjoint(other, /)
+ set.isdisjoint(other, /)
- Return ``True`` if the set has no elements in common with *other*. Sets are
- disjoint if and only if their intersection is the empty set.
+ Return ``True`` if the set has no elements in common with *other*. Sets are
+ disjoint if and only if their intersection is the empty set.
- .. method:: issubset(other, /)
- set <= other
+.. method:: frozenset.issubset(other, /)
+ set.issubset(other, /)
+.. describe:: set <= other
- Test whether every element in the set is in *other*.
+ Test whether every element in the set is in *other*.
- .. method:: set < other
+.. describe:: set < other
- Test whether the set is a proper subset of *other*, that is,
- ``set <= other and set != other``.
+ Test whether the set is a proper subset of *other*, that is,
+ ``set <= other and set != other``.
- .. method:: issuperset(other, /)
- set >= other
+.. method:: frozenset.issuperset(other, /)
+ set.issuperset(other, /)
+.. describe:: set >= other
- Test whether every element in *other* is in the set.
+ Test whether every element in *other* is in the set.
- .. method:: set > other
+.. describe:: set > other
- Test whether the set is a proper superset of *other*, that is, ``set >=
- other and set != other``.
+ Test whether the set is a proper superset of *other*, that is, ``set >=
+ other and set != other``.
- .. method:: union(*others)
- set | other | ...
+.. method:: frozenset.union(*others)
+ set.union(*others)
+.. describe:: set | other | ...
- Return a new set with elements from the set and all others.
+ Return a new set with elements from the set and all others.
- .. method:: intersection(*others)
- set & other & ...
+.. method:: frozenset.intersection(*others)
+ set.intersection(*others)
+.. describe:: set & other & ...
- Return a new set with elements common to the set and all others.
+ Return a new set with elements common to the set and all others.
- .. method:: difference(*others)
- set - other - ...
+.. method:: frozenset.difference(*others)
+ set.difference(*others)
+.. describe:: set - other - ...
- Return a new set with elements in the set that are not in the others.
+ Return a new set with elements in the set that are not in the others.
- .. method:: symmetric_difference(other, /)
- set ^ other
+.. method:: frozenset.symmetric_difference(other, /)
+ set.symmetric_difference(other, /)
+.. describe:: set ^ other
- Return a new set with elements in either the set or *other* but not both.
+ Return a new set with elements in either the set or *other* but not both.
- .. method:: copy()
+.. method:: frozenset.copy()
+ set.copy()
- Return a shallow copy of the set.
+ Return a shallow copy of the set.
- Note, the non-operator versions of :meth:`union`, :meth:`intersection`,
- :meth:`difference`, :meth:`symmetric_difference`, :meth:`issubset`, and
- :meth:`issuperset` methods will accept any iterable as an argument. In
- contrast, their operator based counterparts require their arguments to be
- sets. This precludes error-prone constructions like ``set('abc') & 'cbs'``
- in favor of the more readable ``set('abc').intersection('cbs')``.
+Note, the non-operator versions of :meth:`~frozenset.union`,
+:meth:`~frozenset.intersection`, :meth:`~frozenset.difference`, :meth:`~frozenset.symmetric_difference`, :meth:`~frozenset.issubset`, and
+:meth:`~frozenset.issuperset` methods will accept any iterable as an argument. In
+contrast, their operator based counterparts require their arguments to be
+sets. This precludes error-prone constructions like ``set('abc') & 'cbs'``
+in favor of the more readable ``set('abc').intersection('cbs')``.
- Both :class:`set` and :class:`frozenset` support set to set comparisons. Two
- sets are equal if and only if every element of each set is contained in the
- other (each is a subset of the other). A set is less than another set if and
- only if the first set is a proper subset of the second set (is a subset, but
- is not equal). A set is greater than another set if and only if the first set
- is a proper superset of the second set (is a superset, but is not equal).
+Both :class:`set` and :class:`frozenset` support set to set comparisons. Two
+sets are equal if and only if every element of each set is contained in the
+other (each is a subset of the other). A set is less than another set if and
+only if the first set is a proper subset of the second set (is a subset, but
+is not equal). A set is greater than another set if and only if the first set
+is a proper superset of the second set (is a superset, but is not equal).
- Instances of :class:`set` are compared to instances of :class:`frozenset`
- based on their members. For example, ``set('abc') == frozenset('abc')``
- returns ``True`` and so does ``set('abc') in set([frozenset('abc')])``.
+Instances of :class:`set` are compared to instances of :class:`frozenset`
+based on their members. For example, ``set('abc') == frozenset('abc')``
+returns ``True`` and so does ``set('abc') in set([frozenset('abc')])``.
- The subset and equality comparisons do not generalize to a total ordering
- function. For example, any two nonempty disjoint sets are not equal and are not
- subsets of each other, so *all* of the following return ``False``: ``ab``.
+The subset and equality comparisons do not generalize to a total ordering
+function. For example, any two nonempty disjoint sets are not equal and are not
+subsets of each other, so *all* of the following return ``False``: ``ab``.
- Since sets only define partial ordering (subset relationships), the output of
- the :meth:`list.sort` method is undefined for lists of sets.
+Since sets only define partial ordering (subset relationships), the output of
+the :meth:`list.sort` method is undefined for lists of sets.
- Set elements, like dictionary keys, must be :term:`hashable`.
+Set elements, like dictionary keys, must be :term:`hashable`.
- Binary operations that mix :class:`set` instances with :class:`frozenset`
- return the type of the first operand. For example: ``frozenset('ab') |
- set('bc')`` returns an instance of :class:`frozenset`.
+Binary operations that mix :class:`set` instances with :class:`frozenset`
+return the type of the first operand. For example: ``frozenset('ab') |
+set('bc')`` returns an instance of :class:`frozenset`.
- The following table lists operations available for :class:`set` that do not
- apply to immutable instances of :class:`frozenset`:
+The following table lists operations available for :class:`set` that do not
+apply to immutable instances of :class:`frozenset`:
- .. method:: update(*others)
- set |= other | ...
+.. method:: set.update(*others)
+.. describe:: set |= other | ...
- Update the set, adding elements from all others.
+ Update the set, adding elements from all others.
- .. method:: intersection_update(*others)
- set &= other & ...
+.. method:: set.intersection_update(*others)
+.. describe:: set &= other & ...
- Update the set, keeping only elements found in it and all others.
+ Update the set, keeping only elements found in it and all others.
- .. method:: difference_update(*others)
- set -= other | ...
+.. method:: set.difference_update(*others)
+.. describe:: set -= other | ...
- Update the set, removing elements found in others.
+ Update the set, removing elements found in others.
- .. method:: symmetric_difference_update(other, /)
- set ^= other
+.. method:: set.symmetric_difference_update(other, /)
+.. describe:: set ^= other
- Update the set, keeping only elements found in either set, but not in both.
+ Update the set, keeping only elements found in either set, but not in both.
- .. method:: add(elem, /)
+.. method:: set.add(elem, /)
- Add element *elem* to the set.
+ Add element *elem* to the set.
- .. method:: remove(elem, /)
+.. method:: set.remove(elem, /)
- Remove element *elem* from the set. Raises :exc:`KeyError` if *elem* is
- not contained in the set.
+ Remove element *elem* from the set. Raises :exc:`KeyError` if *elem* is
+ not contained in the set.
- .. method:: discard(elem, /)
+.. method:: set.discard(elem, /)
- Remove element *elem* from the set if it is present.
+ Remove element *elem* from the set if it is present.
- .. method:: pop()
+.. method:: set.pop()
- Remove and return an arbitrary element from the set. Raises
- :exc:`KeyError` if the set is empty.
+ Remove and return an arbitrary element from the set. Raises
+ :exc:`KeyError` if the set is empty.
- .. method:: clear()
+.. method:: set.clear()
- Remove all elements from the set.
+ Remove all elements from the set.
- Note, the non-operator versions of the :meth:`update`,
- :meth:`intersection_update`, :meth:`difference_update`, and
- :meth:`symmetric_difference_update` methods will accept any iterable as an
- argument.
+Note, the non-operator versions of the :meth:`~set.update`,
+:meth:`~set.intersection_update`, :meth:`~set.difference_update`, and
+:meth:`~set.symmetric_difference_update` methods will accept any iterable as an
+argument.
- Note, the *elem* argument to the :meth:`~object.__contains__`,
- :meth:`remove`, and
- :meth:`discard` methods may be a set. To support searching for an equivalent
- frozenset, a temporary one is created from *elem*.
+Note, the *elem* argument to the :meth:`~object.__contains__`,
+:meth:`~set.remove`, and
+:meth:`~set.discard` methods may be a set. To support searching for an equivalent
+frozenset, a temporary one is created from *elem*.
.. _typesmapping:
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/subprocess.rst b/Doc/library/subprocess.rst
index 1aade881745..b8dfcc31077 100644
--- a/Doc/library/subprocess.rst
+++ b/Doc/library/subprocess.rst
@@ -831,7 +831,9 @@ Instances of the :class:`Popen` class have the following methods:
If the process does not terminate after *timeout* seconds, a
:exc:`TimeoutExpired` exception will be raised. Catching this exception and
- retrying communication will not lose any output.
+ retrying communication will not lose any output. Supplying *input* to a
+ subsequent post-timeout :meth:`communicate` call is in undefined behavior
+ and may become an error in the future.
The child process is not killed if the timeout expires, so in order to
cleanup properly a well-behaved application should kill the child process and
@@ -844,6 +846,11 @@ Instances of the :class:`Popen` class have the following methods:
proc.kill()
outs, errs = proc.communicate()
+ After a call to :meth:`~Popen.communicate` raises :exc:`TimeoutExpired`, do
+ not call :meth:`~Popen.wait`. Use an additional :meth:`~Popen.communicate`
+ call to finish handling pipes and populate the :attr:`~Popen.returncode`
+ attribute.
+
.. note::
The data read is buffered in memory, so do not use this method if the data
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 843b8129c73..f8e99bc7d24 100644
--- a/Doc/library/sys.rst
+++ b/Doc/library/sys.rst
@@ -1213,10 +1213,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 df8fb83a018..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
@@ -816,6 +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:: next
+.. 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.handler.rst b/Doc/library/xml.sax.handler.rst
index 38ca4507d81..f1af7253e43 100644
--- a/Doc/library/xml.sax.handler.rst
+++ b/Doc/library/xml.sax.handler.rst
@@ -96,6 +96,14 @@ for the feature and property names.
.. data:: feature_external_ges
+ .. warning::
+
+ Enabling opens a vulnerability to
+ `external entity attacks `_
+ if the parser is used with user-provided XML content.
+ Please reflect on your `threat model `_
+ before enabling this feature.
+
| value: ``"http://xml.org/sax/features/external-general-entities"``
| true: Include all external general (text) entities.
| false: Do not include external general entities.
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..7e511237a6a 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:
@@ -472,7 +472,7 @@ remote server into a single request [#]_.
Create an object used to boxcar method calls. *server* is the eventual target of
the call. Calls can be made to the result object, but they will immediately
- return ``None``, and only store the call name and parameters in the
+ return ``None``, and only store the call name and arguments in the
:class:`MultiCall` object. Calling the object itself causes all stored calls to
be transmitted as a single ``system.multicall`` request. The result of this call
is a :term:`generator`; iterating over this generator yields the individual
diff --git a/Doc/library/zipfile.rst b/Doc/library/zipfile.rst
index f6ec33640b6..ae4e25b13b9 100644
--- a/Doc/library/zipfile.rst
+++ b/Doc/library/zipfile.rst
@@ -16,13 +16,23 @@ provides tools to create, read, write, append, and list a ZIP file. Any
advanced use of this module will require an understanding of the format, as
defined in `PKZIP Application Note`_.
-This module does not currently handle multi-disk ZIP files.
+This module does not handle multipart ZIP files.
It can handle ZIP files that use the ZIP64 extensions
(that is ZIP files that are more than 4 GiB in size). It supports
-decryption of encrypted files in ZIP archives, but it currently cannot
+decryption of encrypted files in ZIP archives, but it 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
@@ -165,7 +175,7 @@ The module defines the following items:
.. _zipfile-objects:
-ZipFile Objects
+ZipFile objects
---------------
@@ -238,7 +248,7 @@ ZipFile Objects
.. note::
*metadata_encoding* is an instance-wide setting for the ZipFile.
- It is not currently possible to set this on a per-member basis.
+ It is not possible to set this on a per-member basis.
This attribute is a workaround for legacy implementations which produce
archives with names in the current locale encoding or code page (mostly
@@ -561,7 +571,7 @@ The following data attributes are also available:
.. _path-objects:
-Path Objects
+Path objects
------------
.. class:: Path(root, at='')
@@ -697,7 +707,7 @@ changes.
.. _pyzipfile-objects:
-PyZipFile Objects
+PyZipFile objects
-----------------
The :class:`PyZipFile` constructor takes the same parameters as the
@@ -774,7 +784,7 @@ The :class:`PyZipFile` constructor takes the same parameters as the
.. _zipinfo-objects:
-ZipInfo Objects
+ZipInfo objects
---------------
Instances of the :class:`ZipInfo` class are returned by the :meth:`.getinfo` and
@@ -944,7 +954,7 @@ Instances have the following methods and attributes:
.. _zipfile-commandline:
.. program:: zipfile
-Command-Line Interface
+Command-line interface
----------------------
The :mod:`zipfile` module provides a simple command-line interface to interact
@@ -1019,7 +1029,7 @@ From file itself
Decompression may fail due to incorrect password / CRC checksum / ZIP format or
unsupported compression method / decryption.
-File System limitations
+File system limitations
~~~~~~~~~~~~~~~~~~~~~~~
Exceeding limitations on different file systems can cause decompression failed.
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..5f79c6fe8f5 100644
--- a/Doc/reference/datamodel.rst
+++ b/Doc/reference/datamodel.rst
@@ -449,7 +449,7 @@ Sets
These represent a mutable set. They are created by the built-in :func:`set`
constructor and can be modified afterwards by several methods, such as
- :meth:`add `.
+ :meth:`~set.add`.
Frozen sets
@@ -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/reference/expressions.rst b/Doc/reference/expressions.rst
index c655d6c52ec..165dfa69f88 100644
--- a/Doc/reference/expressions.rst
+++ b/Doc/reference/expressions.rst
@@ -174,7 +174,7 @@ Formally:
.. grammar-snippet::
:group: python-grammar
- strings: ( `STRING` | fstring)+ | tstring+
+ strings: ( `STRING` | `fstring`)+ | `tstring`+
This feature is defined at the syntactical level, so it only works with literals.
To concatenate string expressions at run time, the '+' operator may be used::
diff --git a/Doc/reference/lexical_analysis.rst b/Doc/reference/lexical_analysis.rst
index ea386706e8b..9322d8571f7 100644
--- a/Doc/reference/lexical_analysis.rst
+++ b/Doc/reference/lexical_analysis.rst
@@ -345,7 +345,15 @@ Whitespace between tokens
Except at the beginning of a logical line or in string literals, the whitespace
characters space, tab and formfeed can be used interchangeably to separate
-tokens. Whitespace is needed between two tokens only if their concatenation
+tokens:
+
+.. grammar-snippet::
+ :group: python-grammar
+
+ whitespace: ' ' | tab | formfeed
+
+
+Whitespace is needed between two tokens only if their concatenation
could otherwise be interpreted as a different token. For example, ``ab`` is one
token, but ``a b`` is two tokens. However, ``+a`` and ``+ a`` both produce
two tokens, ``+`` and ``a``, as ``+a`` is not a valid token.
@@ -386,73 +394,29 @@ Names (identifiers and keywords)
:data:`~token.NAME` tokens represent *identifiers*, *keywords*, and
*soft keywords*.
-Within the ASCII range (U+0001..U+007F), the valid characters for names
-include the uppercase and lowercase letters (``A-Z`` and ``a-z``),
-the underscore ``_`` and, except for the first character, the digits
-``0`` through ``9``.
+Names are composed of the following characters:
+
+* uppercase and lowercase letters (``A-Z`` and ``a-z``),
+* the underscore (``_``),
+* digits (``0`` through ``9``), which cannot appear as the first character, and
+* non-ASCII characters. Valid names may only contain "letter-like" and
+ "digit-like" characters; see :ref:`lexical-names-nonascii` for details.
Names must contain at least one character, but have no upper length limit.
Case is significant.
-Besides ``A-Z``, ``a-z``, ``_`` and ``0-9``, names can also use "letter-like"
-and "number-like" characters from outside the ASCII range, as detailed below.
-
-All identifiers are converted into the `normalization form`_ NFKC while
-parsing; comparison of identifiers is based on NFKC.
-
-Formally, the first character of a normalized identifier must belong to the
-set ``id_start``, which is the union of:
-
-* Unicode category ```` - uppercase letters (includes ``A`` to ``Z``)
-* Unicode category ```` - lowercase letters (includes ``a`` to ``z``)
-* Unicode category ```` - titlecase letters
-* Unicode category ```` - modifier letters
-* Unicode category ```` - other letters
-* Unicode category ```` - letter numbers
-* {``"_"``} - the underscore
-* ```` - an explicit set of characters in `PropList.txt`_
- to support backwards compatibility
-
-The remaining characters must belong to the set ``id_continue``, which is the
-union of:
-
-* all characters in ``id_start``
-* Unicode category ```` - decimal numbers (includes ``0`` to ``9``)
-* Unicode category ```` - connector punctuations
-* Unicode category ```` - nonspacing marks
-* Unicode category ```` - spacing combining marks
-* ```` - another explicit set of characters in
- `PropList.txt`_ to support backwards compatibility
-
-Unicode categories use the version of the Unicode Character Database as
-included in the :mod:`unicodedata` module.
-
-These sets are based on the Unicode standard annex `UAX-31`_.
-See also :pep:`3131` for further details.
-
-Even more formally, names are described by the following lexical definitions:
+Formally, names are described by the following lexical definitions:
.. grammar-snippet::
:group: python-grammar
- NAME: `xid_start` `xid_continue`*
- id_start: | | | | | | "_" |
- id_continue: `id_start` | | | | |
- xid_start:
- xid_continue:
- identifier: <`NAME`, except keywords>
+ NAME: `name_start` `name_continue`*
+ name_start: "a"..."z" | "A"..."Z" | "_" |
+ name_continue: name_start | "0"..."9"
+ identifier: <`NAME`, except keywords>
-A non-normative listing of all valid identifier characters as defined by
-Unicode is available in the `DerivedCoreProperties.txt`_ file in the Unicode
-Character Database.
-
-
-.. _UAX-31: https://www.unicode.org/reports/tr31/
-.. _PropList.txt: https://www.unicode.org/Public/17.0.0/ucd/PropList.txt
-.. _DerivedCoreProperties.txt: https://www.unicode.org/Public/17.0.0/ucd/DerivedCoreProperties.txt
-.. _normalization form: https://www.unicode.org/reports/tr15/#Norm_Forms
+Note that not all names matched by this grammar are valid; see
+:ref:`lexical-names-nonascii` for details.
.. _keywords:
@@ -555,6 +519,95 @@ characters:
:ref:`atom-identifiers`.
+.. _lexical-names-nonascii:
+
+Non-ASCII characters in names
+-----------------------------
+
+Names that contain non-ASCII characters need additional normalization
+and validation beyond the rules and grammar explained
+:ref:`above `.
+For example, ``ř_1``, ``蛇``, or ``साँप`` are valid names, but ``r〰2``,
+``€``, or ``🐍`` are not.
+
+This section explains the exact rules.
+
+All names are converted into the `normalization form`_ NFKC while parsing.
+This means that, for example, some typographic variants of characters are
+converted to their "basic" form. For example, ``fiⁿₐˡᵢᶻₐᵗᵢᵒₙ`` normalizes to
+``finalization``, so Python treats them as the same name::
+
+ >>> fiⁿₐˡᵢᶻₐᵗᵢᵒₙ = 3
+ >>> finalization
+ 3
+
+.. note::
+
+ Normalization is done at the lexical level only.
+ Run-time functions that take names as *strings* generally do not normalize
+ their arguments.
+ For example, the variable defined above is accessible at run time in the
+ :func:`globals` dictionary as ``globals()["finalization"]`` but not
+ ``globals()["fiⁿₐˡᵢᶻₐᵗᵢᵒₙ"]``.
+
+Similarly to how ASCII-only names must contain only letters, digits and
+the underscore, and cannot start with a digit, a valid name must
+start with a character in the "letter-like" set ``xid_start``,
+and the remaining characters must be in the "letter- and digit-like" set
+``xid_continue``.
+
+These sets based on the *XID_Start* and *XID_Continue* sets as defined by the
+Unicode standard annex `UAX-31`_.
+Python's ``xid_start`` additionally includes the underscore (``_``).
+Note that Python does not necessarily conform to `UAX-31`_.
+
+A non-normative listing of characters in the *XID_Start* and *XID_Continue*
+sets as defined by Unicode is available in the `DerivedCoreProperties.txt`_
+file in the Unicode Character Database.
+For reference, the construction rules for the ``xid_*`` sets are given below.
+
+The set ``id_start`` is defined as the union of:
+
+* Unicode category ```` - uppercase letters (includes ``A`` to ``Z``)
+* Unicode category ```` - lowercase letters (includes ``a`` to ``z``)
+* Unicode category ```` - titlecase letters
+* Unicode category ```` - modifier letters
+* Unicode category ```` - other letters
+* Unicode category ```` - letter numbers
+* {``"_"``} - the underscore
+* ```` - an explicit set of characters in `PropList.txt`_
+ to support backwards compatibility
+
+The set ``xid_start`` then closes this set under NFKC normalization, by
+removing all characters whose normalization is not of the form
+``id_start id_continue*``.
+
+The set ``id_continue`` is defined as the union of:
+
+* ``id_start`` (see above)
+* Unicode category ```` - decimal numbers (includes ``0`` to ``9``)
+* Unicode category ```` - connector punctuations
+* Unicode category ```` - nonspacing marks
+* Unicode category ```` - spacing combining marks
+* ```` - another explicit set of characters in
+ `PropList.txt`_ to support backwards compatibility
+
+Again, ``xid_continue`` closes this set under NFKC normalization.
+
+Unicode categories use the version of the Unicode Character Database as
+included in the :mod:`unicodedata` module.
+
+.. _UAX-31: https://www.unicode.org/reports/tr31/
+.. _PropList.txt: https://www.unicode.org/Public/17.0.0/ucd/PropList.txt
+.. _DerivedCoreProperties.txt: https://www.unicode.org/Public/17.0.0/ucd/DerivedCoreProperties.txt
+.. _normalization form: https://www.unicode.org/reports/tr15/#Norm_Forms
+
+.. seealso::
+
+ * :pep:`3131` -- Supporting Non-ASCII Identifiers
+ * :pep:`672` -- Unicode-related Security Considerations for Python
+
+
.. _literals:
Literals
@@ -987,124 +1040,59 @@ f-strings
---------
.. versionadded:: 3.6
+.. versionchanged:: 3.7
+ The :keyword:`await` and :keyword:`async for` can be used in expressions
+ within f-strings.
+.. versionchanged:: 3.8
+ Added the debug specifier (``=``)
+.. versionchanged:: 3.12
+ Many restrictions on expressions within f-strings have been removed.
+ Notably, nested strings, comments, and backslashes are now permitted.
A :dfn:`formatted string literal` or :dfn:`f-string` is a string literal
-that is prefixed with '``f``' or '``F``'. These strings may contain
-replacement fields, which are expressions delimited by curly braces ``{}``.
-While other string literals always have a constant value, formatted strings
-are really expressions evaluated at run time.
+that is prefixed with '``f``' or '``F``'.
+Unlike other string literals, f-strings do not have a constant value.
+They may contain *replacement fields* delimited by curly braces ``{}``.
+Replacement fields contain expressions which are evaluated at run time.
+For example::
-Escape sequences are decoded like in ordinary string literals (except when
-a literal is also marked as a raw string). After decoding, the grammar
-for the contents of the string is:
+ >>> who = 'nobody'
+ >>> nationality = 'Spanish'
+ >>> f'{who.title()} expects the {nationality} Inquisition!'
+ 'Nobody expects the Spanish Inquisition!'
-.. productionlist:: python-grammar
- f_string: (`literal_char` | "{{" | "}}" | `replacement_field`)*
- replacement_field: "{" `f_expression` ["="] ["!" `conversion`] [":" `format_spec`] "}"
- f_expression: (`conditional_expression` | "*" `or_expr`)
- : ("," `conditional_expression` | "," "*" `or_expr`)* [","]
- : | `yield_expression`
- conversion: "s" | "r" | "a"
- format_spec: (`literal_char` | `replacement_field`)*
- literal_char:
+Any doubled curly braces (``{{`` or ``}}``) outside replacement fields
+are replaced with the corresponding single curly brace::
-The parts of the string outside curly braces are treated literally,
-except that any doubled curly braces ``'{{'`` or ``'}}'`` are replaced
-with the corresponding single curly brace. A single opening curly
-bracket ``'{'`` marks a replacement field, which starts with a
-Python expression. To display both the expression text and its value after
-evaluation, (useful in debugging), an equal sign ``'='`` may be added after the
-expression. A conversion field, introduced by an exclamation point ``'!'`` may
-follow. A format specifier may also be appended, introduced by a colon ``':'``.
-A replacement field ends with a closing curly bracket ``'}'``.
+ >>> print(f'{{...}}')
+ {...}
+
+Other characters outside replacement fields are treated like in ordinary
+string literals.
+This means that escape sequences are decoded (except when a literal is
+also marked as a raw string), and newlines are possible in triple-quoted
+f-strings::
+
+ >>> name = 'Galahad'
+ >>> favorite_color = 'blue'
+ >>> print(f'{name}:\t{favorite_color}')
+ Galahad: blue
+ >>> print(rf"C:\Users\{name}")
+ C:\Users\Galahad
+ >>> print(f'''Three shall be the number of the counting
+ ... and the number of the counting shall be three.''')
+ Three shall be the number of the counting
+ and the number of the counting shall be three.
Expressions in formatted string literals are treated like regular
-Python expressions surrounded by parentheses, with a few exceptions.
-An empty expression is not allowed, and both :keyword:`lambda` and
-assignment expressions ``:=`` must be surrounded by explicit parentheses.
+Python expressions.
Each expression is evaluated in the context where the formatted string literal
-appears, in order from left to right. Replacement expressions can contain
-newlines in both single-quoted and triple-quoted f-strings and they can contain
-comments. Everything that comes after a ``#`` inside a replacement field
-is a comment (even closing braces and quotes). In that case, replacement fields
-must be closed in a different line.
-
-.. code-block:: text
-
- >>> f"abc{a # This is a comment }"
- ... + 3}"
- 'abc5'
-
-.. versionchanged:: 3.7
- Prior to Python 3.7, an :keyword:`await` expression and comprehensions
- containing an :keyword:`async for` clause were illegal in the expressions
- in formatted string literals due to a problem with the implementation.
-
-.. versionchanged:: 3.12
- Prior to Python 3.12, comments were not allowed inside f-string replacement
- fields.
-
-When the equal sign ``'='`` is provided, the output will have the expression
-text, the ``'='`` and the evaluated value. Spaces after the opening brace
-``'{'``, within the expression and after the ``'='`` are all retained in the
-output. By default, the ``'='`` causes the :func:`repr` of the expression to be
-provided, unless there is a format specified. When a format is specified it
-defaults to the :func:`str` of the expression unless a conversion ``'!r'`` is
-declared.
-
-.. versionadded:: 3.8
- The equal sign ``'='``.
-
-If a conversion is specified, the result of evaluating the expression
-is converted before formatting. Conversion ``'!s'`` calls :func:`str` on
-the result, ``'!r'`` calls :func:`repr`, and ``'!a'`` calls :func:`ascii`.
-
-The result is then formatted using the :func:`format` protocol. The
-format specifier is passed to the :meth:`~object.__format__` method of the
-expression or conversion result. An empty string is passed when the
-format specifier is omitted. The formatted result is then included in
-the final value of the whole string.
-
-Top-level format specifiers may include nested replacement fields. These nested
-fields may include their own conversion fields and :ref:`format specifiers
-`, but may not include more deeply nested replacement fields. The
-:ref:`format specifier mini-language ` is the same as that used by
-the :meth:`str.format` method.
-
-Formatted string literals may be concatenated, but replacement fields
-cannot be split across literals.
-
-Some examples of formatted string literals::
-
- >>> name = "Fred"
- >>> f"He said his name is {name!r}."
- "He said his name is 'Fred'."
- >>> f"He said his name is {repr(name)}." # repr() is equivalent to !r
- "He said his name is 'Fred'."
- >>> width = 10
- >>> precision = 4
- >>> value = decimal.Decimal("12.34567")
- >>> f"result: {value:{width}.{precision}}" # nested fields
- 'result: 12.35'
- >>> today = datetime(year=2017, month=1, day=27)
- >>> f"{today:%B %d, %Y}" # using date format specifier
- 'January 27, 2017'
- >>> f"{today=:%B %d, %Y}" # using date format specifier and debugging
- 'today=January 27, 2017'
- >>> number = 1024
- >>> f"{number:#0x}" # using integer format specifier
- '0x400'
- >>> foo = "bar"
- >>> f"{ foo = }" # preserves whitespace
- " foo = 'bar'"
- >>> line = "The mill's closed"
- >>> f"{line = }"
- 'line = "The mill\'s closed"'
- >>> f"{line = :20}"
- "line = The mill's closed "
- >>> f"{line = !r:20}"
- 'line = "The mill\'s closed" '
+appears, in order from left to right.
+An empty expression is not allowed, and both :keyword:`lambda` and
+assignment expressions ``:=`` must be surrounded by explicit parentheses::
+ >>> f'{(half := 1/2)}, {half * 42}'
+ '0.5, 21.0'
Reusing the outer f-string quoting type inside a replacement field is
permitted::
@@ -1113,10 +1101,6 @@ permitted::
>>> f"abc {a["x"]} def"
'abc 2 def'
-.. versionchanged:: 3.12
- Prior to Python 3.12, reuse of the same quoting type of the outer f-string
- inside a replacement field was not possible.
-
Backslashes are also allowed in replacement fields and are evaluated the same
way as in any other context::
@@ -1127,23 +1111,84 @@ way as in any other context::
b
c
-.. versionchanged:: 3.12
- Prior to Python 3.12, backslashes were not permitted inside an f-string
- replacement field.
+It is possible to nest f-strings::
-Formatted string literals cannot be used as docstrings, even if they do not
-include expressions.
+ >>> name = 'world'
+ >>> f'Repeated:{f' hello {name}' * 3}'
+ 'Repeated: hello world hello world hello world'
-::
+Portable Python programs should not use more than 5 levels of nesting.
+
+.. impl-detail::
+
+ CPython does not limit nesting of f-strings.
+
+Replacement expressions can contain newlines in both single-quoted and
+triple-quoted f-strings and they can contain comments.
+Everything that comes after a ``#`` inside a replacement field
+is a comment (even closing braces and quotes).
+This means that replacement fields with comments must be closed in a
+different line:
+
+.. code-block:: text
+
+ >>> a = 2
+ >>> f"abc{a # This comment }" continues until the end of the line
+ ... + 3}"
+ 'abc5'
+
+After the expression, replacement fields may optionally contain:
+
+* a *debug specifier* -- an equal sign (``=``), optionally surrounded by
+ whitespace on one or both sides;
+* a *conversion specifier* -- ``!s``, ``!r`` or ``!a``; and/or
+* a *format specifier* prefixed with a colon (``:``).
+
+See the :ref:`Standard Library section on f-strings `
+for details on how these fields are evaluated.
+
+As that section explains, *format specifiers* are passed as the second argument
+to the :func:`format` function to format a replacement field value.
+For example, they can be used to specify a field width and padding characters
+using the :ref:`Format Specification Mini-Language `::
+
+ >>> number = 14.3
+ >>> f'{number:20.7f}'
+ ' 14.3000000'
+
+Top-level format specifiers may include nested replacement fields::
+
+ >>> field_size = 20
+ >>> precision = 7
+ >>> f'{number:{field_size}.{precision}f}'
+ ' 14.3000000'
+
+These nested fields may include their own conversion fields and
+:ref:`format specifiers `::
+
+ >>> number = 3
+ >>> f'{number:{field_size}}'
+ ' 3'
+ >>> f'{number:{field_size:05}}'
+ '00000000000000000003'
+
+However, these nested fields may not include more deeply nested replacement
+fields.
+
+Formatted string literals cannot be used as :term:`docstrings `,
+even if they do not include expressions::
>>> def foo():
... f"Not a docstring"
...
- >>> foo.__doc__ is None
- True
+ >>> print(foo.__doc__)
+ None
-See also :pep:`498` for the proposal that added formatted string literals,
-and :meth:`str.format`, which uses a related format string mechanism.
+.. seealso::
+
+ * :pep:`498` -- Literal String Interpolation
+ * :pep:`701` -- Syntactic formalization of f-strings
+ * :meth:`str.format`, which uses a related format string mechanism.
.. _t-strings:
@@ -1156,36 +1201,99 @@ t-strings
A :dfn:`template string literal` or :dfn:`t-string` is a string literal
that is prefixed with '``t``' or '``T``'.
-These strings follow the same syntax and evaluation rules as
-:ref:`formatted string literals `, with the following differences:
+These strings follow the same syntax rules as
+:ref:`formatted string literals `.
+For differences in evaluation rules, see the
+:ref:`Standard Library section on t-strings `
-* Rather than evaluating to a ``str`` object, template string literals evaluate
- to a :class:`string.templatelib.Template` object.
-* The :func:`format` protocol is not used.
- Instead, the format specifier and conversions (if any) are passed to
- a new :class:`~string.templatelib.Interpolation` object that is created
- for each evaluated expression.
- It is up to code that processes the resulting :class:`~string.templatelib.Template`
- object to decide how to handle format specifiers and conversions.
+Formal grammar for f-strings
+----------------------------
-* Format specifiers containing nested replacement fields are evaluated eagerly,
- prior to being passed to the :class:`~string.templatelib.Interpolation` object.
- For instance, an interpolation of the form ``{amount:.{precision}f}`` will
- evaluate the inner expression ``{precision}`` to determine the value of the
- ``format_spec`` attribute.
- If ``precision`` were to be ``2``, the resulting format specifier
- would be ``'.2f'``.
+F-strings are handled partly by the :term:`lexical analyzer`, which produces the
+tokens :py:data:`~token.FSTRING_START`, :py:data:`~token.FSTRING_MIDDLE`
+and :py:data:`~token.FSTRING_END`, and partly by the parser, which handles
+expressions in the replacement field.
+The exact way the work is split is a CPython implementation detail.
-* When the equals sign ``'='`` is provided in an interpolation expression,
- the text of the expression is appended to the literal string that precedes
- the relevant interpolation.
- This includes the equals sign and any surrounding whitespace.
- The :class:`!Interpolation` instance for the expression will be created as
- normal, except that :attr:`~string.templatelib.Interpolation.conversion` will
- be set to '``r``' (:func:`repr`) by default.
- If an explicit conversion or format specifier are provided,
- this will override the default behaviour.
+Correspondingly, the f-string grammar is a mix of
+:ref:`lexical and syntactic definitions `.
+
+Whitespace is significant in these situations:
+
+* There may be no whitespace in :py:data:`~token.FSTRING_START` (between
+ the prefix and quote).
+* Whitespace in :py:data:`~token.FSTRING_MIDDLE` is part of the literal
+ string contents.
+* In ``fstring_replacement_field``, if ``f_debug_specifier`` is present,
+ all whitespace after the opening brace until the ``f_debug_specifier``,
+ as well as whitespace immediatelly following ``f_debug_specifier``,
+ is retained as part of the expression.
+
+ .. impl-detail::
+
+ The expression is not handled in the tokenization phase; it is
+ retrieved from the source code using locations of the ``{`` token
+ and the token after ``=``.
+
+
+The ``FSTRING_MIDDLE`` definition uses
+:ref:`negative lookaheads ` (``!``)
+to indicate special characters (backslash, newline, ``{``, ``}``) and
+sequences (``f_quote``).
+
+.. grammar-snippet::
+ :group: python-grammar
+
+ fstring: `FSTRING_START` `fstring_middle`* `FSTRING_END`
+
+ FSTRING_START: `fstringprefix` ("'" | '"' | "'''" | '"""')
+ FSTRING_END: `f_quote`
+ fstringprefix: <("f" | "fr" | "rf"), case-insensitive>
+ f_debug_specifier: '='
+ f_quote:
+
+ fstring_middle:
+ | `fstring_replacement_field`
+ | `FSTRING_MIDDLE`
+ FSTRING_MIDDLE:
+ | (!"\" !`newline` !'{' !'}' !`f_quote`) `source_character`
+ | `stringescapeseq`
+ | "{{"
+ | "}}"
+ |
+ fstring_replacement_field:
+ | '{' `f_expression` [`f_debug_specifier`] [`fstring_conversion`]
+ [`fstring_full_format_spec`] '}'
+ fstring_conversion:
+ | "!" ("s" | "r" | "a")
+ fstring_full_format_spec:
+ | ':' `fstring_format_spec`*
+ fstring_format_spec:
+ | `FSTRING_MIDDLE`
+ | `fstring_replacement_field`
+ f_expression:
+ | ','.(`conditional_expression` | "*" `or_expr`)+ [","]
+ | `yield_expression`
+
+.. note::
+
+ In the above grammar snippet, the ``f_quote`` and ``FSTRING_MIDDLE`` rules
+ are context-sensitive -- they depend on the contents of ``FSTRING_START``
+ of the nearest enclosing ``fstring``.
+
+ Constructing a more traditional formal grammar from this template is left
+ as an exercise for the reader.
+
+The grammar for t-strings is identical to the one for f-strings, with *t*
+instead of *f* at the beginning of rule and token names and in the prefix.
+
+.. grammar-snippet::
+ :group: python-grammar
+
+ tstring: TSTRING_START tstring_middle* TSTRING_END
+
+
.. _numbers:
diff --git a/Doc/requirements.txt b/Doc/requirements.txt
index d5f7b473c3a..716772b7f28 100644
--- a/Doc/requirements.txt
+++ b/Doc/requirements.txt
@@ -7,7 +7,7 @@
# won't suddenly cause build failures. Updating the version is fine as long
# as no warnings are raised by doing so.
# Keep this version in sync with ``Doc/conf.py``.
-sphinx~=8.2.0
+sphinx~=9.0.0
blurb
diff --git a/Doc/tools/.nitignore b/Doc/tools/.nitignore
index 6fee1c192c3..c41c70f0ed3 100644
--- a/Doc/tools/.nitignore
+++ b/Doc/tools/.nitignore
@@ -6,9 +6,7 @@ Doc/c-api/descriptor.rst
Doc/c-api/float.rst
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 +28,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/extensions/glossary_search.py b/Doc/tools/extensions/glossary_search.py
index 502b6cd95bc..bcda4b7b435 100644
--- a/Doc/tools/extensions/glossary_search.py
+++ b/Doc/tools/extensions/glossary_search.py
@@ -38,7 +38,7 @@ def process_glossary_nodes(
rendered = app.builder.render_partial(definition)
terms[term.lower()] = {
'title': term,
- 'body': rendered['html_body'],
+ 'body': rendered['fragment'],
}
diff --git a/Doc/tools/extensions/pyspecific.py b/Doc/tools/extensions/pyspecific.py
index f5451adb37b..f9bf273e762 100644
--- a/Doc/tools/extensions/pyspecific.py
+++ b/Doc/tools/extensions/pyspecific.py
@@ -24,14 +24,6 @@
# Used in conf.py and updated here by python/release-tools/run_release.py
SOURCE_URI = 'https://github.com/python/cpython/tree/main/%s'
-# monkey-patch reST parser to disable alphabetic and roman enumerated lists
-from docutils.parsers.rst.states import Body
-Body.enum.converters['loweralpha'] = \
- Body.enum.converters['upperalpha'] = \
- Body.enum.converters['lowerroman'] = \
- Body.enum.converters['upperroman'] = lambda x: None
-
-
class PyAwaitableMixin(object):
def handle_signature(self, sig, signode):
ret = super(PyAwaitableMixin, self).handle_signature(sig, signode)
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/introduction.rst b/Doc/tutorial/introduction.rst
index fb491149793..deabac52530 100644
--- a/Doc/tutorial/introduction.rst
+++ b/Doc/tutorial/introduction.rst
@@ -49,7 +49,7 @@ primary prompt, ``>>>``. (It shouldn't take long.)
Numbers
-------
-The interpreter acts as a simple calculator: you can type an expression at it
+The interpreter acts as a simple calculator: you can type an expression into it
and it will write the value. Expression syntax is straightforward: the
operators ``+``, ``-``, ``*`` and ``/`` can be used to perform
arithmetic; parentheses (``()``) can be used for grouping.
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..dff0fe036ea 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:
@@ -255,6 +322,30 @@ General Options
.. versionadded:: 3.11
+.. option:: --with-missing-stdlib-config=FILE
+
+ Path to a `JSON `_ configuration file
+ containing custom error messages for missing :term:`standard library` modules.
+
+ This option is intended for Python distributors who wish to provide
+ distribution-specific guidance when users encounter standard library
+ modules that are missing or packaged separately.
+
+ The JSON file should map missing module names to custom error message strings.
+ For example, if your distribution packages :mod:`tkinter` and
+ :mod:`_tkinter` separately and excludes :mod:`!_gdbm` for legal reasons,
+ the configuration could contain:
+
+ .. code-block:: json
+
+ {
+ "_gdbm": "The '_gdbm' module is not available in this distribution",
+ "tkinter": "Install the python-tk package to use tkinter",
+ "_tkinter": "Install the python-tk package to use tkinter",
+ }
+
+ .. versionadded:: next
+
.. option:: --enable-pystats
Turn on internal Python performance statistics gathering.
@@ -409,6 +500,8 @@ Linker options
Name for machine-dependent library files.
+.. _configure-options-for-dependencies:
+
Options for third-party dependencies
------------------------------------
@@ -431,12 +524,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 +989,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.3.rst b/Doc/whatsnew/2.3.rst
index b7e4e73f4ce..f43692b3dce 100644
--- a/Doc/whatsnew/2.3.rst
+++ b/Doc/whatsnew/2.3.rst
@@ -66,7 +66,7 @@ Here's a simple example::
The union and intersection of sets can be computed with the :meth:`~frozenset.union` and
:meth:`~frozenset.intersection` methods; an alternative notation uses the bitwise operators
``&`` and ``|``. Mutable sets also have in-place versions of these methods,
-:meth:`!union_update` and :meth:`~frozenset.intersection_update`. ::
+:meth:`!union_update` and :meth:`~set.intersection_update`. ::
>>> S1 = sets.Set([1,2,3])
>>> S2 = sets.Set([4,5,6])
@@ -87,7 +87,7 @@ It's also possible to take the symmetric difference of two sets. This is the
set of all elements in the union that aren't in the intersection. Another way
of putting it is that the symmetric difference contains all elements that are in
exactly one set. Again, there's an alternative notation (``^``), and an
-in-place version with the ungainly name :meth:`~frozenset.symmetric_difference_update`. ::
+in-place version with the ungainly name :meth:`~set.symmetric_difference_update`. ::
>>> S1 = sets.Set([1,2,3,4])
>>> S2 = sets.Set([3,4,5,6])
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 5a10c036c35..d94a97dd3b8 100644
--- a/Doc/whatsnew/3.15.rst
+++ b/Doc/whatsnew/3.15.rst
@@ -400,6 +400,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
===========
@@ -418,6 +509,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`.)
@@ -461,6 +556,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
---
@@ -486,6 +599,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
-------
@@ -514,6 +635,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
------
@@ -536,9 +665,12 @@ math
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`)
+ (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
@@ -703,6 +835,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
------
@@ -732,6 +877,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
--------
@@ -744,17 +900,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
-----------------
@@ -1040,9 +1185,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
--------------
@@ -1161,6 +1320,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.
@@ -1173,6 +1340,12 @@ Build changes
set to ``no`` or with :option:`!--without-system-libmpdec`.
(Contributed by Sergey B Kirpichev in :gh:`115119`.)
+* The new configure option :option:`--with-missing-stdlib-config=FILE` allows
+ distributors to pass a `JSON `_
+ configuration file containing custom error messages for :term:`standard library`
+ modules that are missing or packaged separately.
+ (Contributed by Stan Ulbrych and Petr Viktorin in :gh:`139707`.)
+
Porting to Python 3.15
======================
@@ -1180,7 +1353,7 @@ 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 has been cleaned up.
+* :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`
@@ -1199,3 +1372,16 @@ that may require changes to your code.
* :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/Doc/whatsnew/3.4.rst b/Doc/whatsnew/3.4.rst
index 59afd6520c4..9f4068116e3 100644
--- a/Doc/whatsnew/3.4.rst
+++ b/Doc/whatsnew/3.4.rst
@@ -2,7 +2,7 @@
What's New In Python 3.4
****************************
-:Author: R. David Murray (Editor)
+:Author: \R. David Murray (Editor)
.. Rules for maintenance:
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..8693390aeda 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. */
@@ -432,8 +436,6 @@ PyAPI_FUNC(void) _Py_NO_RETURN _PyObject_AssertFailed(
PyAPI_FUNC(void) _PyTrash_thread_deposit_object(PyThreadState *tstate, PyObject *op);
PyAPI_FUNC(void) _PyTrash_thread_destroy_chain(PyThreadState *tstate);
-PyAPI_FUNC(int) _Py_ReachedRecursionLimitWithMargin(PyThreadState *tstate, int margin_count);
-
/* For backwards compatibility with the old trashcan mechanism */
#define Py_TRASHCAN_BEGIN(op, dealloc)
#define Py_TRASHCAN_END
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_call.h b/Include/internal/pycore_call.h
index 506da06f708..4f4cf02f64b 100644
--- a/Include/internal/pycore_call.h
+++ b/Include/internal/pycore_call.h
@@ -64,39 +64,6 @@ PyAPI_FUNC(PyObject*) _PyObject_CallMethod(
PyObject *name,
const char *format, ...);
-extern PyObject* _PyObject_CallMethodIdObjArgs(
- PyObject *obj,
- _Py_Identifier *name,
- ...);
-
-static inline PyObject *
-_PyObject_VectorcallMethodId(
- _Py_Identifier *name, PyObject *const *args,
- size_t nargsf, PyObject *kwnames)
-{
- PyObject *oname = _PyUnicode_FromId(name); /* borrowed */
- if (!oname) {
- return _Py_NULL;
- }
- return PyObject_VectorcallMethod(oname, args, nargsf, kwnames);
-}
-
-static inline PyObject *
-_PyObject_CallMethodIdNoArgs(PyObject *self, _Py_Identifier *name)
-{
- size_t nargsf = 1 | PY_VECTORCALL_ARGUMENTS_OFFSET;
- return _PyObject_VectorcallMethodId(name, &self, nargsf, _Py_NULL);
-}
-
-static inline PyObject *
-_PyObject_CallMethodIdOneArg(PyObject *self, _Py_Identifier *name, PyObject *arg)
-{
- PyObject *args[2] = {self, arg};
- size_t nargsf = 2 | PY_VECTORCALL_ARGUMENTS_OFFSET;
- assert(arg != NULL);
- return _PyObject_VectorcallMethodId(name, args, nargsf, _Py_NULL);
-}
-
/* === Vectorcall protocol (PEP 590) ============================= */
diff --git a/Include/internal/pycore_ceval.h b/Include/internal/pycore_ceval.h
index f1e84592b2e..56018d9cbad 100644
--- a/Include/internal/pycore_ceval.h
+++ b/Include/internal/pycore_ceval.h
@@ -33,8 +33,6 @@ extern int _PyEval_SetOpcodeTrace(PyFrameObject *f, bool enable);
// Export for 'array' shared extension
PyAPI_FUNC(PyObject*) _PyEval_GetBuiltin(PyObject *);
-extern PyObject* _PyEval_GetBuiltinId(_Py_Identifier *);
-
extern void _PyEval_SetSwitchInterval(unsigned long microseconds);
extern unsigned long _PyEval_GetSwitchInterval(void);
@@ -217,7 +215,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,9 +254,18 @@ 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
}
+// Export for test_peg_generator
+PyAPI_FUNC(int) _Py_ReachedRecursionLimitWithMargin(
+ PyThreadState *tstate,
+ int margin_count);
+
static inline void _Py_LeaveRecursiveCall(void) {
}
@@ -399,6 +413,66 @@ _PyForIter_VirtualIteratorNext(PyThreadState* tstate, struct _PyInterpreterFrame
#define SPECIAL___AEXIT__ 3
#define SPECIAL_MAX 3
+PyAPI_DATA(const _Py_CODEUNIT *) _Py_INTERPRETER_TRAMPOLINE_INSTRUCTIONS_PTR;
+
+/* Helper functions for large uops */
+
+PyAPI_FUNC(PyObject *)
+_Py_VectorCall_StackRefSteal(
+ _PyStackRef callable,
+ _PyStackRef *arguments,
+ int total_args,
+ _PyStackRef kwnames);
+
+PyAPI_FUNC(PyObject *)
+_Py_BuiltinCallFast_StackRefSteal(
+ _PyStackRef callable,
+ _PyStackRef *arguments,
+ int total_args);
+
+PyAPI_FUNC(PyObject *)
+_Py_BuiltinCallFastWithKeywords_StackRefSteal(
+ _PyStackRef callable,
+ _PyStackRef *arguments,
+ int total_args);
+
+PyAPI_FUNC(PyObject *)
+_PyCallMethodDescriptorFast_StackRefSteal(
+ _PyStackRef callable,
+ PyMethodDef *meth,
+ PyObject *self,
+ _PyStackRef *arguments,
+ int total_args);
+
+PyAPI_FUNC(PyObject *)
+_PyCallMethodDescriptorFastWithKeywords_StackRefSteal(
+ _PyStackRef callable,
+ PyMethodDef *meth,
+ PyObject *self,
+ _PyStackRef *arguments,
+ int total_args);
+
+PyAPI_FUNC(PyObject *)
+_Py_CallBuiltinClass_StackRefSteal(
+ _PyStackRef callable,
+ _PyStackRef *arguments,
+ int total_args);
+
+PyAPI_FUNC(PyObject *)
+_Py_BuildString_StackRefSteal(
+ _PyStackRef *arguments,
+ int total_args);
+
+PyAPI_FUNC(PyObject *)
+_Py_BuildMap_StackRefSteal(
+ _PyStackRef *arguments,
+ int half_args);
+
+PyAPI_FUNC(void)
+_Py_assert_within_stack_bounds(
+ _PyInterpreterFrame *frame, _PyStackRef *stack_pointer,
+ const char *filename, int lineno);
+
#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 3f9445f6ae1..911cc1f10f1 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_dict.h b/Include/internal/pycore_dict.h
index 9a14340c9f9..f7bceb4605e 100644
--- a/Include/internal/pycore_dict.h
+++ b/Include/internal/pycore_dict.h
@@ -44,6 +44,7 @@ extern int _PyDict_SetItemId(PyObject *dp, _Py_Identifier *key, PyObject *item);
extern int _PyDict_DelItemId(PyObject *mp, _Py_Identifier *key);
extern void _PyDict_ClearKeysVersion(PyObject *mp);
+
extern int _PyDict_Next(
PyObject *mp, Py_ssize_t *pos, PyObject **key, PyObject **value, Py_hash_t *hash);
diff --git a/Include/internal/pycore_global_objects_fini_generated.h b/Include/internal/pycore_global_objects_fini_generated.h
index 2a7b649f5e7..1a1bcc77ece 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));
@@ -1766,6 +1768,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));
@@ -1909,6 +1912,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));
@@ -2069,6 +2073,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 0024a4cfd8a..0633ceeaf0c 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")
@@ -489,6 +491,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)
@@ -632,6 +635,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)
@@ -792,6 +796,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_import.h b/Include/internal/pycore_import.h
index 23eca2dd911..c0db135a4e4 100644
--- a/Include/internal/pycore_import.h
+++ b/Include/internal/pycore_import.h
@@ -144,11 +144,18 @@ PyAPI_FUNC(int) _PyImport_ClearExtension(PyObject *name, PyObject *filename);
// state of the module argument:
// - If module is NULL or a PyModuleObject with md_gil == Py_MOD_GIL_NOT_USED,
// call _PyEval_DisableGIL().
-// - Otherwise, call _PyEval_EnableGILPermanent(). If the GIL was not already
-// enabled permanently, issue a warning referencing the module's name.
+// - Otherwise, call _PyImport_EnableGILAndWarn
//
// This function may raise an exception.
extern int _PyImport_CheckGILForModule(PyObject *module, PyObject *module_name);
+// Assuming that the GIL is enabled from a call to
+// _PyEval_EnableGILTransient(), call _PyEval_EnableGILPermanent().
+// If the GIL was not already enabled permanently, issue a warning referencing
+// the module's name.
+// Leave a message in verbose mode.
+//
+// This function may raise an exception.
+extern int _PyImport_EnableGILAndWarn(PyThreadState *, PyObject *module_name);
#endif
#ifdef __cplusplus
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_initconfig.h b/Include/internal/pycore_initconfig.h
index 368dafb9063..183b2d45c5e 100644
--- a/Include/internal/pycore_initconfig.h
+++ b/Include/internal/pycore_initconfig.h
@@ -153,10 +153,8 @@ typedef enum {
} _PyConfigInitEnum;
typedef enum {
- /* For now, this means the GIL is enabled.
-
- gh-116329: This will eventually change to "the GIL is disabled but can
- be re-enabled by loading an incompatible extension module." */
+ /* In free threaded builds, this means that the GIL is disabled at startup,
+ but may be enabled by loading an incompatible extension module. */
_PyConfig_GIL_DEFAULT = -1,
/* The GIL has been forced off or on, and will not be affected by module loading. */
diff --git a/Include/internal/pycore_interp_structs.h b/Include/internal/pycore_interp_structs.h
index a147b9e5d73..9507d6e5974 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 */
@@ -940,10 +949,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;
@@ -969,6 +978,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_jit.h b/Include/internal/pycore_jit.h
index 8a88cbf607b..b1550a6ddcf 100644
--- a/Include/internal/pycore_jit.h
+++ b/Include/internal/pycore_jit.h
@@ -13,6 +13,9 @@ extern "C" {
# error "this header requires Py_BUILD_CORE define"
#endif
+/* To be able to reason about code layout and branches, keep code size below 1 MB */
+#define PY_MAX_JIT_CODE_SIZE ((1 << 20)-1)
+
#ifdef _Py_JIT
typedef _Py_CODEUNIT *(*jit_func)(_PyInterpreterFrame *frame, _PyStackRef *stack_pointer, PyThreadState *tstate);
diff --git a/Include/internal/pycore_magic_number.h b/Include/internal/pycore_magic_number.h
index cfaf84181d5..0dd18ff3cb0 100644
--- a/Include/internal/pycore_magic_number.h
+++ b/Include/internal/pycore_magic_number.h
@@ -286,7 +286,8 @@ 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 Lazy imports IMPORT_NAME opcode changes
+ Python 3.15a1 3656 (Add TRACE_RECORD instruction, for platforms with switch based interpreter)
+ Python 3.15a1 3657 Lazy imports IMPORT_NAME opcode changes
Python 3.16 will start with 3700
@@ -300,7 +301,7 @@ PC/launcher.c must also be updated.
*/
-#define PYC_MAGIC_NUMBER 3657
+#define PYC_MAGIC_NUMBER 3658
/* 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 89131c6f0a1..15a68523f47 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,34 +19,51 @@ 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;
// module version we last checked for lazy values
uint32_t m_dict_version;
+ 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_pyatomic_ft_wrappers.h b/Include/internal/pycore_pyatomic_ft_wrappers.h
index c31c3365700..2ae0185226f 100644
--- a/Include/internal/pycore_pyatomic_ft_wrappers.h
+++ b/Include/internal/pycore_pyatomic_ft_wrappers.h
@@ -77,6 +77,10 @@ extern "C" {
_Py_atomic_store_ushort_relaxed(&value, new_value)
#define FT_ATOMIC_LOAD_USHORT_RELAXED(value) \
_Py_atomic_load_ushort_relaxed(&value)
+#define FT_ATOMIC_LOAD_INT(value) \
+ _Py_atomic_load_int(&value)
+#define FT_ATOMIC_STORE_INT(value, new_value) \
+ _Py_atomic_store_int(&value, new_value)
#define FT_ATOMIC_STORE_INT_RELAXED(value, new_value) \
_Py_atomic_store_int_relaxed(&value, new_value)
#define FT_ATOMIC_LOAD_INT_RELAXED(value) \
@@ -144,6 +148,8 @@ extern "C" {
#define FT_ATOMIC_STORE_SHORT_RELAXED(value, new_value) value = new_value
#define FT_ATOMIC_LOAD_USHORT_RELAXED(value) value
#define FT_ATOMIC_STORE_USHORT_RELAXED(value, new_value) value = new_value
+#define FT_ATOMIC_LOAD_INT(value) value
+#define FT_ATOMIC_STORE_INT(value, new_value) value = new_value
#define FT_ATOMIC_LOAD_INT_RELAXED(value) value
#define FT_ATOMIC_STORE_INT_RELAXED(value, new_value) value = new_value
#define FT_ATOMIC_LOAD_UINT_RELAXED(value) value
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..05484e847f1 100644
--- a/Include/internal/pycore_pymem.h
+++ b/Include/internal/pycore_pymem.h
@@ -54,20 +54,43 @@ 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
}
+// Similar to _PyMem_IsPtrFreed() but expects an 'unsigned long' instead of a
+// pointer.
+static inline int _PyMem_IsULongFreed(unsigned long value)
+{
+#if SIZEOF_LONG == 8
+ return (value == 0
+ || value == (unsigned long)0xCDCDCDCDCDCDCDCD
+ || value == (unsigned long)0xDDDDDDDDDDDDDDDD
+ || value == (unsigned long)0xFDFDFDFDFDFDFDFD
+ || value == (unsigned long)0xFFFFFFFFFFFFFFFF);
+#elif SIZEOF_LONG == 4
+ return (value == 0
+ || value == (unsigned long)0xCDCDCDCD
+ || value == (unsigned long)0xDDDDDDDD
+ || value == (unsigned long)0xFDFDFDFD
+ || value == (unsigned long)0xFFFFFFFF);
+#else
+# error "unknown long size"
+#endif
+}
+
extern int _PyMem_GetAllocatorName(
const char *name,
PyMemAllocatorName *allocator);
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 5eddb24b854..c0f60925a0f 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"), \
@@ -1764,6 +1766,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), \
@@ -1907,6 +1910,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), \
@@ -2067,6 +2071,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 88189228e1a..ac40e5d6eee 100644
--- a/Include/internal/pycore_symtable.h
+++ b/Include/internal/pycore_symtable.h
@@ -189,7 +189,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_tracemalloc.h b/Include/internal/pycore_tracemalloc.h
index 572e8025876..693385f9a46 100644
--- a/Include/internal/pycore_tracemalloc.h
+++ b/Include/internal/pycore_tracemalloc.h
@@ -30,8 +30,8 @@ struct _PyTraceMalloc_Config {
};
-/* Pack the frame_t structure to reduce the memory footprint on 64-bit
- architectures: 12 bytes instead of 16. */
+/* Pack the tracemalloc_frame and tracemalloc_traceback structures to reduce
+ the memory footprint on 64-bit architectures: 12 bytes instead of 16. */
#if defined(_MSC_VER)
#pragma pack(push, 4)
#endif
@@ -46,18 +46,22 @@ tracemalloc_frame {
PyObject *filename;
unsigned int lineno;
};
-#ifdef _MSC_VER
-#pragma pack(pop)
-#endif
-struct tracemalloc_traceback {
+struct
+#ifdef __GNUC__
+__attribute__((packed))
+#endif
+tracemalloc_traceback {
Py_uhash_t hash;
/* Number of frames stored */
uint16_t nframe;
/* Total number of frames the traceback had */
uint16_t total_nframe;
- struct tracemalloc_frame frames[1];
+ struct tracemalloc_frame frames[];
};
+#ifdef _MSC_VER
+#pragma pack(pop)
+#endif
struct _tracemalloc_runtime_state {
@@ -95,7 +99,7 @@ struct _tracemalloc_runtime_state {
Protected by TABLES_LOCK(). */
_Py_hashtable_t *domains;
- struct tracemalloc_traceback empty_traceback;
+ struct tracemalloc_traceback *empty_traceback;
Py_tss_t reentrant_key;
};
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.h b/Include/internal/pycore_unicodeobject.h
index e7ca65a56b6..97dda73f9b5 100644
--- a/Include/internal/pycore_unicodeobject.h
+++ b/Include/internal/pycore_unicodeobject.h
@@ -307,14 +307,6 @@ PyAPI_FUNC(PyObject*) _PyUnicode_JoinArray(
Py_ssize_t seqlen
);
-/* Test whether a unicode is equal to ASCII identifier. Return 1 if true,
- 0 otherwise. The right argument must be ASCII identifier.
- Any error occurs inside will be cleared before return. */
-extern int _PyUnicode_EqualToASCIIId(
- PyObject *left, /* Left string */
- _Py_Identifier *right /* Right identifier */
- );
-
// Test whether a unicode is equal to ASCII string. Return 1 if true,
// 0 otherwise. The right argument must be ASCII-encoded string.
// Any error occurs inside will be cleared before return.
diff --git a/Include/internal/pycore_unicodeobject_generated.h b/Include/internal/pycore_unicodeobject_generated.h
index fe527fae8f5..0b1bc279722 100644
--- a/Include/internal/pycore_unicodeobject_generated.h
+++ b/Include/internal/pycore_unicodeobject_generated.h
@@ -1744,6 +1744,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));
@@ -2316,6 +2320,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));
@@ -2956,6 +2964,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));
@@ -3248,6 +3260,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));
@@ -3272,6 +3288,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..70576046385 100644
--- a/Include/internal/pycore_uop.h
+++ b/Include/internal/pycore_uop.h
@@ -35,10 +35,23 @@ 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.
+#ifdef Py_DEBUG
+ // With asserts, the stencils are a lot larger
+#define UOP_MAX_TRACE_LENGTH 1000
+#else
+#define UOP_MAX_TRACE_LENGTH 3000
+#endif
#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/modsupport.h b/Include/modsupport.h
index 094b9ff0e5c..cb47ad8cd27 100644
--- a/Include/modsupport.h
+++ b/Include/modsupport.h
@@ -132,7 +132,7 @@ PyAPI_FUNC(int) PyABIInfo_Check(PyABIInfo *info, const char *module_name);
) \
/////////////////////////////////////////////////////////
-#define _PyABIInfo_DEFAULT() { \
+#define _PyABIInfo_DEFAULT { \
1, 0, \
PyABIInfo_DEFAULT_FLAGS, \
PY_VERSION_HEX, \
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..ad452be8405 100644
--- a/Include/object.h
+++ b/Include/object.h
@@ -140,12 +140,12 @@ struct _object {
# endif
};
#else
- Py_ssize_t ob_refcnt;
+ Py_ssize_t ob_refcnt; // part of stable ABI; do not change
#endif
_Py_ALIGNED_DEF(_PyObject_MIN_ALIGNMENT, char) _aligner;
};
- PyTypeObject *ob_type;
+ PyTypeObject *ob_type; // part of stable ABI; do not change
};
#else
// Objects that are not owned by any thread use a thread id (tid) of zero.
@@ -173,7 +173,7 @@ struct _object {
#ifndef _Py_OPAQUE_PYOBJECT
struct PyVarObject {
PyObject ob_base;
- Py_ssize_t ob_size; /* Number of items in variable part */
+ Py_ssize_t ob_size; // Number of items in variable part. Part of stable ABI
};
#endif
typedef struct PyVarObject PyVarObject;
@@ -265,56 +265,72 @@ _Py_IsOwnedByCurrentThread(PyObject *ob)
}
#endif
-// Py_TYPE() implementation for the stable ABI
-PyAPI_FUNC(PyTypeObject*) Py_TYPE(PyObject *ob);
-
-#if defined(Py_LIMITED_API) && Py_LIMITED_API+0 >= 0x030e0000
- // Stable ABI implements Py_TYPE() as a function call
- // on limited C API version 3.14 and newer.
-#else
- static inline PyTypeObject* _Py_TYPE(PyObject *ob)
- {
- return ob->ob_type;
- }
- #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
- # define Py_TYPE(ob) _Py_TYPE(_PyObject_CAST(ob))
- #else
- # define Py_TYPE(ob) _Py_TYPE(ob)
- #endif
-#endif
-
PyAPI_DATA(PyTypeObject) PyLong_Type;
PyAPI_DATA(PyTypeObject) PyBool_Type;
+/* Definitions for the stable ABI */
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= _Py_PACK_VERSION(3, 14)
+PyAPI_FUNC(PyTypeObject*) Py_TYPE(PyObject *ob);
+#endif
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= _Py_PACK_VERSION(3, 15)
+PyAPI_FUNC(Py_ssize_t) Py_SIZE(PyObject *ob);
+PyAPI_FUNC(int) Py_IS_TYPE(PyObject *ob, PyTypeObject *type);
+PyAPI_FUNC(void) Py_SET_SIZE(PyVarObject *ob, Py_ssize_t size);
+#endif
+
#ifndef _Py_OPAQUE_PYOBJECT
+
+static inline void
+Py_SET_TYPE(PyObject *ob, PyTypeObject *type)
+{
+ ob->ob_type = type;
+}
+
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < _Py_PACK_VERSION(3, 11)
+// Non-limited API & limited API 3.11 & below: use static inline functions and
+// use _PyObject_CAST so that users don't need their own casts
+# define Py_TYPE(ob) _Py_TYPE_impl(_PyObject_CAST(ob))
+# define Py_SIZE(ob) _Py_SIZE_impl(_PyObject_CAST(ob))
+# define Py_IS_TYPE(ob, type) _Py_IS_TYPE_impl(_PyObject_CAST(ob), (type))
+# define Py_SET_SIZE(ob, size) _Py_SET_SIZE_impl(_PyVarObject_CAST(ob), (size))
+# define Py_SET_TYPE(ob, type) Py_SET_TYPE(_PyObject_CAST(ob), type)
+#elif Py_LIMITED_API+0 < _Py_PACK_VERSION(3, 15)
+// Limited API 3.11-3.14: use static inline functions, without casts
+# define Py_SIZE(ob) _Py_SIZE_impl(ob)
+# define Py_IS_TYPE(ob, type) _Py_IS_TYPE_impl((ob), (type))
+# define Py_SET_SIZE(ob, size) _Py_SET_SIZE_impl((ob), (size))
+# if Py_LIMITED_API+0 < _Py_PACK_VERSION(3, 14)
+// Py_TYPE() is static inline only on Limited API 3.13 and below
+# define Py_TYPE(ob) _Py_TYPE_impl(ob)
+# endif
+#else
+// Limited API 3.15+: use function calls
+#endif
+
+static inline
+PyTypeObject* _Py_TYPE_impl(PyObject *ob)
+{
+ return ob->ob_type;
+}
+
// bpo-39573: The Py_SET_SIZE() function must be used to set an object size.
-static inline Py_ssize_t Py_SIZE(PyObject *ob) {
+static inline Py_ssize_t
+_Py_SIZE_impl(PyObject *ob)
+{
assert(Py_TYPE(ob) != &PyLong_Type);
assert(Py_TYPE(ob) != &PyBool_Type);
return _PyVarObject_CAST(ob)->ob_size;
}
-#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
-# define Py_SIZE(ob) Py_SIZE(_PyObject_CAST(ob))
-#endif
-#endif // !defined(_Py_OPAQUE_PYOBJECT)
-static inline int Py_IS_TYPE(PyObject *ob, PyTypeObject *type) {
+static inline int
+_Py_IS_TYPE_impl(PyObject *ob, PyTypeObject *type)
+{
return Py_TYPE(ob) == type;
}
-#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
-# define Py_IS_TYPE(ob, type) Py_IS_TYPE(_PyObject_CAST(ob), (type))
-#endif
-
-#ifndef _Py_OPAQUE_PYOBJECT
-static inline void Py_SET_TYPE(PyObject *ob, PyTypeObject *type) {
- ob->ob_type = type;
-}
-#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
-# define Py_SET_TYPE(ob, type) Py_SET_TYPE(_PyObject_CAST(ob), type)
-#endif
-
-static inline void Py_SET_SIZE(PyVarObject *ob, Py_ssize_t size) {
+static inline void
+_Py_SET_SIZE_impl(PyVarObject *ob, Py_ssize_t size)
+{
assert(Py_TYPE(_PyObject_CAST(ob)) != &PyLong_Type);
assert(Py_TYPE(_PyObject_CAST(ob)) != &PyBool_Type);
#ifdef Py_GIL_DISABLED
@@ -323,9 +339,7 @@ static inline void Py_SET_SIZE(PyVarObject *ob, Py_ssize_t size) {
ob->ob_size = size;
#endif
}
-#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
-# define Py_SET_SIZE(ob, size) Py_SET_SIZE(_PyVarObject_CAST(ob), (size))
-#endif
+
#endif // !defined(_Py_OPAQUE_PYOBJECT)
@@ -839,6 +853,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/pymacro.h b/Include/pymacro.h
index 857cdf12db9..7ecce44a0d2 100644
--- a/Include/pymacro.h
+++ b/Include/pymacro.h
@@ -116,6 +116,12 @@
/* Absolute value of the number x */
#define Py_ABS(x) ((x) < 0 ? -(x) : (x))
+/* Safer implementation that avoids an undefined behavior for the minimal
+ value of the signed integer type if its absolute value is larger than
+ the maximal value of the signed integer type (in the two's complement
+ representations, which is common).
+ */
+#define _Py_ABS_CAST(T, x) ((x) >= 0 ? ((T) (x)) : ((T) (((T) -((x) + 1)) + 1u)))
#define _Py_XSTRINGIFY(x) #x
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..61e2317976e 100644
--- a/Include/pyport.h
+++ b/Include/pyport.h
@@ -504,13 +504,20 @@ 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
-#ifdef WITH_THREAD
-// HAVE_THREAD_LOCAL is just defined here for compatibility's sake
+
+/* gh-142163: Some libraries rely on HAVE_THREAD_LOCAL being undefined, so
+ * we can only define it only when Py_BUILD_CORE is set.*/
+#ifdef Py_BUILD_CORE
+// This is no longer coupled to _Py_thread_local.
# define HAVE_THREAD_LOCAL 1
+#endif
+
+#ifdef WITH_THREAD
# ifdef thread_local
# define _Py_thread_local thread_local
# elif __STDC_VERSION__ >= 201112L && !defined(__STDC_NO_THREADS__)
@@ -677,4 +684,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 2166dbff0ee..a5788cdbfae 100644
--- a/Lib/annotationlib.py
+++ b/Lib/annotationlib.py
@@ -150,33 +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. Similar reasoning applies to nonlocals stored in cells.
- if type_params is not None or isinstance(self.__cell__, dict):
- globals = dict(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:
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_value in self.__cell__.items():
+ for cell_name, cell in self.__cell__.items():
try:
- globals[cell_name] = cell_value.cell_contents
+ 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):
@@ -835,14 +844,9 @@ 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, None
- freevars = annotate.__code__.co_freevars
new_closure = []
cell_dict = {}
- for i, cell in enumerate(annotate.__closure__):
- if i < len(freevars):
- name = freevars[i]
- else:
- name = "__cell__"
+ for name, cell in zip(annotate.__code__.co_freevars, annotate.__closure__, strict=True):
cell_dict[name] = cell
new_cell = None
if allow_evaluation:
diff --git a/Lib/argparse.py b/Lib/argparse.py
index 1f4413a9897..07d7d77e884 100644
--- a/Lib/argparse.py
+++ b/Lib/argparse.py
@@ -166,7 +166,6 @@ def __init__(
indent_increment=2,
max_help_position=24,
width=None,
- color=True,
):
# default setting for width
if width is None:
@@ -174,7 +173,6 @@ def __init__(
width = shutil.get_terminal_size().columns
width -= 2
- self._set_color(color)
self._prog = prog
self._indent_increment = indent_increment
self._max_help_position = min(max_help_position,
@@ -355,8 +353,14 @@ def _format_usage(self, usage, actions, groups, prefix):
if len(prefix) + len(self._decolor(usage)) > text_width:
# break usage into wrappable parts
- opt_parts = self._get_actions_usage_parts(optionals, groups)
- pos_parts = self._get_actions_usage_parts(positionals, groups)
+ # keep optionals and positionals together to preserve
+ # mutually exclusive group formatting (gh-75949)
+ all_actions = optionals + positionals
+ parts, pos_start = self._get_actions_usage_parts_with_split(
+ all_actions, groups, len(optionals)
+ )
+ opt_parts = parts[:pos_start]
+ pos_parts = parts[pos_start:]
# helper for wrapping lines
def get_lines(parts, indent, prefix=None):
@@ -420,6 +424,17 @@ def _is_long_option(self, string):
return len(string) > 2
def _get_actions_usage_parts(self, actions, groups):
+ parts, _ = self._get_actions_usage_parts_with_split(actions, groups)
+ return parts
+
+ def _get_actions_usage_parts_with_split(self, actions, groups, opt_count=None):
+ """Get usage parts with split index for optionals/positionals.
+
+ Returns (parts, pos_start) where pos_start is the index in parts
+ where positionals begin. When opt_count is None, pos_start is None.
+ This preserves mutually exclusive group formatting across the
+ optionals/positionals boundary (gh-75949).
+ """
# find group indices and identify actions in groups
group_actions = set()
inserts = {}
@@ -515,8 +530,16 @@ def _get_actions_usage_parts(self, actions, groups):
for i in range(start + group_size, end):
parts[i] = None
- # return the usage parts
- return [item for item in parts if item is not None]
+ # if opt_count is provided, calculate where positionals start in
+ # the final parts list (for wrapping onto separate lines).
+ # Count before filtering None entries since indices shift after.
+ if opt_count is not None:
+ pos_start = sum(1 for p in parts[:opt_count] if p is not None)
+ else:
+ pos_start = None
+
+ # return the usage parts and split point (gh-75949)
+ return [item for item in parts if item is not None], pos_start
def _format_text(self, text):
if '%(prog)' in text:
@@ -748,7 +771,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 +962,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 +991,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)
@@ -1551,8 +1593,8 @@ def add_argument(self, *args, **kwargs):
f'instance of it must be passed')
# raise an error if the metavar does not match the type
- if hasattr(self, "_get_formatter"):
- formatter = self._get_formatter()
+ if hasattr(self, "_get_validation_formatter"):
+ formatter = self._get_validation_formatter()
try:
formatter._format_args(action, None)
except TypeError:
@@ -1660,29 +1702,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('-', '_')
@@ -1740,8 +1788,8 @@ def _handle_conflict_resolve(self, action, conflicting_actions):
action.container._remove_action(action)
def _check_help(self, action):
- if action.help and hasattr(self, "_get_formatter"):
- formatter = self._get_formatter()
+ if action.help and hasattr(self, "_get_validation_formatter"):
+ formatter = self._get_validation_formatter()
try:
formatter._expand_help(action)
except (ValueError, TypeError, KeyError) as exc:
@@ -1896,6 +1944,9 @@ def __init__(self,
self.suggest_on_error = suggest_on_error
self.color = color
+ # Cached formatter for validation (avoids repeated _set_color calls)
+ self._cached_formatter = None
+
add_group = self.add_argument_group
self._positionals = add_group(_('positional arguments'))
self._optionals = add_group(_('options'))
@@ -2727,6 +2778,13 @@ def _get_formatter(self):
formatter._set_color(self.color)
return formatter
+ def _get_validation_formatter(self):
+ # Return cached formatter for read-only validation operations
+ # (_expand_help and _format_args). Avoids repeated slow _set_color calls.
+ if self._cached_formatter is None:
+ self._cached_formatter = self._get_formatter()
+ return self._cached_formatter
+
# =====================
# Help-printing methods
# =====================
@@ -2749,6 +2807,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 +2834,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/streams.py b/Lib/asyncio/streams.py
index 59e22f523a8..d2db1a930c2 100644
--- a/Lib/asyncio/streams.py
+++ b/Lib/asyncio/streams.py
@@ -667,8 +667,7 @@ async def readuntil(self, separator=b'\n'):
# adds data which makes separator be found. That's why we check for
# EOF *after* inspecting the buffer.
if self._eof:
- chunk = bytes(self._buffer)
- self._buffer.clear()
+ chunk = self._buffer.take_bytes()
raise exceptions.IncompleteReadError(chunk, None)
# _wait_for_data() will resume reading if stream was paused.
@@ -678,10 +677,9 @@ async def readuntil(self, separator=b'\n'):
raise exceptions.LimitOverrunError(
'Separator is found, but chunk is longer than limit', match_start)
- chunk = self._buffer[:match_end]
- del self._buffer[:match_end]
+ chunk = self._buffer.take_bytes(match_end)
self._maybe_resume_transport()
- return bytes(chunk)
+ return chunk
async def read(self, n=-1):
"""Read up to `n` bytes from the stream.
@@ -716,20 +714,16 @@ async def read(self, n=-1):
# collect everything in self._buffer, but that would
# deadlock if the subprocess sends more than self.limit
# bytes. So just call self.read(self._limit) until EOF.
- blocks = []
- while True:
- block = await self.read(self._limit)
- if not block:
- break
- blocks.append(block)
- return b''.join(blocks)
+ joined = bytearray()
+ while block := await self.read(self._limit):
+ joined += block
+ return joined.take_bytes()
if not self._buffer and not self._eof:
await self._wait_for_data('read')
# This will work right even if buffer is less than n bytes
- data = bytes(memoryview(self._buffer)[:n])
- del self._buffer[:n]
+ data = self._buffer.take_bytes(min(len(self._buffer), n))
self._maybe_resume_transport()
return data
@@ -760,18 +754,12 @@ async def readexactly(self, n):
while len(self._buffer) < n:
if self._eof:
- incomplete = bytes(self._buffer)
- self._buffer.clear()
+ incomplete = self._buffer.take_bytes()
raise exceptions.IncompleteReadError(incomplete, n)
await self._wait_for_data('readexactly')
- if len(self._buffer) == n:
- data = bytes(self._buffer)
- self._buffer.clear()
- else:
- data = bytes(memoryview(self._buffer)[:n])
- del self._buffer[:n]
+ data = self._buffer.take_bytes(n)
self._maybe_resume_transport()
return data
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..341bf8eaf18 100644
--- a/Lib/base64.py
+++ b/Lib/base64.py
@@ -193,7 +193,7 @@ def _b32encode(alphabet, s):
encoded[-3:] = b'==='
elif leftover == 4:
encoded[-1:] = b'='
- return bytes(encoded)
+ return encoded.take_bytes()
def _b32decode(alphabet, s, casefold=False, map01=None):
# Delay the initialization of the table to not waste memory
@@ -238,7 +238,7 @@ def _b32decode(alphabet, s, casefold=False, map01=None):
last = acc.to_bytes(5) # big endian
leftover = (43 - 5 * padchars) // 8 # 1: 4, 3: 3, 4: 2, 6: 1
decoded[-5:] = last[:leftover]
- return bytes(decoded)
+ return decoded.take_bytes()
def b32encode(s):
@@ -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/cProfile.py b/Lib/cProfile.py
index 4af82f2cb8c..cc6255f61ae 100644
--- a/Lib/cProfile.py
+++ b/Lib/cProfile.py
@@ -9,6 +9,5 @@
__all__ = ["run", "runctx", "Profile"]
if __name__ == "__main__":
- import sys
from profiling.tracing.__main__ import main
main()
diff --git a/Lib/collections/__init__.py b/Lib/collections/__init__.py
index 25ac4d1d524..55ffc36ea5b 100644
--- a/Lib/collections/__init__.py
+++ b/Lib/collections/__init__.py
@@ -1542,6 +1542,8 @@ def format_map(self, mapping):
return self.data.format_map(mapping)
def index(self, sub, start=0, end=_sys.maxsize):
+ if isinstance(sub, UserString):
+ sub = sub.data
return self.data.index(sub, start, end)
def isalpha(self):
@@ -1610,6 +1612,8 @@ def rfind(self, sub, start=0, end=_sys.maxsize):
return self.data.rfind(sub, start, end)
def rindex(self, sub, start=0, end=_sys.maxsize):
+ if isinstance(sub, UserString):
+ sub = sub.data
return self.data.rindex(sub, start, end)
def rjust(self, width, *args):
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..730ced72998 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,49 @@ 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:
+ # gh-142214: The annotation may be missing in unusual dynamic cases.
+ # If so, just skip it.
+ try:
+ new_annotations[k] = cls_annotations[k]
+ except KeyError:
+ pass
+
+ 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 +664,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 +687,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 +721,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 +1389,26 @@ 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 = newcls.__init__
+ if init_annotate := getattr(init, "__annotate__", None):
+ 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/encodings/idna.py b/Lib/encodings/idna.py
index 0c90b4c9fe1..d31ee07ab45 100644
--- a/Lib/encodings/idna.py
+++ b/Lib/encodings/idna.py
@@ -226,7 +226,8 @@ def encode(self, input, errors='strict'):
offset + exc.end,
exc.reason,
)
- return bytes(result+trailing_dot), len(input)
+ result += trailing_dot
+ return result.take_bytes(), len(input)
def decode(self, input, errors='strict'):
@@ -311,7 +312,7 @@ def _buffer_encode(self, input, errors, final):
result += trailing_dot
size += len(trailing_dot)
- return (bytes(result), size)
+ return (result.take_bytes(), size)
class IncrementalDecoder(codecs.BufferedIncrementalDecoder):
def _buffer_decode(self, input, errors, final):
diff --git a/Lib/encodings/punycode.py b/Lib/encodings/punycode.py
index 4622fc8c920..268fccbd539 100644
--- a/Lib/encodings/punycode.py
+++ b/Lib/encodings/punycode.py
@@ -17,7 +17,7 @@ def segregate(str):
else:
extended.add(c)
extended = sorted(extended)
- return bytes(base), extended
+ return base.take_bytes(), extended
def selective_len(str, max):
"""Return the length of str, considering only characters below max."""
@@ -83,7 +83,7 @@ def generate_generalized_integer(N, bias):
t = T(j, bias)
if N < t:
result.append(digits[N])
- return bytes(result)
+ return result.take_bytes()
result.append(digits[t + ((N - t) % (36 - t))])
N = (N - t) // (36 - t)
j += 1
@@ -112,7 +112,7 @@ def generate_integers(baselen, deltas):
s = generate_generalized_integer(delta, bias)
result.extend(s)
bias = adapt(delta, points==0, baselen+points+1)
- return bytes(result)
+ return result.take_bytes()
def punycode_encode(text):
base, extended = segregate(text)
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..73c3256734a 100644
--- a/Lib/http/client.py
+++ b/Lib/http/client.py
@@ -111,6 +111,11 @@
_MAXLINE = 65536
_MAXHEADERS = 100
+# Data larger than this will be read in chunks, to prevent extreme
+# overallocation.
+_MIN_READ_BUF_SIZE = 1 << 20
+
+
# Header name/value ABNF (http://tools.ietf.org/html/rfc7230#section-3.2)
#
# VCHAR = %x21-7E
@@ -231,7 +236,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 +249,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)
@@ -642,10 +647,25 @@ def _safe_read(self, amt):
reading. If the bytes are truly not available (due to EOF), then the
IncompleteRead exception can be used to detect the problem.
"""
- data = self.fp.read(amt)
- if len(data) < amt:
- raise IncompleteRead(data, amt-len(data))
- return data
+ cursize = min(amt, _MIN_READ_BUF_SIZE)
+ data = self.fp.read(cursize)
+ if len(data) >= amt:
+ return data
+ if len(data) < cursize:
+ raise IncompleteRead(data, amt - len(data))
+
+ data = io.BytesIO(data)
+ data.seek(0, 2)
+ while True:
+ # This is a geometric increase in read size (never more than
+ # doubling out the current length of data per loop iteration).
+ delta = min(cursize, amt - cursize)
+ data.write(self.fp.read(delta))
+ if data.tell() >= amt:
+ return data.getvalue()
+ cursize += delta
+ if data.tell() < cursize:
+ raise IncompleteRead(data.getvalue(), amt - data.tell())
def _safe_readinto(self, b):
"""Same as _safe_read, but for reading into a buffer."""
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..2f9307cba4f 100644
--- a/Lib/importlib/_bootstrap_external.py
+++ b/Lib/importlib/_bootstrap_external.py
@@ -208,12 +208,8 @@ def _write_atomic(path, data, mode=0o666):
try:
# We first write data to a temporary file, and then use os.replace() to
# perform an atomic rename.
- with _io.FileIO(fd, 'wb') as file:
- bytes_written = file.write(data)
- if bytes_written != len(data):
- # Raise an OSError so the 'except' below cleans up the partially
- # written file.
- raise OSError("os.write() didn't write the full pyc file")
+ with _io.open(fd, 'wb') as file:
+ file.write(data)
_os.replace(path_tmp, path)
except OSError:
try:
@@ -552,8 +548,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 +814,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 +890,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 +1182,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/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/queues.py b/Lib/multiprocessing/queues.py
index 925f0439000..981599acf5e 100644
--- a/Lib/multiprocessing/queues.py
+++ b/Lib/multiprocessing/queues.py
@@ -121,7 +121,7 @@ def get(self, block=True, timeout=None):
def qsize(self):
# Raises NotImplementedError on Mac OSX because of broken sem_getvalue()
- return self._maxsize - self._sem._semlock._get_value()
+ return self._maxsize - self._sem.get_value()
def empty(self):
return not self._poll()
diff --git a/Lib/multiprocessing/resource_tracker.py b/Lib/multiprocessing/resource_tracker.py
index c53092f6e34..3606d1effb4 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
@@ -65,6 +68,13 @@ def __init__(self):
self._exitcode = None
self._reentrant_messages = deque()
+ # True to use colon-separated lines, rather than JSON lines,
+ # for internal communication. (Mainly for testing).
+ # Filenames not supported by the simple format will always be sent
+ # using JSON.
+ # The reader should understand all formats.
+ self._use_simple_format = False
+
def _reentrant_call_error(self):
# gh-109629: this happens if an explicit call to the ResourceTracker
# gets interrupted by a garbage collection, invoking a finalizer (*)
@@ -111,7 +121,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 +206,19 @@ def _launch(self):
finally:
os.close(r)
+ def _make_probe_message(self):
+ """Return a probe message."""
+ if self._use_simple_format:
+ return b'PROBE:0:noop\n'
+ 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 +230,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 +257,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 +276,35 @@ 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')
+ if self._use_simple_format and '\n' not in name:
+ 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')
+ self._ensure_running_and_write(msg)
+ return
+
+ # 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)"
+ assert msg.startswith(b'{')
self._ensure_running_and_write(msg)
@@ -263,6 +315,30 @@ def _send(self, cmd, name, rtype):
getfd = _resource_tracker.getfd
+def _decode_message(line):
+ if line.startswith(b'{'):
+ 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
+ else:
+ cmd, rest = line.strip().decode('ascii').split(':', maxsplit=1)
+ name, rtype = rest.rsplit(':', maxsplit=1)
+ return cmd, rtype, name
+
+
def main(fd):
'''Run resource tracker.'''
# protect the process from ^C and "killall python" etc
@@ -285,7 +361,7 @@ def main(fd):
with open(fd, 'rb') as f:
for line in f:
try:
- cmd, name, rtype = line.strip().decode('ascii').split(':')
+ cmd, rtype, name = _decode_message(line)
cleanup_func = _CLEANUP_FUNCS.get(rtype, None)
if cleanup_func is None:
raise ValueError(
diff --git a/Lib/multiprocessing/synchronize.py b/Lib/multiprocessing/synchronize.py
index 30425047e98..9188114ae28 100644
--- a/Lib/multiprocessing/synchronize.py
+++ b/Lib/multiprocessing/synchronize.py
@@ -135,11 +135,16 @@ def __init__(self, value=1, *, ctx):
SemLock.__init__(self, SEMAPHORE, value, SEM_VALUE_MAX, ctx=ctx)
def get_value(self):
+ '''Returns current value of Semaphore.
+
+ Raises NotImplementedError on Mac OSX
+ because of broken sem_getvalue().
+ '''
return self._semlock._get_value()
def __repr__(self):
try:
- value = self._semlock._get_value()
+ value = self.get_value()
except Exception:
value = 'unknown'
return '<%s(value=%s)>' % (self.__class__.__name__, value)
@@ -155,7 +160,7 @@ def __init__(self, value=1, *, ctx):
def __repr__(self):
try:
- value = self._semlock._get_value()
+ value = self.get_value()
except Exception:
value = 'unknown'
return '<%s(value=%s, maxvalue=%s)>' % \
@@ -247,8 +252,8 @@ def _make_methods(self):
def __repr__(self):
try:
- num_waiters = (self._sleeping_count._semlock._get_value() -
- self._woken_count._semlock._get_value())
+ num_waiters = (self._sleeping_count.get_value() -
+ self._woken_count.get_value())
except Exception:
num_waiters = 'unknown'
return '<%s(%s, %s)>' % (self.__class__.__name__, self._lock, num_waiters)
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 fdc74198582..1506e3d4709 100644
--- a/Lib/pdb.py
+++ b/Lib/pdb.py
@@ -130,7 +130,7 @@ def find_first_executable_line(code):
return code.co_firstlineno
def find_function(funcname, filename):
- cre = re.compile(r'def\s+%s(\s*\[.+\])?\s*[(]' % re.escape(funcname))
+ cre = re.compile(r'(?:async\s+)?def\s+%s(\s*\[.+\])?\s*[(]' % re.escape(funcname))
try:
fp = tokenize.open(filename)
except OSError:
@@ -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()
@@ -648,7 +654,7 @@ def _show_display(self):
def _get_tb_and_exceptions(self, tb_or_exc):
"""
- Given a tracecack or an exception, return a tuple of chained exceptions
+ Given a traceback or an exception, return a tuple of chained exceptions
and current traceback to inspect.
This will deal with selecting the right ``__cause__`` or ``__context__``
@@ -1481,7 +1487,9 @@ def lineinfo(self, identifier):
f = self.lookupmodule(parts[0])
if f:
fname = f
- item = parts[1]
+ item = parts[1]
+ else:
+ return failed
answer = find_function(item, self.canonic(fname))
return answer or failed
@@ -1493,7 +1501,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)
@@ -2423,7 +2431,9 @@ def print_stack_trace(self, count=None):
except KeyboardInterrupt:
pass
- def print_stack_entry(self, frame_lineno, prompt_prefix=line_prefix):
+ def print_stack_entry(self, frame_lineno, prompt_prefix=None):
+ if prompt_prefix is None:
+ prompt_prefix = line_prefix
frame, lineno = frame_lineno
if frame is self.curframe:
prefix = '> '
@@ -3542,7 +3552,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 +3571,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,30 +3624,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)}")
-
- 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/pickle.py b/Lib/pickle.py
index 729c215514a..f3025776623 100644
--- a/Lib/pickle.py
+++ b/Lib/pickle.py
@@ -189,6 +189,11 @@ def __init__(self, value):
__all__.extend(x for x in dir() if x.isupper() and not x.startswith('_'))
+# Data larger than this will be read in chunks, to prevent extreme
+# overallocation.
+_MIN_READ_BUF_SIZE = (1 << 20)
+
+
class _Framer:
_FRAME_SIZE_MIN = 4
@@ -287,7 +292,7 @@ def read(self, n):
"pickle exhausted before end of frame")
return data
else:
- return self.file_read(n)
+ return self._chunked_file_read(n)
def readline(self):
if self.current_frame:
@@ -302,11 +307,23 @@ def readline(self):
else:
return self.file_readline()
+ def _chunked_file_read(self, size):
+ cursize = min(size, _MIN_READ_BUF_SIZE)
+ b = self.file_read(cursize)
+ while cursize < size and len(b) == cursize:
+ delta = min(cursize, size - cursize)
+ b += self.file_read(delta)
+ cursize += delta
+ return b
+
def load_frame(self, frame_size):
if self.current_frame and self.current_frame.read() != b'':
raise UnpicklingError(
"beginning of a new frame before end of current frame")
- self.current_frame = io.BytesIO(self.file_read(frame_size))
+ data = self._chunked_file_read(frame_size)
+ if len(data) < frame_size:
+ raise EOFError
+ self.current_frame = io.BytesIO(data)
# Tools used for pickling.
@@ -1496,12 +1513,17 @@ def load_binbytes8(self):
dispatch[BINBYTES8[0]] = load_binbytes8
def load_bytearray8(self):
- len, = unpack(' maxsize:
+ size, = unpack(' maxsize:
raise UnpicklingError("BYTEARRAY8 exceeds system's maximum size "
"of %d bytes" % maxsize)
- b = bytearray(len)
- self.readinto(b)
+ cursize = min(size, _MIN_READ_BUF_SIZE)
+ b = bytearray(cursize)
+ if self.readinto(b) == cursize:
+ while cursize < size and len(b) == cursize:
+ delta = min(cursize, size - cursize)
+ b += self.read(delta)
+ cursize += delta
self.append(b)
dispatch[BYTEARRAY8[0]] = load_bytearray8
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/plistlib.py b/Lib/plistlib.py
index 67e832db217..655c51eea3d 100644
--- a/Lib/plistlib.py
+++ b/Lib/plistlib.py
@@ -73,6 +73,9 @@
PlistFormat = enum.Enum('PlistFormat', 'FMT_XML FMT_BINARY', module=__name__)
globals().update(PlistFormat.__members__)
+# Data larger than this will be read in chunks, to prevent extreme
+# overallocation.
+_MIN_READ_BUF_SIZE = 1 << 20
class UID:
def __init__(self, data):
@@ -508,12 +511,24 @@ def _get_size(self, tokenL):
return tokenL
+ def _read(self, size):
+ cursize = min(size, _MIN_READ_BUF_SIZE)
+ data = self._fp.read(cursize)
+ while True:
+ if len(data) != cursize:
+ raise InvalidFileException
+ if cursize == size:
+ return data
+ delta = min(cursize, size - cursize)
+ data += self._fp.read(delta)
+ cursize += delta
+
def _read_ints(self, n, size):
- data = self._fp.read(size * n)
+ data = self._read(size * n)
if size in _BINARY_FORMAT:
return struct.unpack(f'>{n}{_BINARY_FORMAT[size]}', data)
else:
- if not size or len(data) != size * n:
+ if not size:
raise InvalidFileException()
return tuple(int.from_bytes(data[i: i + size], 'big')
for i in range(0, size * n, size))
@@ -573,22 +588,16 @@ def _read_object(self, ref):
elif tokenH == 0x40: # data
s = self._get_size(tokenL)
- result = self._fp.read(s)
- if len(result) != s:
- raise InvalidFileException()
+ result = self._read(s)
elif tokenH == 0x50: # ascii string
s = self._get_size(tokenL)
- data = self._fp.read(s)
- if len(data) != s:
- raise InvalidFileException()
+ data = self._read(s)
result = data.decode('ascii')
elif tokenH == 0x60: # unicode string
s = self._get_size(tokenL) * 2
- data = self._fp.read(s)
- if len(data) != s:
- raise InvalidFileException()
+ data = self._read(s)
result = data.decode('utf-16be')
elif tokenH == 0x80: # UID
diff --git a/Lib/profiling/sampling/__init__.py b/Lib/profiling/sampling/__init__.py
index b493c6aa7eb..6a0bb5e5c2f 100644
--- a/Lib/profiling/sampling/__init__.py
+++ b/Lib/profiling/sampling/__init__.py
@@ -7,7 +7,8 @@
from .collector import Collector
from .pstats_collector import PstatsCollector
from .stack_collector import CollapsedStackCollector
+from .heatmap_collector import HeatmapCollector
from .gecko_collector import GeckoCollector
from .string_table import StringTable
-__all__ = ("Collector", "PstatsCollector", "CollapsedStackCollector", "GeckoCollector", "StringTable")
+__all__ = ("Collector", "PstatsCollector", "CollapsedStackCollector", "HeatmapCollector", "GeckoCollector", "StringTable")
diff --git a/Lib/profiling/sampling/__main__.py b/Lib/profiling/sampling/__main__.py
index a76ca62e2cd..47bd3a0113e 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.
@@ -45,7 +45,7 @@
system restrictions or missing privileges.
"""
-from .sample import main
+from .cli import main
def handle_permission_error():
"""Handle PermissionError by displaying appropriate error message."""
diff --git a/Lib/profiling/sampling/_css_utils.py b/Lib/profiling/sampling/_css_utils.py
new file mode 100644
index 00000000000..40912e9b352
--- /dev/null
+++ b/Lib/profiling/sampling/_css_utils.py
@@ -0,0 +1,22 @@
+import importlib.resources
+
+
+def get_combined_css(component: str) -> str:
+ template_dir = importlib.resources.files(__package__)
+
+ base_css = (template_dir / "_shared_assets" / "base.css").read_text(encoding="utf-8")
+
+ if component == "flamegraph":
+ component_css = (
+ template_dir / "_flamegraph_assets" / "flamegraph.css"
+ ).read_text(encoding="utf-8")
+ elif component == "heatmap":
+ component_css = (template_dir / "_heatmap_assets" / "heatmap.css").read_text(
+ encoding="utf-8"
+ )
+ else:
+ raise ValueError(
+ f"Unknown component: {component}. Expected 'flamegraph' or 'heatmap'."
+ )
+
+ return f"{base_css}\n\n{component_css}"
diff --git a/Lib/profiling/sampling/_flamegraph_assets/flamegraph.css b/Lib/profiling/sampling/_flamegraph_assets/flamegraph.css
new file mode 100644
index 00000000000..c75f2324b6d
--- /dev/null
+++ b/Lib/profiling/sampling/_flamegraph_assets/flamegraph.css
@@ -0,0 +1,901 @@
+/* ==========================================================================
+ Flamegraph Viewer - Component-Specific CSS
+
+ DEPENDENCY: Requires _shared_assets/base.css to be loaded first
+ This file extends the shared foundation with flamegraph-specific styles.
+ ========================================================================== */
+
+/* --------------------------------------------------------------------------
+ Layout Overrides (Flamegraph-specific)
+ -------------------------------------------------------------------------- */
+
+html, body {
+ height: 100%;
+ overflow: hidden;
+}
+
+.app-layout {
+ height: 100vh;
+}
+
+.main-content {
+ display: flex;
+ flex: 1;
+ min-height: 0;
+}
+
+/* --------------------------------------------------------------------------
+ Search Input (Flamegraph-specific)
+ -------------------------------------------------------------------------- */
+
+.search-wrapper {
+ flex: 1;
+ max-width: 360px;
+ position: relative;
+}
+
+.search-input {
+ width: 100%;
+ padding: 8px 36px 8px 14px;
+ font-family: var(--font-sans);
+ font-size: 13px;
+ color: #2e3338;
+ background: rgba(255, 255, 255, 0.95);
+ border: 2px solid rgba(255, 255, 255, 0.3);
+ border-radius: 20px;
+ outline: none;
+ transition: all var(--transition-fast);
+ box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
+}
+
+.search-input::placeholder {
+ color: #6c757d;
+}
+
+.search-input:focus {
+ border-color: rgba(255, 255, 255, 0.8);
+ background: white;
+ box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
+}
+
+/* Dark theme search input */
+[data-theme="dark"] .search-input {
+ color: #e6edf3;
+ background: rgba(33, 38, 45, 0.95);
+ border: 2px solid rgba(88, 166, 255, 0.3);
+ box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
+}
+
+[data-theme="dark"] .search-input::placeholder {
+ color: #8b949e;
+}
+
+[data-theme="dark"] .search-input:focus {
+ border-color: rgba(88, 166, 255, 0.6);
+ background: rgba(33, 38, 45, 1);
+ box-shadow: 0 4px 16px rgba(88, 166, 255, 0.2);
+}
+
+.search-input.has-matches {
+ border-color: rgba(40, 167, 69, 0.8);
+ box-shadow: 0 4px 16px rgba(40, 167, 69, 0.2);
+}
+
+.search-input.no-matches {
+ border-color: rgba(220, 53, 69, 0.8);
+ box-shadow: 0 4px 16px rgba(220, 53, 69, 0.2);
+}
+
+.search-clear {
+ position: absolute;
+ right: 10px;
+ top: 50%;
+ transform: translateY(-50%);
+ width: 20px;
+ height: 20px;
+ padding: 0;
+ display: none;
+ align-items: center;
+ justify-content: center;
+ font-size: 14px;
+ line-height: 1;
+ color: #6c757d;
+ background: transparent;
+ border: none;
+ border-radius: 50%;
+ cursor: pointer;
+ transition: color var(--transition-fast);
+}
+
+.search-clear:hover {
+ color: #2e3338;
+}
+
+[data-theme="dark"] .search-clear {
+ color: #8b949e;
+}
+
+[data-theme="dark"] .search-clear:hover {
+ color: #e6edf3;
+}
+
+.search-wrapper.has-value .search-clear {
+ display: flex;
+}
+
+/* --------------------------------------------------------------------------
+ Sidebar
+ -------------------------------------------------------------------------- */
+
+.sidebar {
+ width: var(--sidebar-width);
+ background: var(--bg-secondary);
+ border-right: 1px solid var(--border);
+ display: flex;
+ flex-direction: column;
+ flex-shrink: 0;
+ overflow: hidden;
+ position: relative;
+}
+
+.sidebar.collapsed {
+ width: var(--sidebar-collapsed) !important;
+ transition: width var(--transition-normal);
+}
+
+.sidebar-toggle {
+ position: absolute;
+ top: 12px;
+ right: 10px;
+ width: 26px;
+ height: 26px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ color: var(--text-muted);
+ background: var(--bg-primary);
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ cursor: pointer;
+ transition: all var(--transition-fast);
+ z-index: 10;
+}
+
+.sidebar-toggle svg {
+ transition: transform var(--transition-fast);
+}
+
+.sidebar-toggle:hover {
+ color: var(--accent);
+ border-color: var(--accent);
+ background: var(--accent-glow);
+}
+
+.sidebar.collapsed .sidebar-toggle {
+ right: 9px;
+}
+
+.sidebar.collapsed .sidebar-toggle svg {
+ transform: rotate(180deg);
+}
+
+.sidebar-content {
+ flex: 1;
+ overflow-y: auto;
+ padding: 44px 14px 14px;
+}
+
+.sidebar.collapsed .sidebar-content {
+ display: none;
+}
+
+.sidebar-resize-handle {
+ position: absolute;
+ top: 0;
+ right: 0;
+ width: 6px;
+ height: 100%;
+ cursor: col-resize;
+ background: transparent;
+ transition: background var(--transition-fast);
+ z-index: 11;
+}
+
+.sidebar-resize-handle:hover,
+.sidebar-resize-handle.resizing {
+ background: var(--python-gold);
+}
+
+.sidebar-resize-handle::before {
+ content: '';
+ position: absolute;
+ top: 50%;
+ left: 50%;
+ transform: translate(-50%, -50%);
+ width: 2px;
+ height: 40px;
+ background: var(--border);
+ border-radius: 1px;
+ opacity: 0;
+ transition: opacity var(--transition-fast);
+}
+
+.sidebar-resize-handle:hover::before {
+ opacity: 1;
+}
+
+.sidebar.collapsed .sidebar-resize-handle {
+ display: none;
+}
+
+body.resizing-sidebar {
+ cursor: col-resize;
+ user-select: none;
+}
+
+/* Sidebar Logo */
+.sidebar-logo {
+ display: flex;
+ justify-content: center;
+ margin-bottom: 16px;
+}
+
+.sidebar-logo-img {
+ width: 90px;
+ height: 90px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+}
+
+.sidebar-logo-img svg,
+.sidebar-logo-img img {
+ width: 100%;
+ height: 100%;
+ object-fit: contain;
+}
+
+/* Sidebar sections */
+.sidebar-section {
+ margin-bottom: 20px;
+}
+
+.sidebar-section:last-child {
+ margin-bottom: 0;
+}
+
+.section-title {
+ font-size: 10px;
+ font-weight: 700;
+ text-transform: uppercase;
+ letter-spacing: 0.8px;
+ color: var(--accent);
+ margin: 0;
+ flex: 1;
+}
+
+/* Collapsible sections */
+.collapsible .section-header {
+ display: flex;
+ align-items: center;
+ width: 100%;
+ padding: 0 0 8px 0;
+ margin-bottom: 10px;
+ background: none;
+ border: none;
+ border-bottom: 2px solid var(--python-gold);
+ cursor: pointer;
+ transition: all var(--transition-fast);
+}
+
+.collapsible .section-header:hover {
+ opacity: 0.8;
+}
+
+.section-chevron {
+ color: var(--text-muted);
+ transition: transform var(--transition-fast);
+}
+
+.collapsible.collapsed .section-chevron {
+ transform: rotate(-90deg);
+}
+
+.section-content {
+ overflow: hidden;
+ transition: max-height var(--transition-normal), opacity var(--transition-normal);
+ max-height: 1000px;
+ opacity: 1;
+}
+
+.collapsible.collapsed .section-content {
+ max-height: 0;
+ opacity: 0;
+ margin-bottom: -10px;
+}
+
+/* --------------------------------------------------------------------------
+ Profile Summary Cards
+ -------------------------------------------------------------------------- */
+
+.summary-grid {
+ display: grid;
+ grid-template-columns: 1fr 1fr;
+ gap: 6px;
+}
+
+.summary-card {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 8px 10px;
+ background: var(--bg-primary);
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ transition: all var(--transition-fast);
+ animation: slideUp 0.4s ease-out backwards;
+ animation-delay: calc(var(--i, 0) * 0.05s);
+ overflow: hidden;
+}
+
+.summary-card:nth-child(1) { --i: 0; }
+.summary-card:nth-child(2) { --i: 1; }
+.summary-card:nth-child(3) { --i: 2; }
+.summary-card:nth-child(4) { --i: 3; }
+
+.summary-card:hover {
+ border-color: var(--accent);
+ background: var(--accent-glow);
+}
+
+.summary-icon {
+ font-size: 16px;
+ width: 28px;
+ height: 28px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ background: var(--bg-tertiary);
+ border-radius: 6px;
+ flex-shrink: 0;
+}
+
+.summary-data {
+ min-width: 0;
+ flex: 1;
+ overflow: hidden;
+}
+
+.summary-value {
+ font-family: var(--font-mono);
+ font-size: 13px;
+ font-weight: 700;
+ color: var(--accent);
+ line-height: 1.2;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+
+.summary-label {
+ font-size: 8px;
+ font-weight: 600;
+ color: var(--text-muted);
+ text-transform: uppercase;
+ letter-spacing: 0.2px;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+
+/* Efficiency Bar */
+.efficiency-section {
+ margin-top: 10px;
+ padding-top: 10px;
+ border-top: 1px solid var(--border);
+}
+
+.efficiency-header {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ margin-bottom: 5px;
+}
+
+.efficiency-label {
+ font-size: 9px;
+ font-weight: 600;
+ color: var(--text-secondary);
+ text-transform: uppercase;
+ letter-spacing: 0.2px;
+}
+
+.efficiency-value {
+ font-family: var(--font-mono);
+ font-size: 11px;
+ font-weight: 700;
+ color: var(--accent);
+}
+
+.efficiency-bar {
+ height: 6px;
+ background: var(--bg-tertiary);
+ border-radius: 3px;
+ overflow: hidden;
+}
+
+.efficiency-fill {
+ height: 100%;
+ background: linear-gradient(90deg, #28a745 0%, #20c997 50%, #17a2b8 100%);
+ border-radius: 3px;
+ transition: width 0.6s ease-out;
+ position: relative;
+ overflow: hidden;
+}
+
+.efficiency-fill::after {
+ content: '';
+ position: absolute;
+ top: 0;
+ left: -100%;
+ width: 100%;
+ height: 100%;
+ background: linear-gradient(
+ 90deg,
+ transparent 0%,
+ rgba(255, 255, 255, 0.4) 50%,
+ transparent 100%
+ );
+ animation: shimmer 2s ease-in-out infinite;
+}
+
+/* --------------------------------------------------------------------------
+ Thread Stats Grid (in Sidebar)
+ -------------------------------------------------------------------------- */
+
+.thread-stats-section {
+ display: block;
+}
+
+.stats-grid {
+ display: grid;
+ grid-template-columns: 1fr 1fr;
+ gap: 8px;
+}
+
+.stat-tile {
+ background: var(--bg-primary);
+ border-radius: 8px;
+ padding: 10px;
+ text-align: center;
+ border: 2px solid var(--border);
+ transition: all var(--transition-fast);
+ animation: fadeIn 0.4s ease-out backwards;
+ animation-delay: calc(var(--i, 0) * 0.05s);
+}
+
+.stat-tile:nth-child(1) { --i: 0; }
+.stat-tile:nth-child(2) { --i: 1; }
+.stat-tile:nth-child(3) { --i: 2; }
+.stat-tile:nth-child(4) { --i: 3; }
+
+.stat-tile:hover {
+ transform: translateY(-2px);
+ box-shadow: var(--shadow-sm);
+}
+
+.stat-tile-value {
+ font-family: var(--font-mono);
+ font-size: 16px;
+ font-weight: 700;
+ color: var(--text-primary);
+ line-height: 1.2;
+}
+
+.stat-tile-label {
+ font-size: 9px;
+ font-weight: 600;
+ text-transform: uppercase;
+ letter-spacing: 0.3px;
+ color: var(--text-muted);
+ margin-top: 2px;
+}
+
+/* Stat tile color variants */
+.stat-tile--green { --tile-color: 40, 167, 69; --tile-text: #28a745; }
+.stat-tile--red { --tile-color: 220, 53, 69; --tile-text: #dc3545; }
+.stat-tile--yellow { --tile-color: 255, 193, 7; --tile-text: #d39e00; }
+.stat-tile--purple { --tile-color: 111, 66, 193; --tile-text: #6f42c1; }
+
+.stat-tile[class*="--"] {
+ border-color: rgba(var(--tile-color), 0.4);
+ background: linear-gradient(135deg, rgba(var(--tile-color), 0.08) 0%, var(--bg-primary) 100%);
+}
+.stat-tile[class*="--"] .stat-tile-value { color: var(--tile-text); }
+
+/* --------------------------------------------------------------------------
+ Hotspot Cards
+ -------------------------------------------------------------------------- */
+
+.hotspot {
+ display: flex;
+ align-items: flex-start;
+ gap: 10px;
+ padding: 10px;
+ margin-bottom: 8px;
+ background: var(--bg-primary);
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ cursor: pointer;
+ transition: all var(--transition-fast);
+ opacity: 0;
+ transform: translateY(8px);
+ box-shadow: var(--shadow-sm);
+}
+
+.hotspot.visible {
+ opacity: 1;
+ transform: translateY(0);
+}
+
+.hotspot:hover {
+ border-color: var(--accent);
+ box-shadow: var(--shadow-md);
+ transform: translateY(-2px);
+}
+
+.hotspot.active {
+ border-color: var(--python-gold);
+ background: var(--accent-glow);
+ box-shadow: 0 0 0 3px var(--accent-glow);
+}
+
+.hotspot:last-child {
+ margin-bottom: 0;
+}
+
+.hotspot-rank {
+ width: 26px;
+ height: 26px;
+ border-radius: 50%;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ font-weight: 700;
+ font-size: 12px;
+ flex-shrink: 0;
+ background: linear-gradient(135deg, var(--python-blue) 0%, var(--python-blue-light) 100%);
+ color: white;
+ box-shadow: 0 2px 4px rgba(55, 118, 171, 0.3);
+}
+
+.hotspot-rank--1 { background: linear-gradient(135deg, #d4af37, #f4d03f); color: #5a4a00; }
+.hotspot-rank--2 { background: linear-gradient(135deg, #a8a8a8, #c0c0c0); color: #4a4a4a; }
+.hotspot-rank--3 { background: linear-gradient(135deg, #cd7f32, #e6a55a); color: #5a3d00; }
+
+.hotspot-info {
+ flex: 1;
+ min-width: 0;
+}
+
+.hotspot-func {
+ font-family: var(--font-mono);
+ font-size: 11px;
+ font-weight: 600;
+ color: var(--text-primary);
+ line-height: 1.3;
+ word-break: break-word;
+ margin-bottom: 2px;
+}
+
+.hotspot-file {
+ font-family: var(--font-mono);
+ font-size: 10px;
+ color: var(--text-muted);
+ margin-bottom: 3px;
+ word-break: break-all;
+}
+
+.hotspot-stats {
+ font-family: var(--font-mono);
+ font-size: 10px;
+ color: var(--text-secondary);
+}
+
+.hotspot-percent {
+ color: var(--accent);
+ font-weight: 600;
+}
+
+/* --------------------------------------------------------------------------
+ Legend
+ -------------------------------------------------------------------------- */
+
+.legend-section {
+ margin-top: auto;
+ padding-top: 12px;
+}
+
+.legend {
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+}
+
+.legend-item {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 5px 8px;
+ background: var(--bg-primary);
+ border-radius: 4px;
+ border: 1px solid var(--border-subtle);
+ font-size: 11px;
+}
+
+.legend-color {
+ width: 20px;
+ height: 10px;
+ border-radius: 2px;
+ flex-shrink: 0;
+ border: 1px solid rgba(0, 0, 0, 0.08);
+}
+
+.legend-label {
+ color: var(--text-primary);
+ font-weight: 500;
+ flex: 1;
+}
+
+.legend-range {
+ font-family: var(--font-mono);
+ font-size: 9px;
+ color: var(--text-muted);
+}
+
+/* --------------------------------------------------------------------------
+ Thread Filter
+ -------------------------------------------------------------------------- */
+
+.filter-section {
+ padding-top: 12px;
+ border-top: 1px solid var(--border);
+}
+
+.filter-label {
+ display: block;
+ font-size: 10px;
+ font-weight: 600;
+ color: var(--text-muted);
+ margin-bottom: 6px;
+}
+
+.filter-select {
+ width: 100%;
+ padding: 7px 28px 7px 10px;
+ font-family: var(--font-mono);
+ font-size: 11px;
+ color: var(--text-primary);
+ background: var(--bg-primary);
+ border: 2px solid var(--accent);
+ border-radius: 6px;
+ cursor: pointer;
+ outline: none;
+ appearance: none;
+ background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%233776ab' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3e%3cpolyline points='6 9 12 15 18 9'%3e%3c/polyline%3e%3c/svg%3e");
+ background-repeat: no-repeat;
+ background-position: right 6px center;
+ background-size: 14px;
+ transition: all var(--transition-fast);
+}
+
+.filter-select:hover {
+ border-color: var(--accent-hover);
+ box-shadow: 0 2px 6px var(--accent-glow);
+}
+
+.filter-select:focus {
+ border-color: var(--accent);
+ box-shadow: 0 0 0 3px var(--accent-glow);
+}
+
+/* --------------------------------------------------------------------------
+ Chart Area
+ -------------------------------------------------------------------------- */
+
+.chart-area {
+ flex: 1;
+ min-width: 0;
+ overflow: hidden;
+ background: var(--bg-primary);
+ position: relative;
+}
+
+#chart {
+ width: 100%;
+ height: 100%;
+ padding: 16px;
+ overflow: auto;
+}
+
+/* D3 Flamegraph overrides */
+.d3-flame-graph rect {
+ stroke: rgba(55, 118, 171, 0.3);
+ stroke-width: 1px;
+ cursor: pointer;
+ transition: filter 0.1s ease;
+}
+
+.d3-flame-graph rect:hover {
+ stroke: var(--python-blue);
+ stroke-width: 2px;
+ filter: brightness(1.08);
+}
+
+.d3-flame-graph text {
+ font-family: var(--font-sans);
+ font-size: 12px;
+ font-weight: 500;
+ fill: var(--text-primary);
+ pointer-events: none;
+}
+
+/* Search highlight */
+.d3-flame-graph rect.search-match {
+ stroke: #ff6b35 !important;
+ stroke-width: 2px !important;
+ stroke-dasharray: 4 2;
+}
+
+.d3-flame-graph rect.search-dim {
+ opacity: 0.25;
+}
+
+/* --------------------------------------------------------------------------
+ Tooltip
+ -------------------------------------------------------------------------- */
+
+.python-tooltip {
+ position: absolute;
+ z-index: 1000;
+ pointer-events: none;
+ background: var(--bg-primary);
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ padding: 14px;
+ max-width: 480px;
+ box-shadow: var(--shadow-lg);
+ font-family: var(--font-sans);
+ font-size: 13px;
+ color: var(--text-primary);
+ word-wrap: break-word;
+ overflow-wrap: break-word;
+ line-height: 1.5;
+}
+
+.tooltip-header {
+ margin-bottom: 10px;
+}
+
+.tooltip-title {
+ font-size: 14px;
+ font-weight: 600;
+ color: var(--accent);
+ line-height: 1.3;
+ word-break: break-word;
+ margin-bottom: 4px;
+}
+
+.tooltip-location {
+ font-family: var(--font-mono);
+ font-size: 11px;
+ color: var(--text-muted);
+ background: var(--bg-tertiary);
+ padding: 4px 8px;
+ border-radius: 4px;
+ word-break: break-all;
+}
+
+.tooltip-stats {
+ display: grid;
+ grid-template-columns: auto 1fr;
+ gap: 4px 14px;
+ font-size: 12px;
+}
+
+.tooltip-stat-label {
+ color: var(--text-secondary);
+ font-weight: 500;
+}
+
+.tooltip-stat-value {
+ color: var(--text-primary);
+ font-weight: 600;
+}
+
+.tooltip-stat-value.accent {
+ color: var(--accent);
+}
+
+.tooltip-source {
+ margin-top: 10px;
+ padding-top: 10px;
+ border-top: 1px solid var(--border);
+}
+
+.tooltip-source-title {
+ font-size: 11px;
+ font-weight: 600;
+ color: var(--accent);
+ margin-bottom: 6px;
+}
+
+.tooltip-source-code {
+ font-family: var(--font-mono);
+ font-size: 10px;
+ line-height: 1.5;
+ background: var(--bg-tertiary);
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ padding: 8px;
+ max-height: 140px;
+ overflow-y: auto;
+ white-space: pre-wrap;
+ word-break: break-all;
+}
+
+.tooltip-source-line {
+ color: var(--text-secondary);
+ padding: 1px 0;
+}
+
+.tooltip-source-line.current {
+ color: var(--accent);
+ font-weight: 600;
+}
+
+.tooltip-hint {
+ margin-top: 10px;
+ padding-top: 8px;
+ border-top: 1px solid var(--border);
+ font-size: 11px;
+ color: var(--text-muted);
+ text-align: center;
+}
+
+/* --------------------------------------------------------------------------
+ Responsive (Flamegraph-specific)
+ -------------------------------------------------------------------------- */
+
+@media (max-width: 900px) {
+ .sidebar {
+ position: fixed;
+ left: 0;
+ top: var(--topbar-height);
+ bottom: var(--statusbar-height);
+ z-index: 100;
+ box-shadow: var(--shadow-lg);
+ }
+
+ .sidebar.collapsed {
+ width: var(--sidebar-collapsed);
+ }
+
+ .search-wrapper {
+ max-width: 220px;
+ }
+}
+
+@media (max-width: 600px) {
+ .search-wrapper {
+ max-width: 160px;
+ }
+
+ .brand-info {
+ display: none;
+ }
+
+ .stats-grid {
+ grid-template-columns: 1fr;
+ }
+}
diff --git a/Lib/profiling/sampling/_flamegraph_assets/flamegraph.js b/Lib/profiling/sampling/_flamegraph_assets/flamegraph.js
new file mode 100644
index 00000000000..494d156a8dd
--- /dev/null
+++ b/Lib/profiling/sampling/_flamegraph_assets/flamegraph.js
@@ -0,0 +1,1012 @@
+const EMBEDDED_DATA = {{FLAMEGRAPH_DATA}};
+
+// Global string table for resolving string indices
+let stringTable = [];
+let originalData = null;
+let currentThreadFilter = 'all';
+
+// Heat colors are now defined in CSS variables (--heat-1 through --heat-8)
+// and automatically switch with theme changes - no JS color arrays needed!
+
+// ============================================================================
+// String Resolution
+// ============================================================================
+
+function resolveString(index) {
+ if (index === null || index === undefined) {
+ return null;
+ }
+ if (typeof index === 'number' && index >= 0 && index < stringTable.length) {
+ return stringTable[index];
+ }
+ return String(index);
+}
+
+function resolveStringIndices(node) {
+ if (!node) return node;
+
+ const resolved = { ...node };
+
+ if (typeof resolved.name === 'number') {
+ resolved.name = resolveString(resolved.name);
+ }
+ if (typeof resolved.filename === 'number') {
+ resolved.filename = resolveString(resolved.filename);
+ }
+ if (typeof resolved.funcname === 'number') {
+ resolved.funcname = resolveString(resolved.funcname);
+ }
+
+ if (Array.isArray(resolved.source)) {
+ resolved.source = resolved.source.map(index =>
+ typeof index === 'number' ? resolveString(index) : index
+ );
+ }
+
+ if (Array.isArray(resolved.children)) {
+ resolved.children = resolved.children.map(child => resolveStringIndices(child));
+ }
+
+ return resolved;
+}
+
+// ============================================================================
+// Theme & UI Controls
+// ============================================================================
+
+function toggleTheme() {
+ const html = document.documentElement;
+ const current = html.getAttribute('data-theme') || 'light';
+ const next = current === 'light' ? 'dark' : 'light';
+ html.setAttribute('data-theme', next);
+ localStorage.setItem('flamegraph-theme', next);
+
+ // Update theme button icon
+ const btn = document.getElementById('theme-btn');
+ if (btn) {
+ btn.innerHTML = next === 'dark' ? '☼' : '☾'; // sun or moon
+ }
+
+ // Re-render flamegraph with new theme colors
+ if (window.flamegraphData && originalData) {
+ const tooltip = createPythonTooltip(originalData);
+ const chart = createFlamegraph(tooltip, originalData.value);
+ renderFlamegraph(chart, window.flamegraphData);
+ }
+}
+
+function toggleSidebar() {
+ const sidebar = document.getElementById('sidebar');
+ if (sidebar) {
+ const isCollapsing = !sidebar.classList.contains('collapsed');
+
+ if (isCollapsing) {
+ // Save current width before collapsing
+ const currentWidth = sidebar.offsetWidth;
+ sidebar.dataset.expandedWidth = currentWidth;
+ localStorage.setItem('flamegraph-sidebar-width', currentWidth);
+ } else {
+ // Restore width when expanding
+ const savedWidth = sidebar.dataset.expandedWidth || localStorage.getItem('flamegraph-sidebar-width');
+ if (savedWidth) {
+ sidebar.style.width = savedWidth + 'px';
+ }
+ }
+
+ sidebar.classList.toggle('collapsed');
+ localStorage.setItem('flamegraph-sidebar', sidebar.classList.contains('collapsed') ? 'collapsed' : 'expanded');
+
+ // Resize chart after sidebar animation
+ setTimeout(() => {
+ resizeChart();
+ }, 300);
+ }
+}
+
+function resizeChart() {
+ if (window.flamegraphChart && window.flamegraphData) {
+ const chartArea = document.querySelector('.chart-area');
+ if (chartArea) {
+ window.flamegraphChart.width(chartArea.clientWidth - 32);
+ d3.select("#chart").datum(window.flamegraphData).call(window.flamegraphChart);
+ }
+ }
+}
+
+function toggleSection(sectionId) {
+ const section = document.getElementById(sectionId);
+ if (section) {
+ section.classList.toggle('collapsed');
+ // Save state
+ const collapsedSections = JSON.parse(localStorage.getItem('flamegraph-collapsed-sections') || '{}');
+ collapsedSections[sectionId] = section.classList.contains('collapsed');
+ localStorage.setItem('flamegraph-collapsed-sections', JSON.stringify(collapsedSections));
+ }
+}
+
+function restoreUIState() {
+ // Restore theme
+ const savedTheme = localStorage.getItem('flamegraph-theme');
+ if (savedTheme) {
+ document.documentElement.setAttribute('data-theme', savedTheme);
+ const btn = document.getElementById('theme-btn');
+ if (btn) {
+ btn.innerHTML = savedTheme === 'dark' ? '☼' : '☾';
+ }
+ }
+
+ // Restore sidebar state
+ const savedSidebar = localStorage.getItem('flamegraph-sidebar');
+ if (savedSidebar === 'collapsed') {
+ const sidebar = document.getElementById('sidebar');
+ if (sidebar) sidebar.classList.add('collapsed');
+ }
+
+ // Restore sidebar width
+ const savedWidth = localStorage.getItem('flamegraph-sidebar-width');
+ if (savedWidth) {
+ const sidebar = document.getElementById('sidebar');
+ if (sidebar) {
+ sidebar.style.width = savedWidth + 'px';
+ }
+ }
+
+ // Restore collapsed sections
+ const collapsedSections = JSON.parse(localStorage.getItem('flamegraph-collapsed-sections') || '{}');
+ for (const [sectionId, isCollapsed] of Object.entries(collapsedSections)) {
+ if (isCollapsed) {
+ const section = document.getElementById(sectionId);
+ if (section) section.classList.add('collapsed');
+ }
+ }
+}
+
+// ============================================================================
+// Status Bar
+// ============================================================================
+
+function updateStatusBar(nodeData, rootValue) {
+ const funcname = resolveString(nodeData.funcname) || resolveString(nodeData.name) || "--";
+ const filename = resolveString(nodeData.filename) || "";
+ const lineno = nodeData.lineno;
+ const timeMs = (nodeData.value / 1000).toFixed(2);
+ const percent = rootValue > 0 ? ((nodeData.value / rootValue) * 100).toFixed(1) : "0.0";
+
+ const locationEl = document.getElementById('status-location');
+ const funcItem = document.getElementById('status-func-item');
+ const timeItem = document.getElementById('status-time-item');
+ const percentItem = document.getElementById('status-percent-item');
+
+ if (locationEl) locationEl.style.display = filename && filename !== "~" ? 'flex' : 'none';
+ if (funcItem) funcItem.style.display = 'flex';
+ if (timeItem) timeItem.style.display = 'flex';
+ if (percentItem) percentItem.style.display = 'flex';
+
+ const fileEl = document.getElementById('status-file');
+ if (fileEl && filename && filename !== "~") {
+ const basename = filename.split('/').pop();
+ fileEl.textContent = lineno ? `${basename}:${lineno}` : basename;
+ }
+
+ const funcEl = document.getElementById('status-func');
+ if (funcEl) funcEl.textContent = funcname.length > 40 ? funcname.substring(0, 37) + '...' : funcname;
+
+ const timeEl = document.getElementById('status-time');
+ if (timeEl) timeEl.textContent = `${timeMs} ms`;
+
+ const percentEl = document.getElementById('status-percent');
+ if (percentEl) percentEl.textContent = `${percent}%`;
+}
+
+function clearStatusBar() {
+ const ids = ['status-location', 'status-func-item', 'status-time-item', 'status-percent-item'];
+ ids.forEach(id => {
+ const el = document.getElementById(id);
+ if (el) el.style.display = 'none';
+ });
+}
+
+// ============================================================================
+// Tooltip
+// ============================================================================
+
+function createPythonTooltip(data) {
+ const pythonTooltip = flamegraph.tooltip.defaultFlamegraphTooltip();
+
+ pythonTooltip.show = function (d, element) {
+ if (!this._tooltip) {
+ this._tooltip = d3.select("body")
+ .append("div")
+ .attr("class", "python-tooltip")
+ .style("opacity", 0);
+ }
+
+ const timeMs = (d.data.value / 1000).toFixed(2);
+ const percentage = ((d.data.value / data.value) * 100).toFixed(2);
+ const calls = d.data.calls || 0;
+ const childCount = d.children ? d.children.length : 0;
+ const source = d.data.source;
+
+ const funcname = resolveString(d.data.funcname) || resolveString(d.data.name);
+ const filename = resolveString(d.data.filename) || "";
+ const isSpecialFrame = filename === "~";
+
+ // Build source section
+ let sourceSection = "";
+ if (source && Array.isArray(source) && source.length > 0) {
+ const sourceLines = source
+ .map((line) => {
+ const isCurrent = line.startsWith("→");
+ const escaped = line.replace(/&/g, "&").replace(//g, ">");
+ return `