Update typeshed version to f8773eb27a29946d3c56dbdcb683c7e6413dbf21

GitOrigin-RevId: adc61539e24fdf9b9d895546cc70a0c8870c9659
This commit is contained in:
PyCharm Automation Bot
2025-09-02 13:32:35 +00:00
committed by intellij-monorepo-bot
parent 232f33f2ec
commit cadd0b15df
1436 changed files with 27226 additions and 10135 deletions
+1 -2
View File
@@ -1,7 +1,6 @@
[flake8]
# Y: Flake8 is only used to run flake8-pyi, everything else is in Ruff
# F821: Typeshed is a testing ground for flake8-pyi, which monkeypatches F821
select = Y, F821
select = Y
# Ignore rules normally excluded by default
extend-ignore = Y090,Y091
per-file-ignores =
-1
View File
@@ -4,6 +4,5 @@
# Set linguist-language to support comments syntax highlight
**/stubtest_allowlist*.txt linguist-language=ini
**/stubtest_allowlists/*.txt linguist-language=ini
tests/pytype_exclude_list.txt linguist-language=ini
pyrightconfig*.json linguist-language=jsonc
.vscode/*.json linguist-language=jsonc
+4 -4
View File
@@ -24,15 +24,15 @@
{
groupName: "most test/lint dependencies",
matchManagers: ["pip_requirements", "pre-commit"],
matchPackageNames: ["!pytype", "!pyright"],
matchPackageNames: ["!pyright"],
description: "Quarterly update of most test dependencies",
schedule: ["every 3 months on the first day of the month"]
},
{
"groupName": "pytype and pyright",
"groupName": "pyright",
"matchManagers": ["pip_requirements"],
"matchPackageNames": ["pytype", "pyright"],
"description": "Daily update of pyright and pytype",
"matchPackageNames": ["pyright"],
"description": "Daily update of pyright",
"schedule": ["before 4am"]
}
]
+6 -1
View File
@@ -80,23 +80,26 @@ jobs:
if [ "${{ runner.os }}" = "Linux" ]; then
if [ -n "$PACKAGES" ]; then
printf "Installing APT packages:\n $(echo $PACKAGES | sed 's/ /\n /g')\n"
sudo apt-get update -q && sudo apt-get install -qy $PACKAGES
fi
PYTHON_EXECUTABLE="xvfb-run python"
else
if [ "${{ runner.os }}" = "macOS" ] && [ -n "$PACKAGES" ]; then
printf "Installing Homebrew packages:\n $(echo $PACKAGES | sed 's/ /\n /g')\n"
brew install -q $PACKAGES
fi
if [ "${{ runner.os }}" = "Windows" ] && [ -n "$PACKAGES" ]; then
printf "Installing Chocolatey packages:\n $(echo $PACKAGES | sed 's/ /\n /g')\n"
choco install -y $PACKAGES
fi
PYTHON_EXECUTABLE="python"
fi
$PYTHON_EXECUTABLE tests/stubtest_third_party.py --specified-platforms-only --num-shards 4 --shard-index ${{ matrix.shard-index }}
$PYTHON_EXECUTABLE tests/stubtest_third_party.py --ci-platforms-only --num-shards 4 --shard-index ${{ matrix.shard-index }}
stub-uploader:
name: stub_uploader tests
@@ -117,6 +120,8 @@ jobs:
# Keep in sync with stub_uploader's check_scripts.yml workflow.
python-version: "3.13"
- uses: astral-sh/setup-uv@v6
with:
version-file: "typeshed/requirements-tests.txt"
- name: Run tests
run: |
cd stub_uploader
+10 -6
View File
@@ -39,7 +39,9 @@ jobs:
- uses: actions/setup-python@v5
with:
python-version: "3.13"
- run: curl -LsSf https://astral.sh/uv/install.sh | sh
- uses: astral-sh/setup-uv@v6
with:
version-file: "requirements-tests.txt"
- run: uv pip install -r requirements-tests.txt --system
- run: python ./tests/typecheck_typeshed.py --platform=${{ matrix.platform }}
pyright:
@@ -53,10 +55,10 @@ jobs:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
# TODO: Since pytype is not available for Python 3.13, and
# pytype_test.py imports pytype, we need to use Python 3.12 for now.
python-version: "3.12"
- run: curl -LsSf https://astral.sh/uv/install.sh | sh
python-version: "3.13"
- uses: astral-sh/setup-uv@v6
with:
version-file: "requirements-tests.txt"
- run: uv pip install -r requirements-tests.txt --system
- name: Run pyright on typeshed
uses: jakebailey/pyright-action@v2
@@ -73,7 +75,9 @@ jobs:
- uses: actions/setup-python@v5
with:
python-version: "3.13"
- run: curl -LsSf https://astral.sh/uv/install.sh | sh
- uses: astral-sh/setup-uv@v6
with:
version-file: "requirements-tests.txt"
- name: Git config
run: |
git config --global user.name stubsabot
+3 -1
View File
@@ -27,7 +27,9 @@ jobs:
- uses: actions/setup-python@v5
with:
python-version: "3.13"
- run: curl -LsSf https://astral.sh/uv/install.sh | sh
- uses: astral-sh/setup-uv@v6
with:
version-file: "requirements-tests.txt"
- name: git config
run: |
git config --global user.name stubsabot
@@ -66,26 +66,26 @@ jobs:
if [ "${{ runner.os }}" = "Linux" ]; then
if [ -n "$PACKAGES" ]; then
echo "Installing apt packages: $PACKAGES"
printf "Installing APT packages:\n $(echo $PACKAGES | sed 's/ /\n /g')\n"
sudo apt-get update -q && sudo apt-get install -qy $PACKAGES
fi
PYTHON_EXECUTABLE="xvfb-run python"
else
if [ "${{ runner.os }}" = "macOS" ] && [ -n "$PACKAGES" ]; then
echo "Installing Homebrew packages: $PACKAGES"
printf "Installing Homebrew packages:\n $(echo $PACKAGES | sed 's/ /\n /g')\n"
brew install -q $PACKAGES
fi
if [ "${{ runner.os }}" = "Windows" ] && [ -n "$PACKAGES" ]; then
echo "Installing Chocolatey packages: $PACKAGES"
printf "Installing Chocolatey packages:\n $(echo $PACKAGES | sed 's/ /\n /g')\n"
choco install -y $PACKAGES
fi
PYTHON_EXECUTABLE="python"
fi
$PYTHON_EXECUTABLE tests/stubtest_third_party.py --specified-platforms-only $STUBS
$PYTHON_EXECUTABLE tests/stubtest_third_party.py --ci-platforms-only $STUBS
else
echo "Nothing to test"
fi
+26 -39
View File
@@ -30,31 +30,12 @@ jobs:
- uses: actions/setup-python@v5
with:
python-version: "3.13"
- run: curl -LsSf https://astral.sh/uv/install.sh | sh
- uses: astral-sh/setup-uv@v6
with:
version-file: "requirements-tests.txt"
- run: uv pip install -r requirements-tests.txt --system
- run: python ./tests/check_typeshed_structure.py
pytype:
name: "pytype: Check stubs"
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
# Max supported Python version as of pytype 2024.10.11
python-version: "3.12"
- uses: astral-sh/setup-uv@v6
- run: uv pip install -r requirements-tests.txt --system
- name: Install external dependencies for 3rd-party stubs
run: |
DEPENDENCIES=$( python tests/get_external_stub_requirements.py )
if [ -n "$DEPENDENCIES" ]; then
printf "Installing packages:\n $(echo $DEPENDENCIES | sed 's/ /\n /g')\n"
uv pip install --system $DEPENDENCIES
fi
- run: uv pip freeze
- run: ./tests/pytype_test.py --print-stderr
mypy:
name: "mypy: Check stubs"
runs-on: ubuntu-latest
@@ -69,15 +50,16 @@ jobs:
- uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python-version }}
- run: curl -LsSf https://astral.sh/uv/install.sh | sh
- uses: astral-sh/setup-uv@v6
with:
version-file: "requirements-tests.txt"
- run: uv pip install -r requirements-tests.txt --system
- name: Install required APT packages
run: |
sudo apt-get update -qy
DEPENDENCIES=$( python tests/get_external_apt_dependencies.py )
if [ -n "$DEPENDENCIES" ]; then
printf "Installing APT packages:\n $(echo $DEPENDENCIES | sed 's/ /\n /g')\n"
sudo apt-get install -qy $DEPENDENCIES
PACKAGES=$(python tests/get_stubtest_system_requirements.py)
if [ -n "$PACKAGES" ]; then
printf "Installing APT packages:\n $(echo $PACKAGES | sed 's/ /\n /g')\n"
sudo apt-get update -q && sudo apt-get install -qy $PACKAGES
fi
- name: Run mypy_test.py
run: |
@@ -102,7 +84,9 @@ jobs:
# Use py311 for now, as py312 seems to be around 30s slower in CI
# TODO: figure out why that is (#11590)
python-version: "3.11"
- run: curl -LsSf https://astral.sh/uv/install.sh | sh
- uses: astral-sh/setup-uv@v6
with:
version-file: "requirements-tests.txt"
- run: uv pip install -r requirements-tests.txt --system
- run: python ./tests/regr_test.py --all --verbosity QUIET
@@ -120,25 +104,26 @@ jobs:
with:
python-version: "3.13"
- uses: astral-sh/setup-uv@v6
with:
version-file: "requirements-tests.txt"
- name: Install typeshed test-suite requirements
# Install these so we can run `get_external_stub_requirements.py`
# Install these so we can run `get_*_requirements.py`
run: uv pip install -r requirements-tests.txt --system
- name: Install required APT packages
run: |
sudo apt-get update -qy
DEPENDENCIES=$( python tests/get_external_apt_dependencies.py )
if [ -n "$DEPENDENCIES" ]; then
printf "Installing APT packages:\n $(echo $DEPENDENCIES | sed 's/ /\n /g')\n"
sudo apt-get install -qy $DEPENDENCIES
PACKAGES=$(python tests/get_stubtest_system_requirements.py)
if [ -n "$PACKAGES" ]; then
printf "Installing APT packages:\n $(echo $PACKAGES | sed 's/ /\n /g')\n"
sudo apt-get update -q && sudo apt-get install -qy $PACKAGES
fi
- name: Create an isolated venv for testing
run: uv venv .venv
- name: Install 3rd-party stub dependencies
run: |
DEPENDENCIES=$( python tests/get_external_stub_requirements.py )
if [ -n "$DEPENDENCIES" ]; then
printf "Installing packages:\n $(echo $DEPENDENCIES | sed 's/ /\n /g')\n"
uv pip install --python-version ${{ matrix.python-version }} $DEPENDENCIES
PACKAGES=$(python tests/get_external_stub_requirements.py)
if [ -n "$PACKAGES" ]; then
printf "Installing python packages:\n $(echo $PACKAGES | sed 's/ /\n /g')\n"
uv pip install --python-version ${{ matrix.python-version }} $PACKAGES
fi
- name: Activate the isolated venv for the rest of the job
run: echo "$PWD/.venv/bin" >> $GITHUB_PATH
@@ -186,6 +171,8 @@ jobs:
# Keep in sync with stub_uploader's check_scripts.yml workflow.
python-version: "3.13"
- uses: astral-sh/setup-uv@v6
with:
version-file: "typeshed/requirements-tests.txt"
- name: Run tests
run: |
cd stub_uploader
@@ -11,7 +11,7 @@ repos:
args: [--fix=lf]
- id: check-case-conflict
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.11.4 # must match requirements-tests.txt
rev: v0.12.2 # must match requirements-tests.txt
hooks:
- id: ruff
name: Run ruff on stubs, tests and scripts
@@ -31,7 +31,7 @@ repos:
hooks:
- id: black
- repo: https://github.com/pycqa/flake8
rev: 7.2.0
rev: 7.3.0
hooks:
- id: flake8
language: python
+14 -20
View File
@@ -77,19 +77,12 @@ Note that some tests require extra setup steps to install the required dependenc
Run the following commands from a Windows terminal to install all requirements:
```powershell
> python -m venv .venv
> py -m venv .venv
> .venv\Scripts\activate
(.venv) > pip install -U pip
(.venv) > python -m pip install -U pip
(.venv) > pip install -r requirements-tests.txt
```
To be able to run pytype tests, you'll also need to install it manually
as it's currently excluded from the requirements file:
```powershell
(.venv) > pip install -U pytype
```
</td>
</tr>
<tr><!-- disables zebra striping --></tr>
@@ -104,10 +97,6 @@ as it's currently excluded from the requirements file:
uv pip install -r requirements-tests.txt
```
```shell
uv pip install -U pytype
```
</td>
</tr>
</table>
@@ -224,18 +213,22 @@ This has the following keys:
that need to be installed for stubtest to run successfully
* `choco_dependencies` (default: `[]`): A list of Windows Chocolatey packages
that need to be installed for stubtest to run successfully
* `platforms` (default: `["linux"]`): A list of OSes on which to run stubtest.
Can contain `win32`, `linux`, and `darwin` values.
If not specified, stubtest is run only on `linux`.
Only add extra OSes to the test
if there are platform-specific branches in a stubs package.
* `supported_platforms` (default: all platforms): A list of OSes on which
stubtest can be run. When a package is not platform-specific, this should
not be set. If the package is platform-specific, this should usually be set
to the supported platforms, unless stubtest is known to fail on a
specific platform.
* `ci_platforms` (default: `["linux"]`): A list of OSes on which to run
stubtest as part of our continuous integration (CI) tests. Can contain
`win32`, `linux`, and `darwin` values. If not specified, stubtest is run
only on `linux`. Only add extra OSes to the test if there are
platform-specific branches in a stubs package.
* `mypy_plugins` (default: `[]`): A list of Python modules to use as mypy plugins
when running stubtest. For example: `mypy_plugins = ["mypy_django_plugin.main"]`
* `mypy_plugins_config` (default: `{}`): A dictionary mapping plugin names to their
configuration dictionaries for use by mypy plugins. For example:
`mypy_plugins_config = {"django-stubs" = {"django_settings_module" = "@tests.django_settings"}}`
`*_dependencies` are usually packages needed to `pip install` the implementation
distribution.
@@ -463,7 +456,8 @@ steps:
4. When a new version of the package was automatically uploaded to PyPI
(which can take up to a day), open a PR to remove the stubs.
If feeling kindly, please update [mypy](https://github.com/python/mypy/blob/master/mypy/stubinfo.py)
Don't forget to make sure the library is not in the [`pyrightconfig.stricter.json`](./pyrightconfig.stricter.json)
exclusion list. If feeling kindly, please update [mypy](https://github.com/python/mypy/blob/master/mypy/stubinfo.py)
for any stub obsoletions or removals.
### Marking PRs as "deferred"
+1
View File
@@ -5,6 +5,7 @@ At present the active maintainers are (alphabetically):
* Ivan Levkivskyi (@ilevkivskyi)
* Sebastian Rittau (@srittau)
* Guido van Rossum (@gvanrossum)
* Brian Schubert (@brianschubert)
* Shantanu (@hauntsaninja)
* Nikita Sobolev (@sobolevn)
* Samuel Therrien (@Avasam)
+3 -3
View File
@@ -25,9 +25,9 @@ Typeshed supports Python versions 3.9 to 3.14.
## Using
If you're just using a type checker ([mypy](https://github.com/python/mypy/),
[pyright](https://github.com/microsoft/pyright),
[pytype](https://github.com/google/pytype/), PyCharm, ...), as opposed to
If you're just using a type checker (e.g. [mypy](https://github.com/python/mypy/),
[pyright](https://github.com/microsoft/pyright), or PyCharm's built-in type
checker), as opposed to
developing it, you don't need to interact with the typeshed repo at
all: a copy of standard library part of typeshed is bundled with type checkers.
And type stubs for third party packages and modules you are using can
@@ -5,8 +5,10 @@
from __future__ import annotations
import datetime
import functools
import re
import sys
import urllib.parse
from collections.abc import Mapping
from dataclasses import dataclass
@@ -14,10 +16,15 @@ from pathlib import Path
from typing import Annotated, Any, Final, NamedTuple, final
from typing_extensions import TypeGuard
import tomli
if sys.version_info >= (3, 11):
import tomllib
else:
import tomli as tomllib
import tomlkit
from packaging.requirements import Requirement
from packaging.specifiers import Specifier
from tomlkit.items import String
from .paths import PYPROJECT_PATH, STUBS_PATH, distribution_path
@@ -26,12 +33,14 @@ __all__ = [
"PackageDependencies",
"StubMetadata",
"StubtestSettings",
"get_oldest_supported_python",
"get_recursive_requirements",
"read_dependencies",
"read_metadata",
"read_stubtest_settings",
]
DEFAULT_STUBTEST_PLATFORMS = ["linux"]
_STUBTEST_PLATFORM_MAPPING: Final = {"linux": "apt_dependencies", "darwin": "brew_dependencies", "win32": "choco_dependencies"}
# Some older websites have a bad pattern of using query params for navigation.
@@ -49,7 +58,7 @@ def _is_nested_dict(obj: object) -> TypeGuard[dict[str, dict[str, Any]]]:
@functools.cache
def get_oldest_supported_python() -> str:
with PYPROJECT_PATH.open("rb") as config:
val = tomli.load(config)["tool"]["typeshed"]["oldest_supported_python"]
val = tomllib.load(config)["tool"]["typeshed"]["oldest_supported_python"]
assert type(val) is str
return val
@@ -73,7 +82,8 @@ class StubtestSettings:
choco_dependencies: list[str]
extras: list[str]
ignore_missing_stub: bool
platforms: list[str]
supported_platforms: list[str] | None # None means all platforms
ci_platforms: list[str]
stubtest_requirements: list[str]
mypy_plugins: list[str]
mypy_plugins_config: dict[str, dict[str, Any]]
@@ -89,7 +99,7 @@ class StubtestSettings:
def read_stubtest_settings(distribution: str) -> StubtestSettings:
"""Return an object describing the stubtest settings for a single stubs distribution."""
with metadata_path(distribution).open("rb") as f:
data: dict[str, object] = tomli.load(f).get("tool", {}).get("stubtest", {})
data: dict[str, object] = tomllib.load(f).get("tool", {}).get("stubtest", {})
skip: object = data.get("skip", False)
apt_dependencies: object = data.get("apt_dependencies", [])
@@ -97,7 +107,8 @@ def read_stubtest_settings(distribution: str) -> StubtestSettings:
choco_dependencies: object = data.get("choco_dependencies", [])
extras: object = data.get("extras", [])
ignore_missing_stub: object = data.get("ignore_missing_stub", False)
specified_platforms: object = data.get("platforms", ["linux"])
supported_platforms: object = data.get("supported_platforms")
ci_platforms: object = data.get("ci_platforms", DEFAULT_STUBTEST_PLATFORMS)
stubtest_requirements: object = data.get("stubtest_requirements", [])
mypy_plugins: object = data.get("mypy_plugins", [])
mypy_plugins_config: object = data.get("mypy_plugins_config", {})
@@ -106,7 +117,8 @@ def read_stubtest_settings(distribution: str) -> StubtestSettings:
assert type(ignore_missing_stub) is bool
# It doesn't work for type-narrowing if we use a for loop here...
assert _is_list_of_strings(specified_platforms)
assert supported_platforms is None or _is_list_of_strings(supported_platforms)
assert _is_list_of_strings(ci_platforms)
assert _is_list_of_strings(apt_dependencies)
assert _is_list_of_strings(brew_dependencies)
assert _is_list_of_strings(choco_dependencies)
@@ -115,11 +127,16 @@ def read_stubtest_settings(distribution: str) -> StubtestSettings:
assert _is_list_of_strings(mypy_plugins)
assert _is_nested_dict(mypy_plugins_config)
unrecognised_platforms = set(specified_platforms) - _STUBTEST_PLATFORM_MAPPING.keys()
assert not unrecognised_platforms, f"Unrecognised platforms specified for {distribution!r}: {unrecognised_platforms}"
unrecognised_platforms = set(ci_platforms) - _STUBTEST_PLATFORM_MAPPING.keys()
assert not unrecognised_platforms, f"Unrecognised ci_platforms specified for {distribution!r}: {unrecognised_platforms}"
if supported_platforms is not None:
assert set(ci_platforms).issubset(
supported_platforms
), f"ci_platforms must be a subset of supported_platforms for {distribution!r}"
for platform, dep_key in _STUBTEST_PLATFORM_MAPPING.items():
if platform not in specified_platforms:
if platform not in ci_platforms:
assert dep_key not in data, (
f"Stubtest is not run on {platform} in CI for {distribution!r}, "
f"but {dep_key!r} are specified in METADATA.toml"
@@ -132,13 +149,21 @@ def read_stubtest_settings(distribution: str) -> StubtestSettings:
choco_dependencies=choco_dependencies,
extras=extras,
ignore_missing_stub=ignore_missing_stub,
platforms=specified_platforms,
supported_platforms=supported_platforms,
ci_platforms=ci_platforms,
stubtest_requirements=stubtest_requirements,
mypy_plugins=mypy_plugins,
mypy_plugins_config=mypy_plugins_config,
)
@final
@dataclass(frozen=True)
class ObsoleteMetadata:
since_version: Annotated[str, "A string representing a specific version"]
since_date: Annotated[datetime.date, "A date when the package became obsolete"]
@final
@dataclass(frozen=True)
class StubMetadata:
@@ -153,7 +178,7 @@ class StubMetadata:
extra_description: str | None
stub_distribution: Annotated[str, "The name under which the distribution is uploaded to PyPI"]
upstream_repository: Annotated[str, "The URL of the upstream repository"] | None
obsolete_since: Annotated[str, "A string representing a specific version"] | None
obsolete: Annotated[ObsoleteMetadata, "Metadata indicating when the stubs package became obsolete"] | None
no_longer_updated: bool
uploaded_to_pypi: Annotated[bool, "Whether or not a distribution is uploaded to PyPI"]
partial_stub: Annotated[bool, "Whether this is a partial type stub package as per PEP 561."]
@@ -162,7 +187,7 @@ class StubMetadata:
@property
def is_obsolete(self) -> bool:
return self.obsolete_since is not None
return self.obsolete is not None
_KNOWN_METADATA_FIELDS: Final = frozenset(
@@ -189,7 +214,8 @@ _KNOWN_METADATA_TOOL_FIELDS: Final = {
"choco_dependencies",
"extras",
"ignore_missing_stub",
"platforms",
"supported_platforms",
"ci_platforms",
"stubtest_requirements",
"mypy_plugins",
"mypy_plugins_config",
@@ -213,7 +239,7 @@ def read_metadata(distribution: str) -> StubMetadata:
"""
try:
with metadata_path(distribution).open("rb") as f:
data: dict[str, object] = tomli.load(f)
data = tomlkit.load(f)
except FileNotFoundError:
raise NoSuchStubError(f"Typeshed has no stubs for {distribution!r}!") from None
@@ -221,7 +247,7 @@ def read_metadata(distribution: str) -> StubMetadata:
assert not unknown_metadata_fields, f"Unexpected keys in METADATA.toml for {distribution!r}: {unknown_metadata_fields}"
assert "version" in data, f"Missing 'version' field in METADATA.toml for {distribution!r}"
version = data["version"]
version: object = data.get("version") # pyright: ignore[reportUnknownMemberType]
assert isinstance(version, str) and len(version) > 0, f"Invalid 'version' field in METADATA.toml for {distribution!r}"
# Check that the version spec parses
if version[0].isdigit():
@@ -229,11 +255,11 @@ def read_metadata(distribution: str) -> StubMetadata:
version_spec = Specifier(version)
assert version_spec.operator in {"==", "~="}, f"Invalid 'version' field in METADATA.toml for {distribution!r}"
requires_s: object = data.get("requires", [])
requires_s: object = data.get("requires", []) # pyright: ignore[reportUnknownMemberType]
assert isinstance(requires_s, list)
requires = [parse_requires(distribution, req) for req in requires_s]
extra_description: object = data.get("extra_description")
extra_description: object = data.get("extra_description") # pyright: ignore[reportUnknownMemberType]
assert isinstance(extra_description, (str, type(None)))
if "stub_distribution" in data:
@@ -243,7 +269,7 @@ def read_metadata(distribution: str) -> StubMetadata:
else:
stub_distribution = f"types-{distribution}"
upstream_repository: object = data.get("upstream_repository")
upstream_repository: object = data.get("upstream_repository") # pyright: ignore[reportUnknownMemberType]
assert isinstance(upstream_repository, (str, type(None)))
if isinstance(upstream_repository, str):
parsed_url = urllib.parse.urlsplit(upstream_repository)
@@ -267,21 +293,28 @@ def read_metadata(distribution: str) -> StubMetadata:
)
assert num_url_path_parts == 2, bad_github_url_msg
obsolete_since: object = data.get("obsolete_since")
assert isinstance(obsolete_since, (str, type(None)))
no_longer_updated: object = data.get("no_longer_updated", False)
obsolete_since: object = data.get("obsolete_since") # pyright: ignore[reportUnknownMemberType]
assert isinstance(obsolete_since, (String, type(None)))
if obsolete_since:
comment = obsolete_since.trivia.comment
since_date_string = comment.removeprefix("# Released on ")
since_date = datetime.date.fromisoformat(since_date_string)
obsolete = ObsoleteMetadata(since_version=obsolete_since, since_date=since_date)
else:
obsolete = None
no_longer_updated: object = data.get("no_longer_updated", False) # pyright: ignore[reportUnknownMemberType]
assert type(no_longer_updated) is bool
uploaded_to_pypi: object = data.get("upload", True)
uploaded_to_pypi: object = data.get("upload", True) # pyright: ignore[reportUnknownMemberType]
assert type(uploaded_to_pypi) is bool
partial_stub: object = data.get("partial_stub", True)
partial_stub: object = data.get("partial_stub", True) # pyright: ignore[reportUnknownMemberType]
assert type(partial_stub) is bool
requires_python_str: object = data.get("requires_python")
requires_python_str: object = data.get("requires_python") # pyright: ignore[reportUnknownMemberType]
oldest_supported_python = get_oldest_supported_python()
oldest_supported_python_specifier = Specifier(f">={oldest_supported_python}")
if requires_python_str is None:
requires_python = oldest_supported_python_specifier
else:
assert type(requires_python_str) is str
assert isinstance(requires_python_str, str)
requires_python = Specifier(requires_python_str)
assert requires_python != oldest_supported_python_specifier, f'requires_python="{requires_python}" is redundant'
# Check minimum Python version is not less than the oldest version of Python supported by typeshed
@@ -291,7 +324,7 @@ def read_metadata(distribution: str) -> StubMetadata:
assert requires_python.operator == ">=", "'requires_python' should be a minimum version specifier, use '>=3.x'"
empty_tools: dict[object, object] = {}
tools_settings: object = data.get("tool", empty_tools)
tools_settings: object = data.get("tool", empty_tools) # pyright: ignore[reportUnknownMemberType]
assert isinstance(tools_settings, dict)
assert tools_settings.keys() <= _KNOWN_METADATA_TOOL_FIELDS.keys(), f"Unrecognised tool for {distribution!r}"
for tool, tk in _KNOWN_METADATA_TOOL_FIELDS.items():
@@ -307,7 +340,7 @@ def read_metadata(distribution: str) -> StubMetadata:
extra_description=extra_description,
stub_distribution=stub_distribution,
upstream_repository=upstream_repository,
obsolete_since=obsolete_since,
obsolete=obsolete,
no_longer_updated=no_longer_updated,
uploaded_to_pypi=uploaded_to_pypi,
partial_stub=partial_stub,
+6 -2
View File
@@ -1,10 +1,14 @@
from __future__ import annotations
import sys
from collections.abc import Generator, Iterable
from contextlib import contextmanager
from typing import Any, NamedTuple
import tomli
if sys.version_info >= (3, 11):
import tomllib
else:
import tomli as tomllib
from ts_utils.metadata import StubtestSettings, metadata_path
from ts_utils.utils import NamedTemporaryFile, TemporaryFileWrapper
@@ -26,7 +30,7 @@ class MypyDistConf(NamedTuple):
def mypy_configuration_from_distribution(distribution: str) -> list[MypyDistConf]:
with metadata_path(distribution).open("rb") as f:
data = tomli.load(f)
data = tomllib.load(f)
# TODO: This could be added to ts_utils.metadata
mypy_tests_conf: dict[str, dict[str, Any]] = data.get("mypy-tests", {})
@@ -12,6 +12,7 @@ STUBS_PATH: Final = TS_BASE_PATH / "stubs"
PYPROJECT_PATH: Final = TS_BASE_PATH / "pyproject.toml"
REQUIREMENTS_PATH: Final = TS_BASE_PATH / "requirements-tests.txt"
GITIGNORE_PATH: Final = TS_BASE_PATH / ".gitignore"
PYRIGHT_CONFIG: Final = TS_BASE_PATH / "pyrightconfig.stricter.json"
TESTS_DIR: Final = "@tests"
TEST_CASES_DIR: Final = "test_cases"
@@ -18,11 +18,12 @@ def get_external_stub_requirements(distributions: Iterable[str] = ()) -> set[Req
return set(itertools.chain.from_iterable([read_dependencies(distribution).external_pkgs for distribution in distributions]))
def get_stubtest_system_requirements(distributions: Iterable[str] = (), platform: str = sys.platform) -> list[str]:
def get_stubtest_system_requirements(distributions: Iterable[str] = (), platform: str = sys.platform) -> set[str]:
if not distributions:
distributions = os.listdir(STUBS_PATH)
requirements: list[str] = []
for distribution in distributions:
requirements.extend(read_stubtest_settings(distribution).system_requirements_for_platform(platform))
return requirements
return set(
itertools.chain.from_iterable(
[read_stubtest_settings(distribution).system_requirements_for_platform(platform) for distribution in distributions]
)
)
@@ -50,6 +50,10 @@ def print_info(message: str) -> None:
print(colored(message, "blue"))
def print_warning(message: str) -> None:
print(colored(message, "yellow"))
def print_error(error: str, end: str = "\n", fix_path: tuple[str, str] = ("", "")) -> None:
error_split = error.split("\n")
old, new = fix_path
+3 -1
View File
@@ -23,7 +23,6 @@ exclude = [
# cache directories, etc.:
".git",
".mypy_cache",
".pytype",
]
[tool.ruff.lint]
@@ -159,6 +158,8 @@ ignore = [
# Used for direct, non-subclass type comparison, for example: `type(val) is str`
# see https://github.com/astral-sh/ruff/issues/6465
"E721", # Do not compare types, use `isinstance()`
# Highly opinionated, and it's often necessary to violate it
"PLC0415", # `import` should be at the top-level of a file
# Leave the size and complexity of tests to human interpretation
"PLR09", # Too many ...
# Too many magic number "2" that are preferable inline. https://github.com/astral-sh/ruff/issues/10009
@@ -176,6 +177,7 @@ ignore = [
"TRY003", # Avoid specifying long messages outside the exception class
# Slower and more verbose https://github.com/astral-sh/ruff/issues/7871
"UP038", # Use `X | Y` in `isinstance` call instead of `(X, Y)`
"PLC0205", # Sometimes __slots__ really is a string at runtime
###
# False-positives, but already checked by type-checkers
###
@@ -18,28 +18,22 @@
"stdlib/optparse.pyi",
"stdlib/_tkinter.pyi",
"stdlib/tkinter/__init__.pyi",
"stdlib/tkinter/commondialog.pyi",
"stdlib/tkinter/filedialog.pyi",
"stdlib/tkinter/dialog.pyi",
"stdlib/tkinter/messagebox.pyi",
"stdlib/tkinter/scrolledtext.pyi",
"stdlib/tkinter/tix.pyi",
"stdlib/tkinter/ttk.pyi",
"stubs/aiofiles",
"stubs/antlr4-python3-runtime",
"stubs/auth0-python",
"stubs/Authlib",
"stubs/aws-xray-sdk",
"stubs/beautifulsoup4",
"stubs/boltons",
"stubs/braintree",
"stubs/cffi",
"stubs/click-web",
"stubs/dateparser",
"stubs/defusedxml",
"stubs/docker",
"stubs/docutils",
"stubs/flake8-typing-imports",
"stubs/Flask-SocketIO",
"stubs/fpdf2",
"stubs/gdb",
@@ -55,11 +49,10 @@
"stubs/httplib2",
"stubs/hvac",
"stubs/icalendar",
"stubs/jmespath",
"stubs/jsonschema",
"stubs/jwcrypto",
"stubs/ldap3",
"stubs/m3u8",
"stubs/m3u8/m3u8/model.pyi",
"stubs/Markdown",
"stubs/mock/mock/mock.pyi",
"stubs/mysqlclient",
@@ -76,6 +69,7 @@
"stubs/peewee",
"stubs/pexpect",
"stubs/pika",
"stubs/pony",
"stubs/protobuf",
"stubs/psutil",
"stubs/psycopg2",
@@ -83,14 +77,10 @@
"stubs/pycurl",
"stubs/Pygments",
"stubs/PyMySQL",
"stubs/python-crontab",
"stubs/python-datemath",
"stubs/python-dateutil",
"stubs/python-http-client",
"stubs/python-jose",
"stubs/pytz/pytz/lazy.pyi",
"stubs/pywin32",
"stubs/pyxdg",
"stubs/PyYAML",
"stubs/reportlab",
"stubs/requests",
@@ -102,7 +92,6 @@
"stubs/tqdm",
"stubs/vobject",
"stubs/workalendar",
"stubs/wurlitzer",
],
"typeCheckingMode": "strict",
// TODO: Complete incomplete stubs
+9 -11
View File
@@ -1,30 +1,28 @@
# Type checkers that we test our stubs against. These should always
# be pinned to a specific version to make failure reproducible.
mypy==1.16.0
pyright==1.1.400
# pytype can be installed on Windows, but requires building wheels, let's not do that on the CI
pytype==2024.10.11; platform_system != "Windows" and python_version >= "3.10" and python_version < "3.13"
mypy==1.17.1
pyright==1.1.404
# Libraries used by our various scripts.
# TODO (2025-05-09): Installing this on Python 3.14 on Windows fails at
# the moment.
aiohttp==3.11.15; python_version < "3.14"
aiohttp==3.12.14; python_version < "3.14"
# TODO (2025-05-09): No wheels exist for Python 3.14 yet, slowing down CI
# considerably and prone to fail.
grpcio-tools>=1.66.2; python_version < "3.14" # For grpc_tools.protoc
mypy-protobuf==3.6.0
packaging==24.2
packaging==25.0
pathspec>=0.11.1
pre-commit
# Required by create_baseline_stubs.py. Must match .pre-commit-config.yaml.
ruff==0.11.4
ruff==0.12.2
# TODO (2025-05-07): Dependency libcst doesn't support Python 3.14 yet.
stubdefaulter==0.1.0; python_version < "3.14"
termcolor>=2.3
tomli==2.2.1
tomlkit==0.13.2
typing_extensions>=4.14.0rc1
uv==0.7.4
tomli==2.2.1; python_version < "3.11"
tomlkit==0.13.3
typing_extensions>=4.15.0rc1
uv==0.8.6
# Utilities for typeshed infrastructure scripts.
ts_utils @ file:lib
+1 -3
View File
@@ -23,9 +23,7 @@ from pathlib import Path
import aiohttp
import termcolor
from ts_utils.paths import STDLIB_PATH, STUBS_PATH
PYRIGHT_CONFIG = Path("pyrightconfig.stricter.json")
from ts_utils.paths import PYRIGHT_CONFIG, STDLIB_PATH, STUBS_PATH
def search_pip_freeze_output(project: str, output: str) -> tuple[str, str] | None:
+300 -69
View File
@@ -3,6 +3,7 @@ from __future__ import annotations
import argparse
import asyncio
import calendar
import contextlib
import datetime
import enum
@@ -10,33 +11,41 @@ import functools
import io
import os
import re
import shutil
import subprocess
import sys
import tarfile
import textwrap
import urllib.parse
import zipfile
from collections.abc import Iterator, Mapping, Sequence
from collections.abc import Callable, Iterator, Mapping, Sequence
from dataclasses import dataclass, field
from http import HTTPStatus
from pathlib import Path
from typing import Annotated, Any, ClassVar, NamedTuple
from typing import Annotated, Any, ClassVar, Literal, NamedTuple, TypedDict, TypeVar
from typing_extensions import Self, TypeAlias
if sys.version_info >= (3, 11):
import tomllib
else:
import tomli as tomllib
import aiohttp
import packaging.version
import tomlkit
from packaging.specifiers import Specifier
from termcolor import colored
from ts_utils.metadata import StubMetadata, read_metadata, update_metadata
from ts_utils.paths import STUBS_PATH, distribution_path
from ts_utils.metadata import ObsoleteMetadata, StubMetadata, read_metadata, update_metadata
from ts_utils.paths import PYRIGHT_CONFIG, STUBS_PATH, distribution_path
TYPESHED_OWNER = "python"
TYPESHED_API_URL = f"https://api.github.com/repos/{TYPESHED_OWNER}/typeshed"
STUBSABOT_LABEL = "bot: stubsabot"
POLICY_MONTHS_DELTA = 6
class ActionLevel(enum.IntEnum):
def __new__(cls, value: int, doc: str) -> Self:
@@ -128,7 +137,7 @@ class Update:
diff_analysis: DiffAnalysis | None
def __str__(self) -> str:
return f"Updating {self.distribution} from {self.old_version_spec!r} to {self.new_version_spec!r}"
return f"{colored('updating', 'yellow')} from '{self.old_version_spec}' to '{self.new_version_spec}'"
@property
def new_version(self) -> str:
@@ -146,7 +155,17 @@ class Obsolete:
links: dict[str, str]
def __str__(self) -> str:
return f"Marking {self.distribution} as obsolete since {self.obsolete_since_version!r}"
return f"{colored('marking as obsolete', 'yellow')} since {self.obsolete_since_version!r}"
@dataclass
class Remove:
distribution: str
reason: str
links: dict[str, str]
def __str__(self) -> str:
return f"{colored('removing', 'yellow')} ({self.reason})"
@dataclass
@@ -155,7 +174,48 @@ class NoUpdate:
reason: str
def __str__(self) -> str:
return f"Skipping {self.distribution}: {self.reason}"
return f"{colored('skipping', 'green')} ({self.reason})"
@dataclass
class Error:
distribution: str
message: str
def __str__(self) -> str:
return f"{colored('error', 'red')} ({self.message})"
_T = TypeVar("_T")
async def with_extracted_archive(
release_to_download: PypiReleaseDownload,
*,
session: aiohttp.ClientSession,
handler: Callable[[zipfile.ZipFile | tarfile.TarFile], _T],
) -> _T:
async with session.get(release_to_download.url) as response:
body = io.BytesIO(await response.read())
packagetype = release_to_download.packagetype
if packagetype == "bdist_wheel":
assert release_to_download.filename.endswith(".whl")
with zipfile.ZipFile(body) as zf:
return handler(zf)
elif packagetype == "sdist":
# sdist defaults to `.tar.gz` on Lunix and to `.zip` on Windows:
# https://docs.python.org/3.11/distutils/sourcedist.html
if release_to_download.filename.endswith(".tar.gz"):
with tarfile.open(fileobj=body, mode="r:gz") as zf:
return handler(zf)
elif release_to_download.filename.endswith(".zip"):
with zipfile.ZipFile(body) as zf:
return handler(zf)
else:
raise AssertionError(f"Package file {release_to_download.filename!r} does not end with '.tar.gz' or '.zip'")
else:
raise AssertionError(f"Unknown package type for {release_to_download.distribution}: {packagetype!r}")
def all_py_files_in_source_are_in_py_typed_dirs(source: zipfile.ZipFile | tarfile.TarFile) -> bool:
@@ -207,27 +267,7 @@ def all_py_files_in_source_are_in_py_typed_dirs(source: zipfile.ZipFile | tarfil
async def release_contains_py_typed(release_to_download: PypiReleaseDownload, *, session: aiohttp.ClientSession) -> bool:
async with session.get(release_to_download.url) as response:
body = io.BytesIO(await response.read())
packagetype = release_to_download.packagetype
if packagetype == "bdist_wheel":
assert release_to_download.filename.endswith(".whl")
with zipfile.ZipFile(body) as zf:
return all_py_files_in_source_are_in_py_typed_dirs(zf)
elif packagetype == "sdist":
# sdist defaults to `.tar.gz` on Lunix and to `.zip` on Windows:
# https://docs.python.org/3.11/distutils/sourcedist.html
if release_to_download.filename.endswith(".tar.gz"):
with tarfile.open(fileobj=body, mode="r:gz") as zf:
return all_py_files_in_source_are_in_py_typed_dirs(zf)
elif release_to_download.filename.endswith(".zip"):
with zipfile.ZipFile(body) as zf:
return all_py_files_in_source_are_in_py_typed_dirs(zf)
else:
raise AssertionError(f"Package file {release_to_download.filename!r} does not end with '.tar.gz' or '.zip'")
else:
raise AssertionError(f"Unknown package type for {release_to_download.distribution}: {packagetype!r}")
return await with_extracted_archive(release_to_download, session=session, handler=all_py_files_in_source_are_in_py_typed_dirs)
async def find_first_release_with_py_typed(pypi_info: PypiInfo, *, session: aiohttp.ClientSession) -> PypiReleaseDownload | None:
@@ -286,57 +326,80 @@ def get_github_api_headers() -> Mapping[str, str]:
return headers
GitHost: TypeAlias = Literal["github", "gitlab"]
@dataclass
class GitHubInfo:
class GitHostInfo:
host: GitHost
repo_path: str
tags: list[dict[str, Any]] = field(repr=False)
tags: list[str] = field(repr=False)
async def get_github_repo_info(session: aiohttp.ClientSession, stub_info: StubMetadata) -> GitHubInfo | None:
async def get_host_repo_info(session: aiohttp.ClientSession, stub_info: StubMetadata) -> GitHostInfo | None:
"""
If the project represented by `stub_info` is hosted on GitHub,
return information regarding the project as it exists on GitHub.
If the project represented by `stub_info` is publicly hosted (e.g. on GitHub)
return information regarding the project as it exists on the public host.
Else, return None.
"""
if stub_info.upstream_repository:
# We have various sanity checks for the upstream_repository field in ts_utils.metadata,
# so no need to repeat all of them here
split_url = urllib.parse.urlsplit(stub_info.upstream_repository)
if split_url.netloc == "github.com":
url_path = split_url.path.strip("/")
assert len(Path(url_path).parts) == 2
github_tags_info_url = f"https://api.github.com/repos/{url_path}/tags"
async with session.get(github_tags_info_url, headers=get_github_api_headers()) as response:
if response.status == HTTPStatus.OK:
tags: list[dict[str, Any]] = await response.json()
assert isinstance(tags, list)
return GitHubInfo(repo_path=url_path, tags=tags)
if not stub_info.upstream_repository:
return None
# We have various sanity checks for the upstream_repository field in ts_utils.metadata,
# so no need to repeat all of them here
split_url = urllib.parse.urlsplit(stub_info.upstream_repository)
host = split_url.netloc.removesuffix(".com")
if host not in ("github", "gitlab"):
return None
url_path = split_url.path.strip("/")
assert len(Path(url_path).parts) == 2
if host == "github":
# https://docs.github.com/en/rest/git/tags
info_url = f"https://api.github.com/repos/{url_path}/tags"
headers = get_github_api_headers()
else:
assert host == "gitlab"
# https://docs.gitlab.com/api/tags/
project_id = urllib.parse.quote(url_path, safe="")
info_url = f"https://gitlab.com/api/v4/projects/{project_id}/repository/tags"
headers = None
async with session.get(info_url, headers=headers) as response:
if response.status == HTTPStatus.OK:
# Conveniently both GitHub and GitLab use the same key name.
tags = [tag["name"] for tag in await response.json()]
return GitHostInfo(host=host, repo_path=url_path, tags=tags) # type: ignore[arg-type]
return None
class GitHubDiffInfo(NamedTuple):
class GitHostDiffInfo(NamedTuple):
host: GitHost
repo_path: str
old_tag: str
new_tag: str
diff_url: str
@property
def diff_url(self) -> str:
if self.host == "github":
return f"https://github.com/{self.repo_path}/compare/{self.old_tag}...{self.new_tag}"
else:
assert self.host == "gitlab"
return f"https://gitlab.com/{self.repo_path}/-/compare/{self.old_tag}...{self.new_tag}"
async def get_diff_info(
session: aiohttp.ClientSession, stub_info: StubMetadata, pypi_version: packaging.version.Version
) -> GitHubDiffInfo | None:
) -> GitHostDiffInfo | None:
"""Return a tuple giving info about the diff between two releases, if possible.
Return `None` if the project isn't hosted on GitHub,
or if a link pointing to the diff couldn't be found for any other reason.
"""
github_info = await get_github_repo_info(session, stub_info)
if github_info is None:
host_info = await get_host_repo_info(session, stub_info)
if host_info is None:
return None
versions_to_tags: dict[packaging.version.Version, str] = {}
for tag in github_info.tags:
tag_name = tag["name"]
for tag_name in host_info.tags:
# Some packages in typeshed have tag names
# that are invalid to be passed to the Version() constructor,
# e.g. v.1.4.2
@@ -355,11 +418,17 @@ async def get_diff_info(
else:
old_tag = versions_to_tags[old_version]
diff_url = f"https://github.com/{github_info.repo_path}/compare/{old_tag}...{new_tag}"
return GitHubDiffInfo(repo_path=github_info.repo_path, old_tag=old_tag, new_tag=new_tag, diff_url=diff_url)
return GitHostDiffInfo(host=host_info.host, repo_path=host_info.repo_path, old_tag=old_tag, new_tag=new_tag)
FileInfo: TypeAlias = dict[str, Any]
FileStatus: TypeAlias = Literal["added", "modified", "removed", "renamed"]
class FileInfo(TypedDict):
filename: str
status: FileStatus
additions: int
deletions: int
def _plural_s(num: int, /) -> str:
@@ -454,10 +523,10 @@ class DiffAnalysis:
return "Stubsabot analysis of the diff between the two releases:\n - " + "\n - ".join(data_points)
async def analyze_diff(
github_repo_path: str, distribution: str, old_tag: str, new_tag: str, *, session: aiohttp.ClientSession
async def analyze_github_diff(
repo_path: str, distribution: str, old_tag: str, new_tag: str, *, session: aiohttp.ClientSession
) -> DiffAnalysis | None:
url = f"https://api.github.com/repos/{github_repo_path}/compare/{old_tag}...{new_tag}"
url = f"https://api.github.com/repos/{repo_path}/compare/{old_tag}...{new_tag}"
async with session.get(url, headers=get_github_api_headers()) as response:
response.raise_for_status()
json_resp: dict[str, list[FileInfo]] = await response.json()
@@ -470,12 +539,124 @@ async def analyze_diff(
return DiffAnalysis(py_files=py_files, py_files_stubbed_in_typeshed=py_files_stubbed_in_typeshed)
async def determine_action(distribution: str, session: aiohttp.ClientSession) -> Update | NoUpdate | Obsolete:
async def analyze_gitlab_diff(
repo_path: str, distribution: str, old_tag: str, new_tag: str, *, session: aiohttp.ClientSession
) -> DiffAnalysis | None:
# https://docs.gitlab.com/api/repositories/#compare-branches-tags-or-commits
project_id = urllib.parse.quote(repo_path, safe="")
url = f"https://gitlab.com/api/v4/projects/{project_id}/repository/compare?from={old_tag}&to={new_tag}"
async with session.get(url) as response:
response.raise_for_status()
json_resp: dict[str, Any] = await response.json()
assert isinstance(json_resp, dict)
py_files: list[FileInfo] = []
for file_diff in json_resp["diffs"]:
filename = file_diff["new_path"]
if Path(filename).suffix != ".py":
continue
status: FileStatus
if file_diff["new_file"]:
status = "added"
elif file_diff["renamed_file"]:
status = "renamed"
elif file_diff["deleted_file"]:
status = "removed"
else:
status = "modified"
diff_lines = file_diff["diff"].splitlines()
additions = sum(1 for ln in diff_lines if ln.startswith("+"))
deletions = sum(1 for ln in diff_lines if ln.startswith("-"))
py_files.append(FileInfo(filename=filename, status=status, additions=additions, deletions=deletions))
stub_path = distribution_path(distribution)
files_in_typeshed = set(stub_path.rglob("*.pyi"))
py_files_stubbed_in_typeshed = [file for file in py_files if (stub_path / f"{file['filename']}i") in files_in_typeshed]
return DiffAnalysis(py_files=py_files, py_files_stubbed_in_typeshed=py_files_stubbed_in_typeshed)
def _add_months(date: datetime.date, months: int) -> datetime.date:
month = date.month - 1 + months
year = date.year + month // 12
month = month % 12 + 1
day = min(date.day, calendar.monthrange(year, month)[1])
return datetime.date(year, month, day)
def obsolete_more_than_n_months(since_date: datetime.date) -> bool:
remove_date = _add_months(since_date, POLICY_MONTHS_DELTA)
today = datetime.datetime.now(tz=datetime.timezone.utc).date()
return remove_date <= today
def parse_no_longer_updated_from_archive(source: zipfile.ZipFile | tarfile.TarFile) -> bool:
if isinstance(source, zipfile.ZipFile):
try:
file = source.open("METADATA.toml", "r")
except KeyError:
return False
else:
try:
tarinfo = source.getmember("METADATA.toml")
file = source.extractfile(tarinfo) # type: ignore[assignment]
if file is None:
return False
except KeyError:
return False
with file as f:
toml_data: dict[str, object] = tomllib.load(f)
no_longer_updated = toml_data.get("no_longer_updated", False)
assert type(no_longer_updated) is bool
return bool(no_longer_updated)
async def has_no_longer_updated_release(release_to_download: PypiReleaseDownload, *, session: aiohttp.ClientSession) -> bool:
"""
Return `True` if the `no_longer_updated` field exists and the value is
`True` in the `METADATA.toml` file of latest `types-{distribution}` pypi release.
"""
return await with_extracted_archive(release_to_download, session=session, handler=parse_no_longer_updated_from_archive)
async def determine_action(distribution: str, session: aiohttp.ClientSession) -> Update | NoUpdate | Obsolete | Remove | Error:
try:
return await determine_action_no_error_handling(distribution, session)
except Exception as exc:
return Error(distribution, str(exc))
async def determine_action_no_error_handling(
distribution: str, session: aiohttp.ClientSession
) -> Update | NoUpdate | Obsolete | Remove:
stub_info = read_metadata(distribution)
if stub_info.is_obsolete:
return NoUpdate(stub_info.distribution, "obsolete")
assert type(stub_info.obsolete) is ObsoleteMetadata
since_date = stub_info.obsolete.since_date
if obsolete_more_than_n_months(since_date):
pypi_info = await fetch_pypi_info(f"types-{stub_info.distribution}", session)
latest_release = pypi_info.get_latest_release()
links = {
"Typeshed release": f"{pypi_info.pypi_root}",
"Typeshed stubs": f"https://github.com/{TYPESHED_OWNER}/typeshed/tree/main/stubs/{stub_info.distribution}",
}
return Remove(stub_info.distribution, reason="older than 6 months", links=links)
else:
return NoUpdate(stub_info.distribution, "obsolete")
if stub_info.no_longer_updated:
return NoUpdate(stub_info.distribution, "no longer updated")
pypi_info = await fetch_pypi_info(f"types-{stub_info.distribution}", session)
latest_release = pypi_info.get_latest_release()
if await has_no_longer_updated_release(latest_release, session=session):
links = {
"Typeshed release": f"{pypi_info.pypi_root}",
"Typeshed stubs": f"https://github.com/{TYPESHED_OWNER}/typeshed/tree/main/stubs/{stub_info.distribution}",
}
return Remove(stub_info.distribution, reason="no longer updated", links=links)
else:
return NoUpdate(stub_info.distribution, "no longer updated")
pypi_info = await fetch_pypi_info(stub_info.distribution, session)
latest_release = pypi_info.get_latest_release()
@@ -511,8 +692,9 @@ async def determine_action(distribution: str, session: aiohttp.ClientSession) ->
if diff_info is None:
diff_analysis: DiffAnalysis | None = None
else:
analyze_diff = {"github": analyze_github_diff, "gitlab": analyze_gitlab_diff}[diff_info.host]
diff_analysis = await analyze_diff(
github_repo_path=diff_info.repo_path,
repo_path=diff_info.repo_path,
distribution=distribution,
old_tag=diff_info.old_tag,
new_tag=diff_info.new_tag,
@@ -683,6 +865,22 @@ def get_update_pr_body(update: Update, metadata: Mapping[str, Any]) -> str:
return body
def remove_stubs(distribution: str) -> None:
stub_path = distribution_path(distribution)
target_path_prefix = f'"stubs/{distribution}'
if stub_path.exists() and stub_path.is_dir():
shutil.rmtree(stub_path)
with PYRIGHT_CONFIG.open("r", encoding="UTF-8") as f:
lines = f.readlines()
lines = [line for line in lines if not line.lstrip().startswith(target_path_prefix)]
with PYRIGHT_CONFIG.open("w", encoding="UTF-8") as f:
f.writelines(lines)
async def suggest_typeshed_update(update: Update, session: aiohttp.ClientSession, action_level: ActionLevel) -> None:
if action_level <= ActionLevel.nothing:
return
@@ -729,7 +927,29 @@ async def suggest_typeshed_obsolete(obsolete: Obsolete, session: aiohttp.ClientS
await create_or_update_pull_request(title=title, body=body, branch_name=branch_name, session=session)
async def main() -> None:
async def suggest_typeshed_remove(remove: Remove, session: aiohttp.ClientSession, action_level: ActionLevel) -> None:
if action_level <= ActionLevel.nothing:
return
title = f"[stubsabot] Remove {remove.distribution} as {remove.reason}"
async with _repo_lock:
branch_name = f"{BRANCH_PREFIX}/{normalize(remove.distribution)}"
subprocess.check_call(["git", "checkout", "-B", branch_name, "origin/main"])
remove_stubs(remove.distribution)
body = "\n".join(f"{k}: {v}" for k, v in remove.links.items())
subprocess.check_call(["git", "commit", "--all", "-m", f"{title}\n\n{body}"])
if action_level <= ActionLevel.local:
return
if not latest_commit_is_different_to_last_commit_on_origin(branch_name):
print(f"No pushing to origin required: origin/{branch_name} exists and requires no changes!")
return
somewhat_safe_force_push(branch_name)
if action_level <= ActionLevel.fork:
return
await create_or_update_pull_request(title=title, body=body, branch_name=branch_name, session=session)
async def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument(
"--action-level",
@@ -758,11 +978,11 @@ async def main() -> None:
print("Unexpected exception!")
print(diff_result.stdout)
print(diff_result.stderr)
sys.exit(diff_result.returncode)
return diff_result.returncode
if diff_result.stdout:
changed_files = ", ".join(repr(line) for line in diff_result.stdout.split("\n") if line)
print(f"Cannot run stubsabot, as uncommitted changes are present in {changed_files}!")
sys.exit(1)
return 1
if args.action_level > ActionLevel.fork:
if os.environ.get("GITHUB_TOKEN") is None:
@@ -777,6 +997,8 @@ async def main() -> None:
if args.action_level >= ActionLevel.local:
subprocess.check_call(["git", "fetch", "--prune", "--all"])
error = False
try:
conn = aiohttp.TCPConnector(limit_per_host=10)
async with aiohttp.ClientSession(connector=conn) as session:
@@ -789,10 +1011,14 @@ async def main() -> None:
action_count = 0
for task in asyncio.as_completed(tasks):
update = await task
print(f"{update.distribution}... ", end="")
print(update)
if isinstance(update, NoUpdate):
continue
if isinstance(update, Error):
error = True
continue
if args.action_count_limit is not None and action_count >= args.action_count_limit:
print(colored("... but we've reached action count limit", "red"))
@@ -803,10 +1029,13 @@ async def main() -> None:
if isinstance(update, Update):
await suggest_typeshed_update(update, session, action_level=args.action_level)
continue
# Redundant, but keeping for extra runtime validation
if isinstance(update, Obsolete): # pyright: ignore[reportUnnecessaryIsInstance]
if isinstance(update, Obsolete):
await suggest_typeshed_obsolete(update, session, action_level=args.action_level)
continue
# Redundant, but keeping for extra runtime validation
if isinstance(update, Remove): # pyright: ignore[reportUnnecessaryIsInstance]
await suggest_typeshed_remove(update, session, action_level=args.action_level)
continue
except RemoteConflictError as e:
print(colored(f"... but ran into {type(e).__qualname__}: {e}", "red"))
continue
@@ -817,6 +1046,8 @@ async def main() -> None:
if args.action_level >= ActionLevel.local and original_branch:
subprocess.check_call(["git", "checkout", original_branch])
return 1 if error else 0
if __name__ == "__main__":
asyncio.run(main())
sys.exit(asyncio.run(main()))
View File
View File
View File
@@ -195,6 +195,10 @@ _frozen_importlib_external.FileLoader.get_filename
_frozen_importlib_external.FileLoader.get_resource_reader
_frozen_importlib_external.FileLoader.load_module
# Mismatch of default values of `report` parameter:
_markupbase.ParserBase.parse_comment
_markupbase.ParserBase.parse_marked_section
_pydecimal.* # See comments in file
_typeshed.* # Utility types for typeshed, doesn't exist at runtime
argparse.ArgumentParser.__init__ # stubtest doesn't recognise the runtime default (a class) as being compatible with a callback protocol (the stub annotation)
@@ -307,6 +311,7 @@ functools._lru_cache_wrapper.cache_parameters # Cannot be detected statically
functools.cached_property.__set__ # doesn't exist, but cached_property is settable by another mechanism
hmac.new # Raises TypeError if optional argument digestmod is not provided
html.parser.HTMLParser.parse_bogus_comment # default values mismatch
http.HTTPStatus.description # set in __new__; work-around for enum wierdness
http.HTTPStatus.phrase # set in __new__; work-around for enum wierdness
imaplib.IMAP4_SSL.ssl # Depends on the existence and flags of SSL
@@ -461,11 +466,9 @@ typing._Final.__init_subclass__
typing\.Protocol
typing(_extensions)?\._TypedDict
typing(_extensions)?\.Any.*
typing(_extensions)?\.Generic
typing(_extensions)?\.TypedDict
typing_extensions\.ParamSpec.*
typing_extensions\.TypeVar.*
typing_extensions\._SpecialForm.*
# Special primitives
typing(_extensions)?\.AbstractSet
@@ -494,7 +497,6 @@ typing(_extensions)?\.Reversible
typing(_extensions)?\.Sequence
typing(_extensions)?\.Sized
typing(_extensions)?\.ValuesView
typing_extensions\.Final
typing_extensions\.LiteralString
# Typing-related weirdness
@@ -1,6 +1,6 @@
# ===========
# 3.9 to 3.11
# ===========
# =======
# <= 3.11
# =======
# Added in Python 3.10.15
email._header_value_parser.NLSET
@@ -41,6 +41,7 @@ xml.etree.cElementTree.XMLPullParser.flush
xml.parsers.expat.XMLParserType.GetReparseDeferralEnabled
xml.parsers.expat.XMLParserType.SetReparseDeferralEnabled
xml.sax.expatreader.ExpatParser.flush
zipfile.ZipInfo.__slots__
# =============================================================
@@ -8,12 +8,11 @@ fcntl.F_OFD_SETLK
fcntl.F_OFD_SETLKW
# ===========
# 3.9 to 3.11
# ===========
# =======
# <= 3.11
# =======
# Incompatible changes introduced in Python 3.11.10
# (Remove once 3.11.10 becomes available for MacOS)
# Added in Python 3.11.10
email._header_value_parser.NLSET
email._header_value_parser.SPECIALSNL
email.errors.HeaderWriteError
@@ -1,10 +1,3 @@
# ====================================================================
# TODO: New errors in Python 3.14 that need to be fixed or moved below
# ====================================================================
asyncio.tools
# =======
# >= 3.13
# =======
@@ -1,6 +1,6 @@
# ===========
# 3.9 to 3.11
# ===========
# =======
# <= 3.11
# =======
# Added in Python 3.9.20
email._header_value_parser.NLSET
@@ -50,6 +50,7 @@ xml.etree.cElementTree.XMLPullParser.flush
xml.parsers.expat.XMLParserType.GetReparseDeferralEnabled
xml.parsers.expat.XMLParserType.SetReparseDeferralEnabled
xml.sax.expatreader.ExpatParser.flush
zipfile.ZipInfo.__slots__
# =============================================================
@@ -1,5 +0,0 @@
# ====================================================================
# TODO: New errors in Python 3.14 that need to be fixed or moved below
# ====================================================================
asyncio.tools
@@ -70,22 +70,11 @@ importlib.metadata._meta.SimplePath.__truediv__ # Runtime definition of protoco
# ===================================
# ===========
# 3.9 to 3.10
# ===========
builtins.float.__setformat__ # Internal method for CPython test suite
typing._SpecialForm.__mro_entries__ # Exists at runtime, but missing from stubs
# Will always raise. Not included to avoid type checkers inferring that
# Sentinel instances are callable.
typing_extensions.Sentinel.__call__
# =======
# <= 3.10
# =======
builtins.float.__setformat__ # Internal method for CPython test suite
email.contentmanager.typ
gettext.install # codeset default value is ['unspecified'] so can't be specified
gettext.translation # codeset default value is ['unspecified'] so can't be specified
@@ -100,6 +89,11 @@ tempfile.SpooledTemporaryFile.seekable
tempfile.SpooledTemporaryFile.writable
tkinter.Tk.split # Exists at runtime, but missing from stubs
typing._SpecialForm.__mro_entries__ # Exists at runtime, but missing from stubs
# Will always raise. Not included to avoid type checkers inferring that
# Sentinel instances are callable.
typing_extensions.Sentinel.__call__
# =======
@@ -107,13 +101,14 @@ tkinter.Tk.split # Exists at runtime, but missing from stubs
# =======
_?bz2.BZ2Decompressor.__init__ # function does not accept parameters but C signature is set
configparser.ParsingError.filename
enum.Enum._generate_next_value_
importlib.abc.Finder.find_module
urllib.request.HTTPPasswordMgrWithPriorAuth.__init__ # Args are passed as is to super, so super args are specified
xml.etree.ElementTree.Element.__bool__ # Doesn't really exist; see comments in stub
xml.etree.cElementTree.Element.__bool__ # Doesn't really exist; see comments in stub
platform.platform # runtime default is 0, we pretend it's a bool
# =======
# <= 3.12
@@ -163,11 +158,7 @@ tkinter.tix.TkVersion
# because it's not an ABC that makes any sense and was deprecated in 3.12
_collections_abc.ByteString
ast.Bytes.__new__ # runtime is *args, **kwargs due to a wrapper, but we have more accurate signatures in the stubs
ast.Ellipsis.__new__ # runtime is *args, **kwargs due to a wrapper, but we have more accurate signatures in the stubs
ast.NameConstant.__new__ # runtime is *args, **kwargs due to a wrapper, but we have more accurate signatures in the stubs
ast.Num.__new__ # runtime is *args, **kwargs due to a wrapper, but we have more accurate signatures in the stubs
ast.Str.__new__ # runtime is *args, **kwargs due to a wrapper, but we have more accurate signatures in the stubs
ast.Ellipsis.__new__ # Implementation has *args, but shouldn't allow any
_?hashlib.scrypt # Raises TypeError if salt, n, r or p are None
@@ -215,13 +206,6 @@ importlib.metadata.DeprecatedList.sort
typing.ParamSpec(Args|Kwargs).__origin__
# =================================================================
# Allowlist entries that cannot or should not be fixed; 3.9 to 3.12
# =================================================================
typing\.Annotated # Super-special typing primitive
# =============================================================
# Allowlist entries that cannot or should not be fixed; <= 3.10
# =============================================================
@@ -276,6 +260,11 @@ typing_extensions\.TypeAliasType\.__(parameters|type_params|name|module|value)__
unittest.test # Modules that exist at runtime, but shouldn't be added to typeshed
unittest\.test\..+ # Modules that exist at runtime, but shouldn't be added to typeshed
# Incompatible changes introduced in Python 3.10.17
# (Remove once 3.10.17 becomes available for all platforms)
(email._header_value_parser.get_encoded_word)?
(email._header_value_parser.make_quoted_pairs)?
# =============================================================
# Allowlist entries that cannot or should not be fixed; <= 3.12
@@ -320,11 +309,7 @@ sunau.Au_write.initfp
threading.Lock # Factory function at runtime, but that wouldn't let us use it in type hints
types.SimpleNamespace.__init__ # class doesn't accept positional arguments but has default C signature
typing_extensions\.Annotated # Undocumented implementation details
# Incompatible changes introduced in Python 3.10.17
# (Remove once 3.10.17 becomes available for all platforms)
(email._header_value_parser.get_encoded_word)?
(email._header_value_parser.make_quoted_pairs)?
typing\.Annotated # Super-special typing primitive
# These methods have no default implementation for Python < 3.13.
_pickle.Pickler.persistent_id
@@ -7,7 +7,6 @@
# >= 3.11
# =======
enum.Enum.__init__
typing.NewType.__mro_entries__
@@ -70,13 +69,14 @@ importlib.metadata._meta.SimplePath.__truediv__ # Runtime definition of protoco
# =======
_?bz2.BZ2Decompressor.__init__ # function does not accept parameters but C signature is set
configparser.ParsingError.filename
enum.Enum._generate_next_value_
importlib.abc.Finder.find_module
urllib.request.HTTPPasswordMgrWithPriorAuth.__init__ # Args are passed as is to super, so super args are specified
xml.etree.ElementTree.Element.__bool__ # Doesn't really exist; see comments in stub
xml.etree.cElementTree.Element.__bool__ # Doesn't really exist; see comments in stub
platform.platform # runtime default is 0, we pretend it's a bool
# =======
# <= 3.12
@@ -126,11 +126,7 @@ tkinter.tix.TkVersion
# because it's not an ABC that makes any sense and was deprecated in 3.12
_collections_abc.ByteString
ast.Bytes.__new__ # runtime is *args, **kwargs due to a wrapper, but we have more accurate signatures in the stubs
ast.Ellipsis.__new__ # runtime is *args, **kwargs due to a wrapper, but we have more accurate signatures in the stubs
ast.NameConstant.__new__ # runtime is *args, **kwargs due to a wrapper, but we have more accurate signatures in the stubs
ast.Num.__new__ # runtime is *args, **kwargs due to a wrapper, but we have more accurate signatures in the stubs
ast.Str.__new__ # runtime is *args, **kwargs due to a wrapper, but we have more accurate signatures in the stubs
ast.Ellipsis.__new__ # Implementation has *args, but shouldn't allow any
_?hashlib.scrypt # Raises TypeError if salt, n, r or p are None
@@ -143,11 +139,17 @@ typing\.ByteString
typing_extensions.TypeAliasType.__call__
# ============
# 3.11 to 3.13
# ============
enum.Enum.__init__
# =============================================================
# Allowlist entries that cannot or should not be fixed; >= 3.11
# =============================================================
argparse._MutuallyExclusiveGroup.add_mutually_exclusive_group # deprecated, forwards arguments to super
enum.auto.__init__ # The stub for enum.auto is nothing like the implementation
enum.auto.value # The stub for enum.auto is nothing like the implementation
http.HTTPMethod.description # mutable instance attribute at runtime but we pretend it's a property
@@ -201,11 +203,11 @@ importlib.metadata.DeprecatedList.sort
typing.ParamSpec(Args|Kwargs).__origin__
# =================================================================
# Allowlist entries that cannot or should not be fixed; 3.9 to 3.12
# =================================================================
# ==================================================================
# Allowlist entries that cannot or should not be fixed; 3.11 to 3.13
# ==================================================================
typing\.Annotated # Super-special typing primitive
argparse._MutuallyExclusiveGroup.add_mutually_exclusive_group # deprecated, forwards arguments to super
# =============================================================
@@ -236,6 +238,11 @@ typing_extensions\.TypeAliasType\.__(parameters|type_params|name|module|value)__
unittest.test # Modules that exist at runtime, but shouldn't be added to typeshed
unittest\.test\..+ # Modules that exist at runtime, but shouldn't be added to typeshed
# Incompatible changes introduced in Python 3.11.12
# (Remove once 3.11.12 becomes available for all platforms)
(email._header_value_parser.get_encoded_word)?
(email._header_value_parser.make_quoted_pairs)?
# =============================================================
# Allowlist entries that cannot or should not be fixed; <= 3.12
@@ -280,11 +287,7 @@ sunau.Au_write.initfp
threading.Lock # Factory function at runtime, but that wouldn't let us use it in type hints
types.SimpleNamespace.__init__ # class doesn't accept positional arguments but has default C signature
typing_extensions\.Annotated # Undocumented implementation details
# Incompatible changes introduced in Python 3.11.12
# (Remove once 3.11.12 becomes available for all platforms)
(email._header_value_parser.get_encoded_word)?
(email._header_value_parser.make_quoted_pairs)?
typing\.Annotated # Super-special typing primitive
# These methods have no default implementation for Python < 3.13.
_pickle.Pickler.persistent_id
@@ -7,15 +7,20 @@
# >= 3.12
# =======
# Initialized at runtime
typing_extensions.TypeAliasType.__parameters__
typing_extensions.TypeAliasType.__value__
# Types that require `__setattr__` and `__delattr__` for typing purposes:
types.SimpleNamespace.__setattr__
types.SimpleNamespace.__delattr__
# ============
# 3.12 to 3.13
# ============
# Initialized at runtime
typing_extensions.TypeAliasType.__parameters__
typing_extensions.TypeAliasType.__value__
# ====================================
# Pre-existing errors from Python 3.11
# ====================================
@@ -25,10 +30,16 @@ types.SimpleNamespace.__delattr__
# >= 3.11
# =======
enum.Enum.__init__
typing.NewType.__mro_entries__
# ============
# 3.11 to 3.13
# ============
enum.Enum.__init__
# =======
# >= 3.10
# =======
@@ -111,11 +122,7 @@ tkinter.tix.TkVersion
# because it's not an ABC that makes any sense and was deprecated in 3.12
_collections_abc.ByteString
ast.Bytes.__new__ # runtime is *args, **kwargs due to a wrapper, but we have more accurate signatures in the stubs
ast.Ellipsis.__new__ # runtime is *args, **kwargs due to a wrapper, but we have more accurate signatures in the stubs
ast.NameConstant.__new__ # runtime is *args, **kwargs due to a wrapper, but we have more accurate signatures in the stubs
ast.Num.__new__ # runtime is *args, **kwargs due to a wrapper, but we have more accurate signatures in the stubs
ast.Str.__new__ # runtime is *args, **kwargs due to a wrapper, but we have more accurate signatures in the stubs
ast.Ellipsis.__new__ # Implementation has *args, but shouldn't allow any
_?hashlib.scrypt # Raises TypeError if salt, n, r or p are None
@@ -165,7 +172,6 @@ typing_extensions.SupportsRound.__type_params__
# Allowlist entries that cannot or should not be fixed; >= 3.11
# =============================================================
argparse._MutuallyExclusiveGroup.add_mutually_exclusive_group # deprecated, forwards arguments to super
enum.auto.__init__ # The stub for enum.auto is nothing like the implementation
enum.auto.value # The stub for enum.auto is nothing like the implementation
http.HTTPMethod.description # mutable instance attribute at runtime but we pretend it's a property
@@ -175,6 +181,13 @@ typing\._SpecialForm.* # Super-special typing primitive
typing\.LiteralString # Super-special typing primitive
# ==================================================================
# Allowlist entries that cannot or should not be fixed; 3.11 to 3.13
# ==================================================================
argparse._MutuallyExclusiveGroup.add_mutually_exclusive_group # deprecated, forwards arguments to super
# =============================================================
# Allowlist entries that cannot or should not be fixed; >= 3.10
# =============================================================
@@ -206,13 +219,6 @@ ctypes._endian.SIZEOF_TIME_T # Incorrectly star import.
configparser.LegacyInterpolation.__init__ # runtime is *args, **kwargs, but it's just a passthrough
# =================================================================
# Allowlist entries that cannot or should not be fixed; 3.9 to 3.12
# =================================================================
typing\.Annotated # Super-special typing primitive
# =============================================================
# Allowlist entries that cannot or should not be fixed; <= 3.12
# =============================================================
@@ -256,6 +262,7 @@ sunau.Au_write.initfp
threading.Lock # Factory function at runtime, but that wouldn't let us use it in type hints
types.SimpleNamespace.__init__ # class doesn't accept positional arguments but has default C signature
typing_extensions\.Annotated # Undocumented implementation details
typing\.Annotated # Super-special typing primitive
# These methods have no default implementation for Python < 3.13.
_pickle.Pickler.persistent_id
@@ -12,23 +12,34 @@
# >= 3.12
# =======
# Initialized at runtime
typing_extensions.TypeAliasType.__parameters__
typing_extensions.TypeAliasType.__value__
# Types that require `__setattr__` and `__delattr__` for typing purposes:
types.SimpleNamespace.__setattr__
types.SimpleNamespace.__delattr__
# ============
# 3.12 to 3.13
# ============
# Initialized at runtime
typing_extensions.TypeAliasType.__parameters__
typing_extensions.TypeAliasType.__value__
# =======
# >= 3.11
# =======
enum.Enum.__init__
typing.NewType.__mro_entries__
# ============
# 3.11 to 3.13
# ============
enum.Enum.__init__
# =======
# >= 3.10
# =======
@@ -72,11 +83,7 @@ typing(_extensions)?\.IO\.writelines
# because it's not an ABC that makes any sense and was deprecated in 3.12
_collections_abc.ByteString
ast.Bytes.__new__ # runtime is *args, **kwargs due to a wrapper, but we have more accurate signatures in the stubs
ast.Ellipsis.__new__ # runtime is *args, **kwargs due to a wrapper, but we have more accurate signatures in the stubs
ast.NameConstant.__new__ # runtime is *args, **kwargs due to a wrapper, but we have more accurate signatures in the stubs
ast.Num.__new__ # runtime is *args, **kwargs due to a wrapper, but we have more accurate signatures in the stubs
ast.Str.__new__ # runtime is *args, **kwargs due to a wrapper, but we have more accurate signatures in the stubs
ast.Ellipsis.__new__ # Implementation has *args, but shouldn't allow any
_?hashlib.scrypt # Raises TypeError if salt, n, r or p are None
@@ -155,7 +162,6 @@ typing_extensions.SupportsRound.__type_params__
# Allowlist entries that cannot or should not be fixed; >= 3.11
# =============================================================
argparse._MutuallyExclusiveGroup.add_mutually_exclusive_group # deprecated, forwards arguments to super
enum.auto.__init__ # The stub for enum.auto is nothing like the implementation
enum.auto.value # The stub for enum.auto is nothing like the implementation
http.HTTPMethod.description # mutable instance attribute at runtime but we pretend it's a property
@@ -165,6 +171,13 @@ typing\._SpecialForm.* # Super-special typing primitive
typing\.LiteralString # Super-special typing primitive
# ==================================================================
# Allowlist entries that cannot or should not be fixed; 3.11 to 3.13
# ==================================================================
argparse._MutuallyExclusiveGroup.add_mutually_exclusive_group # deprecated, forwards arguments to super
# =============================================================
# Allowlist entries that cannot or should not be fixed; >= 3.10
# =============================================================
@@ -12,13 +12,12 @@ multiprocessing.managers._BaseDictProxy.__ror__
multiprocessing.managers._BaseDictProxy.fromkeys
multiprocessing.process.BaseProcess.interrupt
multiprocessing.synchronize.SemLock.locked
tarfile.TarFile.zstopen
# =========================
# New errors in Python 3.14
# =========================
# Union and UnionType are aliases in 3.14 but type checkers need some changes
typing_extensions.Union
typing.Union
@@ -30,6 +29,18 @@ types.UnionType.__qualname__
# Assigning `__new__` causes `func` not to get recognized.
functools.partialmethod.__new__
# decorator approximated by classmethod
concurrent.interpreters._crossinterp.classonly.*
# object() sentinels at runtime represented by NewTypes in the stubs
concurrent.interpreters._crossinterp.UNBOUND_ERROR
concurrent.interpreters._crossinterp.UNBOUND_REMOVE
concurrent.interpreters._queues.UNBOUND_ERROR
concurrent.interpreters._queues.UNBOUND_REMOVE
importlib.util.Loader.exec_module # See Lib/importlib/_abc.py. Might be defined for backwards compatibility
# ====================================
# Pre-existing errors from Python 3.13
# ====================================
@@ -57,7 +68,6 @@ typing.NewType.__mro_entries__
builtins.ellipsis # type is not exposed anywhere
importlib._abc.Loader.exec_module # See Lib/importlib/_abc.py. Might be defined for backwards compatibility
importlib.util.Loader.exec_module
# positional-only complaints caused by differences between typing aliases and the "real" classes in the stdlib
_collections_abc.Coroutine.send
@@ -85,6 +95,7 @@ typing(_extensions)?\.IO\.truncate
typing(_extensions)?\.IO\.write
typing(_extensions)?\.IO\.writelines
# =============================================================
# Allowlist entries that cannot or should not be fixed; >= 3.14
# =============================================================
@@ -107,6 +118,45 @@ typing(_extensions)?\.IO\.writelines
(io|typing_extensions)\.Writer\.write
# These multiprocessing proxy methods have *args, **kwargs signatures at runtime,
# But have more precise (accurate) signatures in the stub
multiprocessing.managers._BaseSetProxy.__iter__
multiprocessing.managers._BaseSetProxy.__len__
multiprocessing.managers._BaseSetProxy.clear
multiprocessing.managers._BaseSetProxy.copy
multiprocessing.managers._BaseSetProxy.pop
# Changes from patch releases to be introduced in Python 3.14.0b3
# (Remove once 3.14.0b3 becomes available for all platforms)
(genericpath.__all__)?
(genericpath.ALLOW_MISSING)?
(ntpath.__all__)?
(ntpath.ALLOW_MISSING)?
(os.path.__all__)?
(os.path.ALLOW_MISSING)?
(os.path.realpath)?
(posixpath.__all__)?
(posixpath.ALLOW_MISSING)?
(tarfile.__all__)?
(tarfile.LinkFallbackError)?
(tarfile.TarFile._extract_member)?
(tarfile.TarFile.makelink_with_filter)?
(_?hashlib.new)?
(_?hashlib.(openssl_)?md5)?
(_?hashlib.(openssl_)?sha1)?
(_?hashlib.(openssl_)?sha224)?
(_?hashlib.(openssl_)?sha256)?
(_?hashlib.(openssl_)?sha384)?
(_?hashlib.(openssl_)?sha3_224)?
(_?hashlib.(openssl_)?sha3_256)?
(_?hashlib.(openssl_)?sha3_384)?
(_?hashlib.(openssl_)?sha3_512)?
(_?hashlib.(openssl_)?sha512)?
(_?hashlib.(openssl_)?shake_128)?
(_?hashlib.(openssl_)?shake_256)?
# =============================================================
# Allowlist entries that cannot or should not be fixed; >= 3.13
# =============================================================
@@ -130,12 +180,6 @@ multiprocessing.managers._BaseDictProxy.keys
multiprocessing.managers._BaseDictProxy.popitem
multiprocessing.managers._BaseDictProxy.values
multiprocessing.managers._BaseSetProxy.__iter__
multiprocessing.managers._BaseSetProxy.__len__
multiprocessing.managers._BaseSetProxy.clear
multiprocessing.managers._BaseSetProxy.copy
multiprocessing.managers._BaseSetProxy.pop
# To match `dict`, we lie about the runtime, but use overloads to match the correct behavior
types.MappingProxyType.get
@@ -202,32 +246,3 @@ builtins.property.__set_name__ # Doesn't actually exist
collections\.UserList\.index # ignoring pos-or-keyword parameter
dataclasses.KW_ONLY # white lies around defaults
importlib.metadata._meta.SimplePath.joinpath # Runtime definition of protocol is incorrect
# Changes from patch releases to be introduced in Python 3.14.0b3
# (Remove once 3.14.0b3 becomes available for all platforms)
(genericpath.__all__)?
(genericpath.ALLOW_MISSING)?
(ntpath.__all__)?
(ntpath.ALLOW_MISSING)?
(os.path.__all__)?
(os.path.ALLOW_MISSING)?
(os.path.realpath)?
(posixpath.__all__)?
(posixpath.ALLOW_MISSING)?
(tarfile.__all__)?
(tarfile.LinkFallbackError)?
(tarfile.TarFile._extract_member)?
(tarfile.TarFile.makelink_with_filter)?
(_?hashlib.new)?
(_?hashlib.(openssl_)?md5)?
(_?hashlib.(openssl_)?sha1)?
(_?hashlib.(openssl_)?sha224)?
(_?hashlib.(openssl_)?sha256)?
(_?hashlib.(openssl_)?sha384)?
(_?hashlib.(openssl_)?sha3_224)?
(_?hashlib.(openssl_)?sha3_256)?
(_?hashlib.(openssl_)?sha3_384)?
(_?hashlib.(openssl_)?sha3_512)?
(_?hashlib.(openssl_)?sha512)?
(_?hashlib.(openssl_)?shake_128)?
(_?hashlib.(openssl_)?shake_256)?
@@ -23,12 +23,12 @@ collections.Callable
collections.Mapping.get # Adding None to the Union messed up mypy
collections.Sequence.index # Supporting None in end is not mandatory
# ===========
# =======
# <= 3.10
# ===========
# =======
builtins.float.__setformat__ # Internal method for CPython test suite
typing._SpecialForm.__mro_entries__ # Exists at runtime, but missing from stubs
email.contentmanager.typ
gettext.install # codeset default value is ['unspecified'] so can't be specified
gettext.translation # codeset default value is ['unspecified'] so can't be specified
@@ -43,6 +43,7 @@ tempfile.SpooledTemporaryFile.seekable
tempfile.SpooledTemporaryFile.writable
tkinter.Tk.split # Exists at runtime, but missing from stubs
typing._SpecialForm.__mro_entries__ # Exists at runtime, but missing from stubs
# Will always raise. Not included to avoid type checkers inferring that
# Sentinel instances are callable.
@@ -54,13 +55,14 @@ typing_extensions.Sentinel.__call__
# =======
_?bz2.BZ2Decompressor.__init__ # function does not accept parameters but C signature is set
configparser.ParsingError.filename
enum.Enum._generate_next_value_
importlib.abc.Finder.find_module
urllib.request.HTTPPasswordMgrWithPriorAuth.__init__ # Args are passed as is to super, so super args are specified
xml.etree.ElementTree.Element.__bool__ # Doesn't really exist; see comments in stub
xml.etree.cElementTree.Element.__bool__ # Doesn't really exist; see comments in stub
platform.platform # runtime default is 0, we pretend it's a bool
# =======
# <= 3.12
@@ -110,11 +112,7 @@ tkinter.tix.TkVersion
# because it's not an ABC that makes any sense and was deprecated in 3.12
_collections_abc.ByteString
ast.Bytes.__new__ # runtime is *args, **kwargs due to a wrapper, but we have more accurate signatures in the stubs
ast.Ellipsis.__new__ # runtime is *args, **kwargs due to a wrapper, but we have more accurate signatures in the stubs
ast.NameConstant.__new__ # runtime is *args, **kwargs due to a wrapper, but we have more accurate signatures in the stubs
ast.Num.__new__ # runtime is *args, **kwargs due to a wrapper, but we have more accurate signatures in the stubs
ast.Str.__new__ # runtime is *args, **kwargs due to a wrapper, but we have more accurate signatures in the stubs
ast.Ellipsis.__new__ # Implementation has *args, but shouldn't allow any
_?hashlib.scrypt # Raises TypeError if salt, n, r or p are None
@@ -134,18 +132,6 @@ typing_extensions.TypeAliasType.__call__
ast.FormattedValue.conversion # None on the class, but never None on instances
_ast.FormattedValue.conversion # None on the class, but never None on instances
# =================================================================
# Allowlist entries that cannot or should not be fixed; 3.9 to 3.12
# =================================================================
typing\.Annotated # Super-special typing primitive
# ============================================================
# Allowlist entries that cannot or should not be fixed; <= 3.9
# ============================================================
_ssl.RAND_egd # Depends on the existence and flags of SSL
builtins.classmethod.__get__ # Runtime signature is incorrect (https://github.com/python/cpython/issues/93021)
builtins.property.__get__ # Runtime signature is incorrect (https://github.com/python/cpython/issues/93021)
@@ -227,6 +213,14 @@ typing_extensions\.TypeAliasType\.__(parameters|type_params|name|module|value)__
unittest.test # Modules that exist at runtime, but shouldn't be added to typeshed
unittest\.test\..+ # Modules that exist at runtime, but shouldn't be added to typeshed
# Incompatible changes introduced in Python 3.9.22
# (Remove once 3.9.22 becomes available for all platforms)
(email._header_value_parser.get_encoded_word)?
# Incompatible changes introduced in Python 3.9.23
# (Remove once 3.9.23 becomes available for all platforms)
(email._header_value_parser.make_quoted_pairs)?
# =============================================================
# Allowlist entries that cannot or should not be fixed; <= 3.12
@@ -271,10 +265,7 @@ sunau.Au_write.initfp
threading.Lock # Factory function at runtime, but that wouldn't let us use it in type hints
types.SimpleNamespace.__init__ # class doesn't accept positional arguments but has default C signature
typing_extensions\.Annotated # Undocumented implementation details
# Incompatible changes introduced in Python 3.9.22
# (Remove once 3.9.22 becomes available for all platforms)
(email._header_value_parser.get_encoded_word)?
typing\.Annotated # Super-special typing primitive
# These methods have no default implementation for Python < 3.13.
_pickle.Pickler.persistent_id
@@ -284,7 +275,6 @@ pickle.Unpickler.persistent_load
# Incompatible changes introduced in Python 3.9.23
# (Remove once 3.9.23 becomes available for all platforms)
(email._header_value_parser.make_quoted_pairs)?
(genericpath.__all__)?
(genericpath.ALLOW_MISSING)?
(ntpath.__all__)?
@@ -1,6 +1,6 @@
# ===========
# 3.9 to 3.11
# ===========
# =======
# <= 3.11
# =======
# Incompatible changes introduced in Python 3.10.15
# (Remove once 3.10.15 becomes available for Windows)
@@ -42,7 +42,7 @@ xml.etree.cElementTree.XMLPullParser.flush
xml.parsers.expat.XMLParserType.GetReparseDeferralEnabled
xml.parsers.expat.XMLParserType.SetReparseDeferralEnabled
xml.sax.expatreader.ExpatParser.flush
zipfile.ZipInfo.__slots__
# =============================================================
# Allowlist entries that cannot or should not be fixed; <= 3.12
@@ -1,6 +1,6 @@
# ===========
# 3.9 to 3.11
# ===========
# =======
# <= 3.11
# =======
# Incompatible changes introduced in Python 3.11.10
# (Remove once 3.11.10 becomes available for Windows)
@@ -1,16 +1,3 @@
# ====================================================================
# TODO: New errors in Python 3.14 that need to be fixed or moved below
# ====================================================================
_winapi.COPY_FILE_DIRECTORY
compression.zlib.ZLIBNG_VERSION
encodings.win32_code_page_search_function
nt.readinto
pathlib.Path.group
pathlib.Path.owner
zlib.ZLIBNG_VERSION
# =======
# >= 3.12
# =======
@@ -1,6 +1,6 @@
# ===========
# 3.9 to 3.11
# ===========
# =======
# <= 3.11
# =======
# Incompatible changes introduced in Python 3.9.20
# (Remove once 3.9.20 becomes available for Windows)
@@ -51,7 +51,7 @@ xml.etree.cElementTree.XMLPullParser.flush
xml.parsers.expat.XMLParserType.GetReparseDeferralEnabled
xml.parsers.expat.XMLParserType.SetReparseDeferralEnabled
xml.sax.expatreader.ExpatParser.flush
zipfile.ZipInfo.__slots__
# =============================================================
# Allowlist entries that cannot or should not be fixed; <= 3.12
@@ -4,6 +4,10 @@ import os
from typing import Any, Dict, Generic, Iterable, Mapping, TypeVar, Union
from typing_extensions import Self, assert_type
###################################################################
# Note: tests for `dict.update()` are in `check_MutableMapping.py`.
###################################################################
# These do follow `__init__` overloads order:
# mypy and pyright have different opinions about this one:
# mypy raises: 'Need type annotation for "bad"'
@@ -0,0 +1,94 @@
from typing_extensions import assert_type
def test_min_builtin() -> None:
# legal comparisons that succeed at runtime
b1, b2 = bool(True), bool(False)
i1, i2 = int(1), int(2)
s1, s2 = str("a"), str("b")
f1, f2 = float(0.5), float(2.3)
l1, l2 = list[int]([1, 2]), list[int]([3, 4])
t1, t2 = tuple[str, str](("A", "B")), tuple[str, str](("C", "D"))
tN = tuple[str, ...](["A", "B", "C"])
assert_type(min(b1, b2), bool)
assert_type(min(i1, i2), int)
assert_type(min(s1, s2), str)
assert_type(min(f1, f2), float)
# mixed numerical types (note: float = int or float)
assert_type(min(b1, i1), int)
assert_type(min(i1, b1), int)
assert_type(min(b1, f1), float)
assert_type(min(f1, b1), float)
assert_type(min(i1, f1), float)
assert_type(min(f1, i1), float)
# comparisons with lists and tuples
assert_type(min(l1, l2), list[int])
assert_type(min(t1, t2), tuple[str, str])
assert_type(min(tN, t2), tuple[str, ...])
def test_min_bad_builtin() -> None:
# illegal comparisons that fail at runtime
i1 = int(1)
s1 = str("a")
f1 = float(1.0)
c1, c2 = complex(1.0, 2.0), complex(3.0, 4.0)
list_str = list[str](["A", "B"])
list_int = list[int]([2, 3])
tup_str = tuple[str, str](("A", "B"))
tup_int = tuple[int, int]((2, 3))
# True negatives.
min(c1, c2) # type: ignore
# FIXME: False negatives.
min(i1, s1)
min(s1, f1)
min(f1, list_str)
min(list_str, list_int)
min(tup_str, tup_int)
def test_min_custom_comparison() -> None:
class BoolScalar:
def __bool__(self) -> bool: ...
class FloatScalar:
def __float__(self) -> float: ...
def __ge__(self, other: "FloatScalar") -> BoolScalar: ...
def __gt__(self, other: "FloatScalar") -> BoolScalar: ...
def __lt__(self, other: "FloatScalar") -> BoolScalar: ...
def __le__(self, other: "FloatScalar") -> BoolScalar: ...
f1 = FloatScalar()
f2 = FloatScalar()
assert_type(min(f1, f2), FloatScalar)
def test_min_bad_custom_type() -> None:
class FloatScalar:
def __float__(self) -> float: ...
def __ge__(self, other: "FloatScalar") -> object:
return object()
def __gt__(self, other: "FloatScalar") -> object:
return object()
def __lt__(self, other: "FloatScalar") -> object:
return object()
def __le__(self, other: "FloatScalar") -> object:
return object()
f1 = FloatScalar()
f2 = FloatScalar()
# Note: min(f1, f2) works at runtime, but always returns the second argument.
# therefore, we require returning a boolean-like type for comparisons.
min(f1, f2) # type: ignore
@@ -47,11 +47,11 @@ if sys.version_info >= (3, 14):
with InterpreterPoolExecutor(initializer=_initializer, initargs=("x",)): # type: ignore
...
context = InterpreterPoolExecutor.prepare_context(initializer=_initializer, initargs=(1,), shared={})
context = InterpreterPoolExecutor.prepare_context(initializer=_initializer, initargs=(1,))
worker_context = context[0]()
assert_type(worker_context, concurrent.futures.interpreter.WorkerContext)
resolve_task = context[1]
# Function should enfore that the arguments are correct.
# Function should enforce that the arguments are correct.
res = resolve_task(_initializer, 1)
assert_type(res, tuple[bytes, Literal["function"]])
# When the function is a script, the arguments should be a string.
@@ -5,9 +5,9 @@ from collections.abc import Iterator, Mapping
from datetime import datetime, timedelta
from decimal import Decimal
from fractions import Fraction
from typing import TypedDict
from typing import TypedDict, Union
from typing_extensions import assert_type
from unittest.mock import MagicMock, Mock, patch
from unittest.mock import AsyncMock, MagicMock, Mock, patch
case = unittest.TestCase()
@@ -154,10 +154,17 @@ def f_explicit_new(i: int) -> str:
return "asdf"
@patch("sys.exit", new_callable=lambda: 42)
def f_explicit_new_callable(i: int, new_callable_ret: int) -> str:
return "asdf"
assert_type(f_default_new(1), str)
f_default_new("a") # Not an error due to ParamSpec limitations
assert_type(f_explicit_new(1), str)
f_explicit_new("a") # type: ignore[arg-type]
assert_type(f_explicit_new_callable(1), str)
f_explicit_new_callable("a") # Same as default new
@patch("sys.exit", new=Mock())
@@ -171,3 +178,51 @@ class TestXYZ(unittest.TestCase):
assert_type(TestXYZ.attr, int)
assert_type(TestXYZ.method(), int)
with patch("sys.exit") as default_new_enter:
assert_type(default_new_enter, Union[MagicMock, AsyncMock])
with patch("sys.exit", new=42) as explicit_new_enter:
assert_type(explicit_new_enter, int)
with patch("sys.exit", new_callable=lambda: 42) as explicit_new_callable_enter:
assert_type(explicit_new_callable_enter, int)
###
# Tests for mock.patch.object
###
@patch.object(Decimal, "exp")
def obj_f_default_new(i: int, mock: MagicMock) -> str:
return "asdf"
@patch.object(Decimal, "exp", new=42)
def obj_f_explicit_new(i: int) -> str:
return "asdf"
@patch.object(Decimal, "exp", new_callable=lambda: 42)
def obj_f_explicit_new_callable(i: int, new_callable_ret: int) -> str:
return "asdf"
assert_type(obj_f_default_new(1), str)
obj_f_default_new("a") # Not an error due to ParamSpec limitations
assert_type(obj_f_explicit_new(1), str)
obj_f_explicit_new("a") # type: ignore[arg-type]
assert_type(obj_f_explicit_new_callable(1), str)
obj_f_explicit_new_callable("a") # Same as default new
with patch.object(Decimal, "exp") as obj_default_new_enter:
assert_type(obj_default_new_enter, Union[MagicMock, AsyncMock])
with patch.object(Decimal, "exp", new=42) as obj_explicit_new_enter:
assert_type(obj_explicit_new_enter, int)
with patch.object(Decimal, "exp", new_callable=lambda: 42) as obj_explicit_new_callable_enter:
assert_type(obj_explicit_new_callable_enter, int)
@@ -1,6 +1,6 @@
from __future__ import annotations
from typing import Any, Union
from typing import Any, Hashable, Sequence, Union
from typing_extensions import assert_type
@@ -30,6 +30,15 @@ def check_update_method__str_key() -> None:
d.update([("", "")]) # type: ignore
def test_keywords_allowed_on_dict_update_where_key_type_is_str_supertype(
a: dict[object, Any], b: dict[Hashable, Any], c: dict[Sequence[str], Any], d: dict[str, Any]
) -> None:
a.update(keyword_args_are_accepted="whatever")
b.update(here_too="whooo")
c.update(and_here="hooray")
d.update(also_here="yay")
def check_setdefault_method() -> None:
d: dict[int, str] = {}
d2: dict[int, str | None] = {}
+2
View File
@@ -95,6 +95,7 @@ asyncio.staggered: 3.8-
asyncio.taskgroups: 3.11-
asyncio.threads: 3.9-
asyncio.timeouts: 3.11-
asyncio.tools: 3.14-
asyncio.trsock: 3.8-
asyncore: 3.0-3.11
atexit: 3.0-
@@ -123,6 +124,7 @@ compileall: 3.0-
compression: 3.14-
concurrent: 3.2-
concurrent.futures.interpreter: 3.14-
concurrent.interpreters: 3.14-
configparser: 3.0-
contextlib: 3.0-
contextvars: 3.7-
+5 -5
View File
@@ -108,7 +108,7 @@ from ast import (
unaryop as unaryop,
withitem as withitem,
)
from typing import Literal
from typing import Final
if sys.version_info >= (3, 12):
from ast import (
@@ -137,9 +137,9 @@ if sys.version_info >= (3, 10):
pattern as pattern,
)
PyCF_ALLOW_TOP_LEVEL_AWAIT: Literal[8192]
PyCF_ONLY_AST: Literal[1024]
PyCF_TYPE_COMMENTS: Literal[4096]
PyCF_ALLOW_TOP_LEVEL_AWAIT: Final = 8192
PyCF_ONLY_AST: Final = 1024
PyCF_TYPE_COMMENTS: Final = 4096
if sys.version_info >= (3, 13):
PyCF_OPTIMIZED_AST: Literal[33792]
PyCF_OPTIMIZED_AST: Final = 33792
+9 -9
View File
@@ -1,15 +1,15 @@
from _typeshed import ReadableBuffer
from typing import ClassVar, final
from typing import ClassVar, Final, final
from typing_extensions import Self
BLAKE2B_MAX_DIGEST_SIZE: int = 64
BLAKE2B_MAX_KEY_SIZE: int = 64
BLAKE2B_PERSON_SIZE: int = 16
BLAKE2B_SALT_SIZE: int = 16
BLAKE2S_MAX_DIGEST_SIZE: int = 32
BLAKE2S_MAX_KEY_SIZE: int = 32
BLAKE2S_PERSON_SIZE: int = 8
BLAKE2S_SALT_SIZE: int = 8
BLAKE2B_MAX_DIGEST_SIZE: Final = 64
BLAKE2B_MAX_KEY_SIZE: Final = 64
BLAKE2B_PERSON_SIZE: Final = 16
BLAKE2B_SALT_SIZE: Final = 16
BLAKE2S_MAX_DIGEST_SIZE: Final = 32
BLAKE2S_MAX_KEY_SIZE: Final = 32
BLAKE2S_PERSON_SIZE: Final = 8
BLAKE2S_SALT_SIZE: Final = 8
@final
class blake2b:
@@ -103,5 +103,6 @@ class dict_items(ItemsView[_KT_co, _VT_co]): # undocumented
if sys.version_info >= (3, 12):
@runtime_checkable
class Buffer(Protocol):
__slots__ = ()
@abstractmethod
def __buffer__(self, flags: int, /) -> memoryview: ...
@@ -1,8 +1,10 @@
IMPORT_MAPPING: dict[str, str]
NAME_MAPPING: dict[tuple[str, str], tuple[str, str]]
PYTHON2_EXCEPTIONS: tuple[str, ...]
MULTIPROCESSING_EXCEPTIONS: tuple[str, ...]
REVERSE_IMPORT_MAPPING: dict[str, str]
REVERSE_NAME_MAPPING: dict[tuple[str, str], tuple[str, str]]
PYTHON3_OSERROR_EXCEPTIONS: tuple[str, ...]
PYTHON3_IMPORTERROR_EXCEPTIONS: tuple[str, ...]
from typing import Final
IMPORT_MAPPING: Final[dict[str, str]]
NAME_MAPPING: Final[dict[tuple[str, str], tuple[str, str]]]
PYTHON2_EXCEPTIONS: Final[tuple[str, ...]]
MULTIPROCESSING_EXCEPTIONS: Final[tuple[str, ...]]
REVERSE_IMPORT_MAPPING: Final[dict[str, str]]
REVERSE_NAME_MAPPING: Final[dict[tuple[str, str], tuple[str, str]]]
PYTHON3_OSERROR_EXCEPTIONS: Final[tuple[str, ...]]
PYTHON3_IMPORTERROR_EXCEPTIONS: Final[tuple[str, ...]]
@@ -3,10 +3,11 @@
from _typeshed import Incomplete, WriteableBuffer
from collections.abc import Callable
from io import DEFAULT_BUFFER_SIZE, BufferedIOBase, RawIOBase
from typing import Any, Protocol
from typing import Any, Protocol, type_check_only
BUFFER_SIZE = DEFAULT_BUFFER_SIZE
@type_check_only
class _Reader(Protocol):
def read(self, n: int, /) -> bytes: ...
def seekable(self) -> bool: ...
@@ -39,7 +39,7 @@ class Token(Generic[_T]):
if sys.version_info >= (3, 14):
def __enter__(self) -> Self: ...
def __exit__(
self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None
self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None, /
) -> None: ...
def copy_context() -> Context: ...
+2
View File
@@ -90,6 +90,7 @@ else:
def writer(
csvfile: SupportsWrite[str],
/,
dialect: _DialectLike = "excel",
*,
delimiter: str = ",",
@@ -103,6 +104,7 @@ def writer(
) -> _writer: ...
def reader(
csvfile: Iterable[str],
/,
dialect: _DialectLike = "excel",
*,
delimiter: str = ",",
+15 -12
View File
@@ -5,24 +5,24 @@ from abc import abstractmethod
from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence
from ctypes import CDLL, ArgumentError as ArgumentError, c_void_p
from types import GenericAlias
from typing import Any, ClassVar, Generic, TypeVar, final, overload, type_check_only
from typing import Any, ClassVar, Final, Generic, TypeVar, final, overload, type_check_only
from typing_extensions import Self, TypeAlias
_T = TypeVar("_T")
_CT = TypeVar("_CT", bound=_CData)
FUNCFLAG_CDECL: int
FUNCFLAG_PYTHONAPI: int
FUNCFLAG_USE_ERRNO: int
FUNCFLAG_USE_LASTERROR: int
RTLD_GLOBAL: int
RTLD_LOCAL: int
FUNCFLAG_CDECL: Final = 0x1
FUNCFLAG_PYTHONAPI: Final = 0x4
FUNCFLAG_USE_ERRNO: Final = 0x8
FUNCFLAG_USE_LASTERROR: Final = 0x10
RTLD_GLOBAL: Final[int]
RTLD_LOCAL: Final[int]
if sys.version_info >= (3, 11):
CTYPES_MAX_ARGCOUNT: int
CTYPES_MAX_ARGCOUNT: Final[int]
if sys.version_info >= (3, 12):
SIZEOF_TIME_T: int
SIZEOF_TIME_T: Final[int]
if sys.platform == "win32":
# Description, Source, HelpFile, HelpContext, scode
@@ -37,8 +37,8 @@ if sys.platform == "win32":
def CopyComPointer(src: _PointerLike, dst: _PointerLike | _CArgObject) -> int: ...
FUNCFLAG_HRESULT: int
FUNCFLAG_STDCALL: int
FUNCFLAG_HRESULT: Final = 0x2
FUNCFLAG_STDCALL: Final = 0x0
def FormatError(code: int = ...) -> str: ...
def get_last_error() -> int: ...
@@ -103,7 +103,10 @@ class _SimpleCData(_CData, Generic[_T], metaclass=_PyCSimpleType):
def __init__(self, value: _T = ...) -> None: ... # pyright: ignore[reportInvalidTypeVarUse]
def __ctypes_from_outparam__(self, /) -> _T: ... # type: ignore[override]
@type_check_only
class _CanCastTo(_CData): ...
@type_check_only
class _PointerLike(_CanCastTo): ...
# This type is not exposed. It calls itself _ctypes.PyCPointerType.
@@ -114,7 +117,7 @@ class _PyCPointerType(_CTypeBaseType):
def from_buffer_copy(self: type[_typeshed.Self], buffer: ReadableBuffer, offset: int = 0, /) -> _typeshed.Self: ...
def from_param(self: type[_typeshed.Self], value: Any, /) -> _typeshed.Self | _CArgObject: ...
def in_dll(self: type[_typeshed.Self], dll: CDLL, name: str, /) -> _typeshed.Self: ...
def set_type(self, type: Any, /) -> None: ...
def set_type(self, type: _CTypeBaseType, /) -> None: ...
if sys.version_info < (3, 13):
# Inherited from CType_Type starting on 3.13
def __mul__(cls: type[_CT], other: int) -> type[Array[_CT]]: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues]
+264 -264
View File
@@ -1,7 +1,7 @@
import sys
from _typeshed import ReadOnlyBuffer, SupportsRead, SupportsWrite
from curses import _ncurses_version
from typing import Any, final, overload
from typing import Any, Final, final, overload
from typing_extensions import TypeAlias
# NOTE: This module is ordinarily only available on Unix, but the windows-curses
@@ -11,270 +11,270 @@ from typing_extensions import TypeAlias
_ChType: TypeAlias = str | bytes | int
# ACS codes are only initialized after initscr is called
ACS_BBSS: int
ACS_BLOCK: int
ACS_BOARD: int
ACS_BSBS: int
ACS_BSSB: int
ACS_BSSS: int
ACS_BTEE: int
ACS_BULLET: int
ACS_CKBOARD: int
ACS_DARROW: int
ACS_DEGREE: int
ACS_DIAMOND: int
ACS_GEQUAL: int
ACS_HLINE: int
ACS_LANTERN: int
ACS_LARROW: int
ACS_LEQUAL: int
ACS_LLCORNER: int
ACS_LRCORNER: int
ACS_LTEE: int
ACS_NEQUAL: int
ACS_PI: int
ACS_PLMINUS: int
ACS_PLUS: int
ACS_RARROW: int
ACS_RTEE: int
ACS_S1: int
ACS_S3: int
ACS_S7: int
ACS_S9: int
ACS_SBBS: int
ACS_SBSB: int
ACS_SBSS: int
ACS_SSBB: int
ACS_SSBS: int
ACS_SSSB: int
ACS_SSSS: int
ACS_STERLING: int
ACS_TTEE: int
ACS_UARROW: int
ACS_ULCORNER: int
ACS_URCORNER: int
ACS_VLINE: int
ALL_MOUSE_EVENTS: int
A_ALTCHARSET: int
A_ATTRIBUTES: int
A_BLINK: int
A_BOLD: int
A_CHARTEXT: int
A_COLOR: int
A_DIM: int
A_HORIZONTAL: int
A_INVIS: int
A_ITALIC: int
A_LEFT: int
A_LOW: int
A_NORMAL: int
A_PROTECT: int
A_REVERSE: int
A_RIGHT: int
A_STANDOUT: int
A_TOP: int
A_UNDERLINE: int
A_VERTICAL: int
BUTTON1_CLICKED: int
BUTTON1_DOUBLE_CLICKED: int
BUTTON1_PRESSED: int
BUTTON1_RELEASED: int
BUTTON1_TRIPLE_CLICKED: int
BUTTON2_CLICKED: int
BUTTON2_DOUBLE_CLICKED: int
BUTTON2_PRESSED: int
BUTTON2_RELEASED: int
BUTTON2_TRIPLE_CLICKED: int
BUTTON3_CLICKED: int
BUTTON3_DOUBLE_CLICKED: int
BUTTON3_PRESSED: int
BUTTON3_RELEASED: int
BUTTON3_TRIPLE_CLICKED: int
BUTTON4_CLICKED: int
BUTTON4_DOUBLE_CLICKED: int
BUTTON4_PRESSED: int
BUTTON4_RELEASED: int
BUTTON4_TRIPLE_CLICKED: int
ACS_BBSS: Final[int]
ACS_BLOCK: Final[int]
ACS_BOARD: Final[int]
ACS_BSBS: Final[int]
ACS_BSSB: Final[int]
ACS_BSSS: Final[int]
ACS_BTEE: Final[int]
ACS_BULLET: Final[int]
ACS_CKBOARD: Final[int]
ACS_DARROW: Final[int]
ACS_DEGREE: Final[int]
ACS_DIAMOND: Final[int]
ACS_GEQUAL: Final[int]
ACS_HLINE: Final[int]
ACS_LANTERN: Final[int]
ACS_LARROW: Final[int]
ACS_LEQUAL: Final[int]
ACS_LLCORNER: Final[int]
ACS_LRCORNER: Final[int]
ACS_LTEE: Final[int]
ACS_NEQUAL: Final[int]
ACS_PI: Final[int]
ACS_PLMINUS: Final[int]
ACS_PLUS: Final[int]
ACS_RARROW: Final[int]
ACS_RTEE: Final[int]
ACS_S1: Final[int]
ACS_S3: Final[int]
ACS_S7: Final[int]
ACS_S9: Final[int]
ACS_SBBS: Final[int]
ACS_SBSB: Final[int]
ACS_SBSS: Final[int]
ACS_SSBB: Final[int]
ACS_SSBS: Final[int]
ACS_SSSB: Final[int]
ACS_SSSS: Final[int]
ACS_STERLING: Final[int]
ACS_TTEE: Final[int]
ACS_UARROW: Final[int]
ACS_ULCORNER: Final[int]
ACS_URCORNER: Final[int]
ACS_VLINE: Final[int]
ALL_MOUSE_EVENTS: Final[int]
A_ALTCHARSET: Final[int]
A_ATTRIBUTES: Final[int]
A_BLINK: Final[int]
A_BOLD: Final[int]
A_CHARTEXT: Final[int]
A_COLOR: Final[int]
A_DIM: Final[int]
A_HORIZONTAL: Final[int]
A_INVIS: Final[int]
A_ITALIC: Final[int]
A_LEFT: Final[int]
A_LOW: Final[int]
A_NORMAL: Final[int]
A_PROTECT: Final[int]
A_REVERSE: Final[int]
A_RIGHT: Final[int]
A_STANDOUT: Final[int]
A_TOP: Final[int]
A_UNDERLINE: Final[int]
A_VERTICAL: Final[int]
BUTTON1_CLICKED: Final[int]
BUTTON1_DOUBLE_CLICKED: Final[int]
BUTTON1_PRESSED: Final[int]
BUTTON1_RELEASED: Final[int]
BUTTON1_TRIPLE_CLICKED: Final[int]
BUTTON2_CLICKED: Final[int]
BUTTON2_DOUBLE_CLICKED: Final[int]
BUTTON2_PRESSED: Final[int]
BUTTON2_RELEASED: Final[int]
BUTTON2_TRIPLE_CLICKED: Final[int]
BUTTON3_CLICKED: Final[int]
BUTTON3_DOUBLE_CLICKED: Final[int]
BUTTON3_PRESSED: Final[int]
BUTTON3_RELEASED: Final[int]
BUTTON3_TRIPLE_CLICKED: Final[int]
BUTTON4_CLICKED: Final[int]
BUTTON4_DOUBLE_CLICKED: Final[int]
BUTTON4_PRESSED: Final[int]
BUTTON4_RELEASED: Final[int]
BUTTON4_TRIPLE_CLICKED: Final[int]
# Darwin ncurses doesn't provide BUTTON5_* constants prior to 3.12.10 and 3.13.3
if sys.version_info >= (3, 10):
if sys.version_info >= (3, 12) or sys.platform != "darwin":
BUTTON5_PRESSED: int
BUTTON5_RELEASED: int
BUTTON5_CLICKED: int
BUTTON5_DOUBLE_CLICKED: int
BUTTON5_TRIPLE_CLICKED: int
BUTTON_ALT: int
BUTTON_CTRL: int
BUTTON_SHIFT: int
COLOR_BLACK: int
COLOR_BLUE: int
COLOR_CYAN: int
COLOR_GREEN: int
COLOR_MAGENTA: int
COLOR_RED: int
COLOR_WHITE: int
COLOR_YELLOW: int
ERR: int
KEY_A1: int
KEY_A3: int
KEY_B2: int
KEY_BACKSPACE: int
KEY_BEG: int
KEY_BREAK: int
KEY_BTAB: int
KEY_C1: int
KEY_C3: int
KEY_CANCEL: int
KEY_CATAB: int
KEY_CLEAR: int
KEY_CLOSE: int
KEY_COMMAND: int
KEY_COPY: int
KEY_CREATE: int
KEY_CTAB: int
KEY_DC: int
KEY_DL: int
KEY_DOWN: int
KEY_EIC: int
KEY_END: int
KEY_ENTER: int
KEY_EOL: int
KEY_EOS: int
KEY_EXIT: int
KEY_F0: int
KEY_F1: int
KEY_F10: int
KEY_F11: int
KEY_F12: int
KEY_F13: int
KEY_F14: int
KEY_F15: int
KEY_F16: int
KEY_F17: int
KEY_F18: int
KEY_F19: int
KEY_F2: int
KEY_F20: int
KEY_F21: int
KEY_F22: int
KEY_F23: int
KEY_F24: int
KEY_F25: int
KEY_F26: int
KEY_F27: int
KEY_F28: int
KEY_F29: int
KEY_F3: int
KEY_F30: int
KEY_F31: int
KEY_F32: int
KEY_F33: int
KEY_F34: int
KEY_F35: int
KEY_F36: int
KEY_F37: int
KEY_F38: int
KEY_F39: int
KEY_F4: int
KEY_F40: int
KEY_F41: int
KEY_F42: int
KEY_F43: int
KEY_F44: int
KEY_F45: int
KEY_F46: int
KEY_F47: int
KEY_F48: int
KEY_F49: int
KEY_F5: int
KEY_F50: int
KEY_F51: int
KEY_F52: int
KEY_F53: int
KEY_F54: int
KEY_F55: int
KEY_F56: int
KEY_F57: int
KEY_F58: int
KEY_F59: int
KEY_F6: int
KEY_F60: int
KEY_F61: int
KEY_F62: int
KEY_F63: int
KEY_F7: int
KEY_F8: int
KEY_F9: int
KEY_FIND: int
KEY_HELP: int
KEY_HOME: int
KEY_IC: int
KEY_IL: int
KEY_LEFT: int
KEY_LL: int
KEY_MARK: int
KEY_MAX: int
KEY_MESSAGE: int
KEY_MIN: int
KEY_MOUSE: int
KEY_MOVE: int
KEY_NEXT: int
KEY_NPAGE: int
KEY_OPEN: int
KEY_OPTIONS: int
KEY_PPAGE: int
KEY_PREVIOUS: int
KEY_PRINT: int
KEY_REDO: int
KEY_REFERENCE: int
KEY_REFRESH: int
KEY_REPLACE: int
KEY_RESET: int
KEY_RESIZE: int
KEY_RESTART: int
KEY_RESUME: int
KEY_RIGHT: int
KEY_SAVE: int
KEY_SBEG: int
KEY_SCANCEL: int
KEY_SCOMMAND: int
KEY_SCOPY: int
KEY_SCREATE: int
KEY_SDC: int
KEY_SDL: int
KEY_SELECT: int
KEY_SEND: int
KEY_SEOL: int
KEY_SEXIT: int
KEY_SF: int
KEY_SFIND: int
KEY_SHELP: int
KEY_SHOME: int
KEY_SIC: int
KEY_SLEFT: int
KEY_SMESSAGE: int
KEY_SMOVE: int
KEY_SNEXT: int
KEY_SOPTIONS: int
KEY_SPREVIOUS: int
KEY_SPRINT: int
KEY_SR: int
KEY_SREDO: int
KEY_SREPLACE: int
KEY_SRESET: int
KEY_SRIGHT: int
KEY_SRSUME: int
KEY_SSAVE: int
KEY_SSUSPEND: int
KEY_STAB: int
KEY_SUNDO: int
KEY_SUSPEND: int
KEY_UNDO: int
KEY_UP: int
OK: int
REPORT_MOUSE_POSITION: int
BUTTON5_PRESSED: Final[int]
BUTTON5_RELEASED: Final[int]
BUTTON5_CLICKED: Final[int]
BUTTON5_DOUBLE_CLICKED: Final[int]
BUTTON5_TRIPLE_CLICKED: Final[int]
BUTTON_ALT: Final[int]
BUTTON_CTRL: Final[int]
BUTTON_SHIFT: Final[int]
COLOR_BLACK: Final[int]
COLOR_BLUE: Final[int]
COLOR_CYAN: Final[int]
COLOR_GREEN: Final[int]
COLOR_MAGENTA: Final[int]
COLOR_RED: Final[int]
COLOR_WHITE: Final[int]
COLOR_YELLOW: Final[int]
ERR: Final[int]
KEY_A1: Final[int]
KEY_A3: Final[int]
KEY_B2: Final[int]
KEY_BACKSPACE: Final[int]
KEY_BEG: Final[int]
KEY_BREAK: Final[int]
KEY_BTAB: Final[int]
KEY_C1: Final[int]
KEY_C3: Final[int]
KEY_CANCEL: Final[int]
KEY_CATAB: Final[int]
KEY_CLEAR: Final[int]
KEY_CLOSE: Final[int]
KEY_COMMAND: Final[int]
KEY_COPY: Final[int]
KEY_CREATE: Final[int]
KEY_CTAB: Final[int]
KEY_DC: Final[int]
KEY_DL: Final[int]
KEY_DOWN: Final[int]
KEY_EIC: Final[int]
KEY_END: Final[int]
KEY_ENTER: Final[int]
KEY_EOL: Final[int]
KEY_EOS: Final[int]
KEY_EXIT: Final[int]
KEY_F0: Final[int]
KEY_F1: Final[int]
KEY_F10: Final[int]
KEY_F11: Final[int]
KEY_F12: Final[int]
KEY_F13: Final[int]
KEY_F14: Final[int]
KEY_F15: Final[int]
KEY_F16: Final[int]
KEY_F17: Final[int]
KEY_F18: Final[int]
KEY_F19: Final[int]
KEY_F2: Final[int]
KEY_F20: Final[int]
KEY_F21: Final[int]
KEY_F22: Final[int]
KEY_F23: Final[int]
KEY_F24: Final[int]
KEY_F25: Final[int]
KEY_F26: Final[int]
KEY_F27: Final[int]
KEY_F28: Final[int]
KEY_F29: Final[int]
KEY_F3: Final[int]
KEY_F30: Final[int]
KEY_F31: Final[int]
KEY_F32: Final[int]
KEY_F33: Final[int]
KEY_F34: Final[int]
KEY_F35: Final[int]
KEY_F36: Final[int]
KEY_F37: Final[int]
KEY_F38: Final[int]
KEY_F39: Final[int]
KEY_F4: Final[int]
KEY_F40: Final[int]
KEY_F41: Final[int]
KEY_F42: Final[int]
KEY_F43: Final[int]
KEY_F44: Final[int]
KEY_F45: Final[int]
KEY_F46: Final[int]
KEY_F47: Final[int]
KEY_F48: Final[int]
KEY_F49: Final[int]
KEY_F5: Final[int]
KEY_F50: Final[int]
KEY_F51: Final[int]
KEY_F52: Final[int]
KEY_F53: Final[int]
KEY_F54: Final[int]
KEY_F55: Final[int]
KEY_F56: Final[int]
KEY_F57: Final[int]
KEY_F58: Final[int]
KEY_F59: Final[int]
KEY_F6: Final[int]
KEY_F60: Final[int]
KEY_F61: Final[int]
KEY_F62: Final[int]
KEY_F63: Final[int]
KEY_F7: Final[int]
KEY_F8: Final[int]
KEY_F9: Final[int]
KEY_FIND: Final[int]
KEY_HELP: Final[int]
KEY_HOME: Final[int]
KEY_IC: Final[int]
KEY_IL: Final[int]
KEY_LEFT: Final[int]
KEY_LL: Final[int]
KEY_MARK: Final[int]
KEY_MAX: Final[int]
KEY_MESSAGE: Final[int]
KEY_MIN: Final[int]
KEY_MOUSE: Final[int]
KEY_MOVE: Final[int]
KEY_NEXT: Final[int]
KEY_NPAGE: Final[int]
KEY_OPEN: Final[int]
KEY_OPTIONS: Final[int]
KEY_PPAGE: Final[int]
KEY_PREVIOUS: Final[int]
KEY_PRINT: Final[int]
KEY_REDO: Final[int]
KEY_REFERENCE: Final[int]
KEY_REFRESH: Final[int]
KEY_REPLACE: Final[int]
KEY_RESET: Final[int]
KEY_RESIZE: Final[int]
KEY_RESTART: Final[int]
KEY_RESUME: Final[int]
KEY_RIGHT: Final[int]
KEY_SAVE: Final[int]
KEY_SBEG: Final[int]
KEY_SCANCEL: Final[int]
KEY_SCOMMAND: Final[int]
KEY_SCOPY: Final[int]
KEY_SCREATE: Final[int]
KEY_SDC: Final[int]
KEY_SDL: Final[int]
KEY_SELECT: Final[int]
KEY_SEND: Final[int]
KEY_SEOL: Final[int]
KEY_SEXIT: Final[int]
KEY_SF: Final[int]
KEY_SFIND: Final[int]
KEY_SHELP: Final[int]
KEY_SHOME: Final[int]
KEY_SIC: Final[int]
KEY_SLEFT: Final[int]
KEY_SMESSAGE: Final[int]
KEY_SMOVE: Final[int]
KEY_SNEXT: Final[int]
KEY_SOPTIONS: Final[int]
KEY_SPREVIOUS: Final[int]
KEY_SPRINT: Final[int]
KEY_SR: Final[int]
KEY_SREDO: Final[int]
KEY_SREPLACE: Final[int]
KEY_SRESET: Final[int]
KEY_SRIGHT: Final[int]
KEY_SRSUME: Final[int]
KEY_SSAVE: Final[int]
KEY_SSUSPEND: Final[int]
KEY_STAB: Final[int]
KEY_SUNDO: Final[int]
KEY_SUSPEND: Final[int]
KEY_UNDO: Final[int]
KEY_UP: Final[int]
OK: Final[int]
REPORT_MOUSE_POSITION: Final[int]
_C_API: Any
version: bytes
version: Final[bytes]
def baudrate() -> int: ...
def beep() -> None: ...
@@ -394,8 +394,8 @@ class window: # undocumented
def attroff(self, attr: int, /) -> None: ...
def attron(self, attr: int, /) -> None: ...
def attrset(self, attr: int, /) -> None: ...
def bkgd(self, ch: _ChType, attr: int = ..., /) -> None: ...
def bkgdset(self, ch: _ChType, attr: int = ..., /) -> None: ...
def bkgd(self, ch: _ChType, attr: int = 0, /) -> None: ...
def bkgdset(self, ch: _ChType, attr: int = 0, /) -> None: ...
def border(
self,
ls: _ChType = ...,
@@ -433,7 +433,7 @@ class window: # undocumented
def derwin(self, begin_y: int, begin_x: int) -> window: ...
@overload
def derwin(self, nlines: int, ncols: int, begin_y: int, begin_x: int) -> window: ...
def echochar(self, ch: _ChType, attr: int = ..., /) -> None: ...
def echochar(self, ch: _ChType, attr: int = 0, /) -> None: ...
def enclose(self, y: int, x: int, /) -> bool: ...
def erase(self) -> None: ...
def getbegyx(self) -> tuple[int, int]: ...
@@ -1,8 +1,8 @@
from _curses import window
from typing import final
from typing import Final, final
__version__: str
version: str
__version__: Final[str]
version: Final[str]
class error(Exception): ...
+2 -2
View File
@@ -1,7 +1,7 @@
import sys
from _typeshed import ReadOnlyBuffer, StrOrBytesPath
from types import TracebackType
from typing import TypeVar, final, overload, type_check_only
from typing import Final, TypeVar, final, overload, type_check_only
from typing_extensions import Self, TypeAlias
if sys.platform != "win32":
@@ -10,7 +10,7 @@ if sys.platform != "win32":
_ValueType: TypeAlias = str | ReadOnlyBuffer
class error(OSError): ...
library: str
library: Final[str]
# Actual typename dbm, not exposed by the implementation
@final
@@ -6,6 +6,7 @@ from _typeshed.importlib import LoaderProtocol
from collections.abc import Mapping, Sequence
from types import ModuleType
from typing import Any, ClassVar
from typing_extensions import deprecated
# Signature of `builtins.__import__` should be kept identical to `importlib.__import__`
def __import__(
@@ -49,6 +50,7 @@ class BuiltinImporter(importlib.abc.MetaPathFinder, importlib.abc.InspectLoader)
# MetaPathFinder
if sys.version_info < (3, 12):
@classmethod
@deprecated("Deprecated since Python 3.4; removed in Python 3.12. Use `find_spec()` instead.")
def find_module(cls, fullname: str, path: Sequence[str] | None = None) -> importlib.abc.Loader | None: ...
@classmethod
@@ -67,6 +69,10 @@ class BuiltinImporter(importlib.abc.MetaPathFinder, importlib.abc.InspectLoader)
# Loader
if sys.version_info < (3, 12):
@staticmethod
@deprecated(
"Deprecated since Python 3.4; removed in Python 3.12. "
"The module spec is now used by the import machinery to generate a module repr."
)
def module_repr(module: types.ModuleType) -> str: ...
if sys.version_info >= (3, 10):
@staticmethod
@@ -83,6 +89,7 @@ class FrozenImporter(importlib.abc.MetaPathFinder, importlib.abc.InspectLoader):
# MetaPathFinder
if sys.version_info < (3, 12):
@classmethod
@deprecated("Deprecated since Python 3.4; removed in Python 3.12. Use `find_spec()` instead.")
def find_module(cls, fullname: str, path: Sequence[str] | None = None) -> importlib.abc.Loader | None: ...
@classmethod
@@ -101,6 +108,10 @@ class FrozenImporter(importlib.abc.MetaPathFinder, importlib.abc.InspectLoader):
# Loader
if sys.version_info < (3, 12):
@staticmethod
@deprecated(
"Deprecated since Python 3.4; removed in Python 3.12. "
"The module spec is now used by the import machinery to generate a module repr."
)
def module_repr(m: types.ModuleType) -> str: ...
if sys.version_info >= (3, 10):
@staticmethod
@@ -9,7 +9,7 @@ from _typeshed.importlib import LoaderProtocol
from collections.abc import Callable, Iterable, Iterator, Mapping, MutableSequence, Sequence
from importlib.machinery import ModuleSpec
from importlib.metadata import DistributionFinder, PathDistribution
from typing import Any, Literal
from typing import Any, Final, Literal
from typing_extensions import Self, deprecated
if sys.version_info >= (3, 10):
@@ -24,7 +24,7 @@ else:
path_sep: Literal["/"]
path_sep_tuple: tuple[Literal["/"]]
MAGIC_NUMBER: bytes
MAGIC_NUMBER: Final[bytes]
def cache_from_source(path: StrPath, debug_override: bool | None = None, *, optimization: Any | None = None) -> str: ...
def source_from_cache(path: StrPath) -> str: ...
@@ -37,12 +37,13 @@ def spec_from_file_location(
submodule_search_locations: list[str] | None = ...,
) -> importlib.machinery.ModuleSpec | None: ...
@deprecated(
"Deprecated as of Python 3.6: Use site configuration instead. "
"Deprecated since Python 3.6. Use site configuration instead. "
"Future versions of Python may not enable this finder by default."
)
class WindowsRegistryFinder(importlib.abc.MetaPathFinder):
if sys.version_info < (3, 12):
@classmethod
@deprecated("Deprecated since Python 3.4; removed in Python 3.12. Use `find_spec()` instead.")
def find_module(cls, fullname: str, path: Sequence[str] | None = None) -> importlib.abc.Loader | None: ...
@classmethod
@@ -70,13 +71,14 @@ class PathFinder(importlib.abc.MetaPathFinder):
) -> ModuleSpec | None: ...
if sys.version_info < (3, 12):
@classmethod
@deprecated("Deprecated since Python 3.4; removed in Python 3.12. Use `find_spec()` instead.")
def find_module(cls, fullname: str, path: Sequence[str] | None = None) -> importlib.abc.Loader | None: ...
SOURCE_SUFFIXES: list[str]
DEBUG_BYTECODE_SUFFIXES: list[str]
OPTIMIZED_BYTECODE_SUFFIXES: list[str]
BYTECODE_SUFFIXES: list[str]
EXTENSION_SUFFIXES: list[str]
SOURCE_SUFFIXES: Final[list[str]]
DEBUG_BYTECODE_SUFFIXES: Final = [".pyc"]
OPTIMIZED_BYTECODE_SUFFIXES: Final = [".pyc"]
BYTECODE_SUFFIXES: Final = [".pyc"]
EXTENSION_SUFFIXES: Final[list[str]]
class FileFinder(importlib.abc.PathEntryFinder):
path: str
@@ -153,12 +155,15 @@ if sys.version_info >= (3, 11):
def get_code(self, fullname: str) -> types.CodeType: ...
def create_module(self, spec: ModuleSpec) -> None: ...
def exec_module(self, module: types.ModuleType) -> None: ...
@deprecated("load_module() is deprecated; use exec_module() instead")
@deprecated("Deprecated since Python 3.10; will be removed in Python 3.15. Use `exec_module()` instead.")
def load_module(self, fullname: str) -> types.ModuleType: ...
def get_resource_reader(self, module: types.ModuleType) -> importlib.readers.NamespaceReader: ...
if sys.version_info < (3, 12):
@staticmethod
@deprecated("module_repr() is deprecated, and has been removed in Python 3.12")
@deprecated(
"Deprecated since Python 3.4; removed in Python 3.12. "
"The module spec is now used by the import machinery to generate a module repr."
)
def module_repr(module: types.ModuleType) -> str: ...
_NamespaceLoader = NamespaceLoader
@@ -172,16 +177,23 @@ else:
def get_code(self, fullname: str) -> types.CodeType: ...
def create_module(self, spec: ModuleSpec) -> None: ...
def exec_module(self, module: types.ModuleType) -> None: ...
@deprecated("load_module() is deprecated; use exec_module() instead")
def load_module(self, fullname: str) -> types.ModuleType: ...
if sys.version_info >= (3, 10):
@deprecated("Deprecated since Python 3.10; will be removed in Python 3.15. Use `exec_module()` instead.")
def load_module(self, fullname: str) -> types.ModuleType: ...
@staticmethod
@deprecated("module_repr() is deprecated, and has been removed in Python 3.12")
@deprecated(
"Deprecated since Python 3.4; removed in Python 3.12. "
"The module spec is now used by the import machinery to generate a module repr."
)
def module_repr(module: types.ModuleType) -> str: ...
def get_resource_reader(self, module: types.ModuleType) -> importlib.readers.NamespaceReader: ...
else:
def load_module(self, fullname: str) -> types.ModuleType: ...
@classmethod
@deprecated("module_repr() is deprecated, and has been removed in Python 3.12")
@deprecated(
"Deprecated since Python 3.4; removed in Python 3.12. "
"The module spec is now used by the import machinery to generate a module repr."
)
def module_repr(cls, module: types.ModuleType) -> str: ...
if sys.version_info >= (3, 13):
+2 -1
View File
@@ -1,7 +1,7 @@
import sys
from _typeshed import ReadOnlyBuffer, StrOrBytesPath
from types import TracebackType
from typing import TypeVar, overload
from typing import TypeVar, overload, type_check_only
from typing_extensions import Self, TypeAlias
if sys.platform != "win32":
@@ -13,6 +13,7 @@ if sys.platform != "win32":
class error(OSError): ...
# Actual typename gdbm, not exposed by the implementation
@type_check_only
class _gdbm:
def firstkey(self) -> bytes | None: ...
def nextkey(self, key: _KeyType) -> bytes | None: ...
+4 -5
View File
@@ -1,18 +1,17 @@
import sys
from typing import Any, Final, TypeVar
_T = TypeVar("_T") # list items must be comparable
from _typeshed import SupportsRichComparisonT as _T # All type variable use in this module requires comparability.
from typing import Final
__about__: Final[str]
def heapify(heap: list[Any], /) -> None: ... # list items must be comparable
def heapify(heap: list[_T], /) -> None: ...
def heappop(heap: list[_T], /) -> _T: ...
def heappush(heap: list[_T], item: _T, /) -> None: ...
def heappushpop(heap: list[_T], item: _T, /) -> _T: ...
def heapreplace(heap: list[_T], item: _T, /) -> _T: ...
if sys.version_info >= (3, 14):
def heapify_max(heap: list[Any], /) -> None: ... # list items must be comparable
def heapify_max(heap: list[_T], /) -> None: ...
def heappop_max(heap: list[_T], /) -> _T: ...
def heappush_max(heap: list[_T], item: _T, /) -> None: ...
def heappushpop_max(heap: list[_T], item: _T, /) -> _T: ...
@@ -17,15 +17,15 @@ class ChannelID:
def send(self) -> Self: ...
@property
def recv(self) -> Self: ...
def __eq__(self, other: object) -> bool: ...
def __ge__(self, other: ChannelID) -> bool: ...
def __gt__(self, other: ChannelID) -> bool: ...
def __eq__(self, other: object, /) -> bool: ...
def __ge__(self, other: ChannelID, /) -> bool: ...
def __gt__(self, other: ChannelID, /) -> bool: ...
def __hash__(self) -> int: ...
def __index__(self) -> int: ...
def __int__(self) -> int: ...
def __le__(self, other: ChannelID) -> bool: ...
def __lt__(self, other: ChannelID) -> bool: ...
def __ne__(self, other: object) -> bool: ...
def __le__(self, other: ChannelID, /) -> bool: ...
def __lt__(self, other: ChannelID, /) -> bool: ...
def __ne__(self, other: object, /) -> bool: ...
@final
class ChannelInfo(structseq[int], tuple[bool, bool, bool, int, int, int, int, int]):
@@ -1,9 +1,12 @@
import types
from collections.abc import Callable, Mapping
from typing import Final, Literal, SupportsIndex
from collections.abc import Callable
from typing import Any, Final, Literal, SupportsIndex, TypeVar, overload
from typing_extensions import TypeAlias
_R = TypeVar("_R")
_Configs: TypeAlias = Literal["default", "isolated", "legacy", "empty", ""]
_SharedDict: TypeAlias = dict[str, Any] # many objects can be shared
class InterpreterError(Exception): ...
class InterpreterNotFoundError(InterpreterError): ...
@@ -15,35 +18,40 @@ class CrossInterpreterBufferView:
def new_config(name: _Configs = "isolated", /, **overides: object) -> types.SimpleNamespace: ...
def create(config: types.SimpleNamespace | _Configs | None = "isolated", *, reqrefs: bool = False) -> int: ...
def destroy(id: SupportsIndex, *, restrict: bool = False) -> None: ...
def list_all(*, require_ready: bool) -> list[tuple[int, int]]: ...
def get_current() -> tuple[int, int]: ...
def get_main() -> tuple[int, int]: ...
def list_all(*, require_ready: bool = False) -> list[tuple[int, _Whence]]: ...
def get_current() -> tuple[int, _Whence]: ...
def get_main() -> tuple[int, _Whence]: ...
def is_running(id: SupportsIndex, *, restrict: bool = False) -> bool: ...
def get_config(id: SupportsIndex, *, restrict: bool = False) -> types.SimpleNamespace: ...
def whence(id: SupportsIndex) -> int: ...
def whence(id: SupportsIndex) -> _Whence: ...
def exec(
id: SupportsIndex, code: str | types.CodeType | Callable[[], object], shared: bool | None = None, *, restrict: bool = False
id: SupportsIndex, code: str | types.CodeType | Callable[[], object], shared: _SharedDict = {}, *, restrict: bool = False
) -> None | types.SimpleNamespace: ...
def call(
id: SupportsIndex,
callable: Callable[..., object],
args: tuple[object, ...] | None = None,
kwargs: dict[str, object] | None = None,
callable: Callable[..., _R],
args: tuple[Any, ...] = (),
kwargs: dict[str, Any] = {},
*,
preserve_exc: bool = False,
restrict: bool = False,
) -> object: ...
) -> tuple[_R, types.SimpleNamespace]: ...
def run_string(
id: SupportsIndex, script: str | types.CodeType | Callable[[], object], shared: bool | None = None, *, restrict: bool = False
id: SupportsIndex, script: str | types.CodeType | Callable[[], object], shared: _SharedDict = {}, *, restrict: bool = False
) -> None: ...
def run_func(
id: SupportsIndex, func: types.CodeType | Callable[[], object], shared: bool | None = None, *, restrict: bool = False
id: SupportsIndex, func: types.CodeType | Callable[[], object], shared: _SharedDict = {}, *, restrict: bool = False
) -> None: ...
def set___main___attrs(id: SupportsIndex, updates: Mapping[str, object], *, restrict: bool = False) -> None: ...
def set___main___attrs(id: SupportsIndex, updates: _SharedDict, *, restrict: bool = False) -> None: ...
def incref(id: SupportsIndex, *, implieslink: bool = False, restrict: bool = False) -> None: ...
def decref(id: SupportsIndex, *, restrict: bool = False) -> None: ...
def is_shareable(obj: object) -> bool: ...
def capture_exception(exc: BaseException | None = None) -> types.SimpleNamespace: ...
@overload
def capture_exception(exc: BaseException) -> types.SimpleNamespace: ...
@overload
def capture_exception(exc: None = None) -> types.SimpleNamespace | None: ...
_Whence: TypeAlias = Literal[0, 1, 2, 3, 4, 5]
WHENCE_UNKNOWN: Final = 0
WHENCE_RUNTIME: Final = 1
WHENCE_LEGACY_CAPI: Final = 2
+1
View File
@@ -88,6 +88,7 @@ class BytesIO(BufferedIOBase, _BufferedIOBase, BinaryIO): # type: ignore[misc]
def readlines(self, size: int | None = None, /) -> list[bytes]: ...
def seek(self, pos: int, whence: int = 0, /) -> int: ...
@type_check_only
class _BufferedReaderStream(Protocol):
def read(self, n: int = ..., /) -> bytes: ...
# Optional: def readall(self) -> bytes: ...
+3 -3
View File
@@ -11,7 +11,7 @@ class make_encoder:
@property
def key_separator(self) -> str: ...
@property
def indent(self) -> int | None: ...
def indent(self) -> str | None: ...
@property
def markers(self) -> dict[int, Any] | None: ...
@property
@@ -25,7 +25,7 @@ class make_encoder:
markers: dict[int, Any] | None,
default: Callable[[Any], Any],
encoder: Callable[[str], str],
indent: int | None,
indent: str | None,
key_separator: str,
item_separator: str,
sort_keys: bool,
@@ -48,4 +48,4 @@ class make_scanner:
def encode_basestring(s: str, /) -> str: ...
def encode_basestring_ascii(s: str, /) -> str: ...
def scanstring(string: str, end: int, strict: bool = ...) -> tuple[str, int]: ...
def scanstring(string: str, end: int, strict: bool = True) -> tuple[str, int]: ...
+2 -2
View File
@@ -16,7 +16,7 @@ CHECK_CRC64: Final = 4
CHECK_SHA256: Final = 10
CHECK_ID_MAX: Final = 15
CHECK_UNKNOWN: Final = 16
FILTER_LZMA1: int # v big number
FILTER_LZMA1: Final[int] # v big number
FILTER_LZMA2: Final = 33
FILTER_DELTA: Final = 3
FILTER_X86: Final = 4
@@ -33,7 +33,7 @@ MF_BT4: Final = 20
MODE_FAST: Final = 1
MODE_NORMAL: Final = 2
PRESET_DEFAULT: Final = 6
PRESET_EXTREME: int # v big number
PRESET_EXTREME: Final[int] # v big number
@final
class LZMADecompressor:
@@ -5,9 +5,9 @@ class ParserBase:
def reset(self) -> None: ...
def getpos(self) -> tuple[int, int]: ...
def unknown_decl(self, data: str) -> None: ...
def parse_comment(self, i: int, report: int = 1) -> int: ... # undocumented
def parse_comment(self, i: int, report: bool = True) -> int: ... # undocumented
def parse_declaration(self, i: int) -> int: ... # undocumented
def parse_marked_section(self, i: int, report: int = 1) -> int: ... # undocumented
def parse_marked_section(self, i: int, report: bool = True) -> int: ... # undocumented
def updatepos(self, i: int, j: int) -> int: ... # undocumented
if sys.version_info < (3, 10):
# Removed from ParserBase: https://bugs.python.org/issue31844
+43 -38
View File
@@ -1,8 +1,10 @@
import sys
from typing import Final, type_check_only
if sys.platform == "win32":
class MSIError(Exception): ...
# Actual typename View, not exposed by the implementation
@type_check_only
class _View:
def Execute(self, params: _Record | None = ...) -> None: ...
def GetColumnInfo(self, kind: int) -> _Record: ...
@@ -14,6 +16,7 @@ if sys.platform == "win32":
__init__: None # type: ignore[assignment]
# Actual typename SummaryInformation, not exposed by the implementation
@type_check_only
class _SummaryInformation:
def GetProperty(self, field: int) -> int | bytes | None: ...
def GetPropertyCount(self) -> int: ...
@@ -24,6 +27,7 @@ if sys.platform == "win32":
__init__: None # type: ignore[assignment]
# Actual typename Database, not exposed by the implementation
@type_check_only
class _Database:
def OpenView(self, sql: str) -> _View: ...
def Commit(self) -> None: ...
@@ -34,6 +38,7 @@ if sys.platform == "win32":
__init__: None # type: ignore[assignment]
# Actual typename Record, not exposed by the implementation
@type_check_only
class _Record:
def GetFieldCount(self) -> int: ...
def GetInteger(self, field: int) -> int: ...
@@ -51,42 +56,42 @@ if sys.platform == "win32":
def OpenDatabase(path: str, persist: int, /) -> _Database: ...
def CreateRecord(count: int, /) -> _Record: ...
MSICOLINFO_NAMES: int
MSICOLINFO_TYPES: int
MSIDBOPEN_CREATE: int
MSIDBOPEN_CREATEDIRECT: int
MSIDBOPEN_DIRECT: int
MSIDBOPEN_PATCHFILE: int
MSIDBOPEN_READONLY: int
MSIDBOPEN_TRANSACT: int
MSIMODIFY_ASSIGN: int
MSIMODIFY_DELETE: int
MSIMODIFY_INSERT: int
MSIMODIFY_INSERT_TEMPORARY: int
MSIMODIFY_MERGE: int
MSIMODIFY_REFRESH: int
MSIMODIFY_REPLACE: int
MSIMODIFY_SEEK: int
MSIMODIFY_UPDATE: int
MSIMODIFY_VALIDATE: int
MSIMODIFY_VALIDATE_DELETE: int
MSIMODIFY_VALIDATE_FIELD: int
MSIMODIFY_VALIDATE_NEW: int
MSICOLINFO_NAMES: Final[int]
MSICOLINFO_TYPES: Final[int]
MSIDBOPEN_CREATE: Final[int]
MSIDBOPEN_CREATEDIRECT: Final[int]
MSIDBOPEN_DIRECT: Final[int]
MSIDBOPEN_PATCHFILE: Final[int]
MSIDBOPEN_READONLY: Final[int]
MSIDBOPEN_TRANSACT: Final[int]
MSIMODIFY_ASSIGN: Final[int]
MSIMODIFY_DELETE: Final[int]
MSIMODIFY_INSERT: Final[int]
MSIMODIFY_INSERT_TEMPORARY: Final[int]
MSIMODIFY_MERGE: Final[int]
MSIMODIFY_REFRESH: Final[int]
MSIMODIFY_REPLACE: Final[int]
MSIMODIFY_SEEK: Final[int]
MSIMODIFY_UPDATE: Final[int]
MSIMODIFY_VALIDATE: Final[int]
MSIMODIFY_VALIDATE_DELETE: Final[int]
MSIMODIFY_VALIDATE_FIELD: Final[int]
MSIMODIFY_VALIDATE_NEW: Final[int]
PID_APPNAME: int
PID_AUTHOR: int
PID_CHARCOUNT: int
PID_CODEPAGE: int
PID_COMMENTS: int
PID_CREATE_DTM: int
PID_KEYWORDS: int
PID_LASTAUTHOR: int
PID_LASTPRINTED: int
PID_LASTSAVE_DTM: int
PID_PAGECOUNT: int
PID_REVNUMBER: int
PID_SECURITY: int
PID_SUBJECT: int
PID_TEMPLATE: int
PID_TITLE: int
PID_WORDCOUNT: int
PID_APPNAME: Final[int]
PID_AUTHOR: Final[int]
PID_CHARCOUNT: Final[int]
PID_CODEPAGE: Final[int]
PID_COMMENTS: Final[int]
PID_CREATE_DTM: Final[int]
PID_KEYWORDS: Final[int]
PID_LASTAUTHOR: Final[int]
PID_LASTPRINTED: Final[int]
PID_LASTSAVE_DTM: Final[int]
PID_PAGECOUNT: Final[int]
PID_REVNUMBER: Final[int]
PID_SECURITY: Final[int]
PID_SUBJECT: Final[int]
PID_TEMPLATE: Final[int]
PID_TITLE: Final[int]
PID_WORDCOUNT: Final[int]
+8 -1
View File
@@ -2,7 +2,7 @@ import sys
from _typeshed import SupportsGetItem
from collections.abc import Callable, Container, Iterable, MutableMapping, MutableSequence, Sequence
from operator import attrgetter as attrgetter, itemgetter as itemgetter, methodcaller as methodcaller
from typing import Any, AnyStr, Protocol, SupportsAbs, SupportsIndex, TypeVar, overload
from typing import Any, AnyStr, Protocol, SupportsAbs, SupportsIndex, TypeVar, overload, type_check_only
from typing_extensions import ParamSpec, TypeAlias, TypeIs
_R = TypeVar("_R")
@@ -16,26 +16,33 @@ _P = ParamSpec("_P")
# operators can be overloaded to return an arbitrary object. For example,
# the numpy.array comparison dunders return another numpy.array.
@type_check_only
class _SupportsDunderLT(Protocol):
def __lt__(self, other: Any, /) -> Any: ...
@type_check_only
class _SupportsDunderGT(Protocol):
def __gt__(self, other: Any, /) -> Any: ...
@type_check_only
class _SupportsDunderLE(Protocol):
def __le__(self, other: Any, /) -> Any: ...
@type_check_only
class _SupportsDunderGE(Protocol):
def __ge__(self, other: Any, /) -> Any: ...
_SupportsComparison: TypeAlias = _SupportsDunderLE | _SupportsDunderGE | _SupportsDunderGT | _SupportsDunderLT
@type_check_only
class _SupportsInversion(Protocol[_T_co]):
def __invert__(self) -> _T_co: ...
@type_check_only
class _SupportsNeg(Protocol[_T_co]):
def __neg__(self) -> _T_co: ...
@type_check_only
class _SupportsPos(Protocol[_T_co]):
def __pos__(self) -> _T_co: ...
@@ -4,6 +4,7 @@ from pickle import PickleBuffer as PickleBuffer
from typing import Any, Protocol, type_check_only
from typing_extensions import TypeAlias
@type_check_only
class _ReadableFileobj(Protocol):
def read(self, n: int, /) -> bytes: ...
def readline(self) -> bytes: ...
File diff suppressed because it is too large Load Diff
+179 -178
View File
@@ -16,6 +16,7 @@ from sqlite3 import (
ProgrammingError as ProgrammingError,
Row as Row,
Warning as Warning,
_IsolationLevel,
)
from typing import Any, Final, Literal, TypeVar, overload
from typing_extensions import TypeAlias
@@ -29,45 +30,45 @@ _SqliteData: TypeAlias = str | ReadableBuffer | int | float | None
_Adapter: TypeAlias = Callable[[_T], _SqliteData]
_Converter: TypeAlias = Callable[[bytes], Any]
PARSE_COLNAMES: Final[int]
PARSE_DECLTYPES: Final[int]
SQLITE_ALTER_TABLE: Final[int]
SQLITE_ANALYZE: Final[int]
SQLITE_ATTACH: Final[int]
SQLITE_CREATE_INDEX: Final[int]
SQLITE_CREATE_TABLE: Final[int]
SQLITE_CREATE_TEMP_INDEX: Final[int]
SQLITE_CREATE_TEMP_TABLE: Final[int]
SQLITE_CREATE_TEMP_TRIGGER: Final[int]
SQLITE_CREATE_TEMP_VIEW: Final[int]
SQLITE_CREATE_TRIGGER: Final[int]
SQLITE_CREATE_VIEW: Final[int]
SQLITE_CREATE_VTABLE: Final[int]
SQLITE_DELETE: Final[int]
SQLITE_DENY: Final[int]
SQLITE_DETACH: Final[int]
SQLITE_DONE: Final[int]
SQLITE_DROP_INDEX: Final[int]
SQLITE_DROP_TABLE: Final[int]
SQLITE_DROP_TEMP_INDEX: Final[int]
SQLITE_DROP_TEMP_TABLE: Final[int]
SQLITE_DROP_TEMP_TRIGGER: Final[int]
SQLITE_DROP_TEMP_VIEW: Final[int]
SQLITE_DROP_TRIGGER: Final[int]
SQLITE_DROP_VIEW: Final[int]
SQLITE_DROP_VTABLE: Final[int]
SQLITE_FUNCTION: Final[int]
SQLITE_IGNORE: Final[int]
SQLITE_INSERT: Final[int]
SQLITE_OK: Final[int]
SQLITE_PRAGMA: Final[int]
SQLITE_READ: Final[int]
SQLITE_RECURSIVE: Final[int]
SQLITE_REINDEX: Final[int]
SQLITE_SAVEPOINT: Final[int]
SQLITE_SELECT: Final[int]
SQLITE_TRANSACTION: Final[int]
SQLITE_UPDATE: Final[int]
PARSE_COLNAMES: Final = 2
PARSE_DECLTYPES: Final = 1
SQLITE_ALTER_TABLE: Final = 26
SQLITE_ANALYZE: Final = 28
SQLITE_ATTACH: Final = 24
SQLITE_CREATE_INDEX: Final = 1
SQLITE_CREATE_TABLE: Final = 2
SQLITE_CREATE_TEMP_INDEX: Final = 3
SQLITE_CREATE_TEMP_TABLE: Final = 4
SQLITE_CREATE_TEMP_TRIGGER: Final = 5
SQLITE_CREATE_TEMP_VIEW: Final = 6
SQLITE_CREATE_TRIGGER: Final = 7
SQLITE_CREATE_VIEW: Final = 8
SQLITE_CREATE_VTABLE: Final = 29
SQLITE_DELETE: Final = 9
SQLITE_DENY: Final = 1
SQLITE_DETACH: Final = 25
SQLITE_DONE: Final = 101
SQLITE_DROP_INDEX: Final = 10
SQLITE_DROP_TABLE: Final = 11
SQLITE_DROP_TEMP_INDEX: Final = 12
SQLITE_DROP_TEMP_TABLE: Final = 13
SQLITE_DROP_TEMP_TRIGGER: Final = 14
SQLITE_DROP_TEMP_VIEW: Final = 15
SQLITE_DROP_TRIGGER: Final = 16
SQLITE_DROP_VIEW: Final = 17
SQLITE_DROP_VTABLE: Final = 30
SQLITE_FUNCTION: Final = 31
SQLITE_IGNORE: Final = 2
SQLITE_INSERT: Final = 18
SQLITE_OK: Final = 0
SQLITE_PRAGMA: Final = 19
SQLITE_READ: Final = 20
SQLITE_RECURSIVE: Final = 33
SQLITE_REINDEX: Final = 27
SQLITE_SAVEPOINT: Final = 32
SQLITE_SELECT: Final = 21
SQLITE_TRANSACTION: Final = 22
SQLITE_UPDATE: Final = 23
adapters: dict[tuple[type[Any], type[Any]], _Adapter[Any]]
converters: dict[str, _Converter]
sqlite_version: str
@@ -76,141 +77,141 @@ if sys.version_info < (3, 12):
version: str
if sys.version_info >= (3, 12):
LEGACY_TRANSACTION_CONTROL: Final[int]
SQLITE_DBCONFIG_DEFENSIVE: Final[int]
SQLITE_DBCONFIG_DQS_DDL: Final[int]
SQLITE_DBCONFIG_DQS_DML: Final[int]
SQLITE_DBCONFIG_ENABLE_FKEY: Final[int]
SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER: Final[int]
SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION: Final[int]
SQLITE_DBCONFIG_ENABLE_QPSG: Final[int]
SQLITE_DBCONFIG_ENABLE_TRIGGER: Final[int]
SQLITE_DBCONFIG_ENABLE_VIEW: Final[int]
SQLITE_DBCONFIG_LEGACY_ALTER_TABLE: Final[int]
SQLITE_DBCONFIG_LEGACY_FILE_FORMAT: Final[int]
SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE: Final[int]
SQLITE_DBCONFIG_RESET_DATABASE: Final[int]
SQLITE_DBCONFIG_TRIGGER_EQP: Final[int]
SQLITE_DBCONFIG_TRUSTED_SCHEMA: Final[int]
SQLITE_DBCONFIG_WRITABLE_SCHEMA: Final[int]
LEGACY_TRANSACTION_CONTROL: Final = -1
SQLITE_DBCONFIG_DEFENSIVE: Final = 1010
SQLITE_DBCONFIG_DQS_DDL: Final = 1014
SQLITE_DBCONFIG_DQS_DML: Final = 1013
SQLITE_DBCONFIG_ENABLE_FKEY: Final = 1002
SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER: Final = 1004
SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION: Final = 1005
SQLITE_DBCONFIG_ENABLE_QPSG: Final = 1007
SQLITE_DBCONFIG_ENABLE_TRIGGER: Final = 1003
SQLITE_DBCONFIG_ENABLE_VIEW: Final = 1015
SQLITE_DBCONFIG_LEGACY_ALTER_TABLE: Final = 1012
SQLITE_DBCONFIG_LEGACY_FILE_FORMAT: Final = 1016
SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE: Final = 1006
SQLITE_DBCONFIG_RESET_DATABASE: Final = 1009
SQLITE_DBCONFIG_TRIGGER_EQP: Final = 1008
SQLITE_DBCONFIG_TRUSTED_SCHEMA: Final = 1017
SQLITE_DBCONFIG_WRITABLE_SCHEMA: Final = 1011
if sys.version_info >= (3, 11):
SQLITE_ABORT: Final[int]
SQLITE_ABORT_ROLLBACK: Final[int]
SQLITE_AUTH: Final[int]
SQLITE_AUTH_USER: Final[int]
SQLITE_BUSY: Final[int]
SQLITE_BUSY_RECOVERY: Final[int]
SQLITE_BUSY_SNAPSHOT: Final[int]
SQLITE_BUSY_TIMEOUT: Final[int]
SQLITE_CANTOPEN: Final[int]
SQLITE_CANTOPEN_CONVPATH: Final[int]
SQLITE_CANTOPEN_DIRTYWAL: Final[int]
SQLITE_CANTOPEN_FULLPATH: Final[int]
SQLITE_CANTOPEN_ISDIR: Final[int]
SQLITE_CANTOPEN_NOTEMPDIR: Final[int]
SQLITE_CANTOPEN_SYMLINK: Final[int]
SQLITE_CONSTRAINT: Final[int]
SQLITE_CONSTRAINT_CHECK: Final[int]
SQLITE_CONSTRAINT_COMMITHOOK: Final[int]
SQLITE_CONSTRAINT_FOREIGNKEY: Final[int]
SQLITE_CONSTRAINT_FUNCTION: Final[int]
SQLITE_CONSTRAINT_NOTNULL: Final[int]
SQLITE_CONSTRAINT_PINNED: Final[int]
SQLITE_CONSTRAINT_PRIMARYKEY: Final[int]
SQLITE_CONSTRAINT_ROWID: Final[int]
SQLITE_CONSTRAINT_TRIGGER: Final[int]
SQLITE_CONSTRAINT_UNIQUE: Final[int]
SQLITE_CONSTRAINT_VTAB: Final[int]
SQLITE_CORRUPT: Final[int]
SQLITE_CORRUPT_INDEX: Final[int]
SQLITE_CORRUPT_SEQUENCE: Final[int]
SQLITE_CORRUPT_VTAB: Final[int]
SQLITE_EMPTY: Final[int]
SQLITE_ERROR: Final[int]
SQLITE_ERROR_MISSING_COLLSEQ: Final[int]
SQLITE_ERROR_RETRY: Final[int]
SQLITE_ERROR_SNAPSHOT: Final[int]
SQLITE_FORMAT: Final[int]
SQLITE_FULL: Final[int]
SQLITE_INTERNAL: Final[int]
SQLITE_INTERRUPT: Final[int]
SQLITE_IOERR: Final[int]
SQLITE_IOERR_ACCESS: Final[int]
SQLITE_IOERR_AUTH: Final[int]
SQLITE_IOERR_BEGIN_ATOMIC: Final[int]
SQLITE_IOERR_BLOCKED: Final[int]
SQLITE_IOERR_CHECKRESERVEDLOCK: Final[int]
SQLITE_IOERR_CLOSE: Final[int]
SQLITE_IOERR_COMMIT_ATOMIC: Final[int]
SQLITE_IOERR_CONVPATH: Final[int]
SQLITE_IOERR_CORRUPTFS: Final[int]
SQLITE_IOERR_DATA: Final[int]
SQLITE_IOERR_DELETE: Final[int]
SQLITE_IOERR_DELETE_NOENT: Final[int]
SQLITE_IOERR_DIR_CLOSE: Final[int]
SQLITE_IOERR_DIR_FSYNC: Final[int]
SQLITE_IOERR_FSTAT: Final[int]
SQLITE_IOERR_FSYNC: Final[int]
SQLITE_IOERR_GETTEMPPATH: Final[int]
SQLITE_IOERR_LOCK: Final[int]
SQLITE_IOERR_MMAP: Final[int]
SQLITE_IOERR_NOMEM: Final[int]
SQLITE_IOERR_RDLOCK: Final[int]
SQLITE_IOERR_READ: Final[int]
SQLITE_IOERR_ROLLBACK_ATOMIC: Final[int]
SQLITE_IOERR_SEEK: Final[int]
SQLITE_IOERR_SHMLOCK: Final[int]
SQLITE_IOERR_SHMMAP: Final[int]
SQLITE_IOERR_SHMOPEN: Final[int]
SQLITE_IOERR_SHMSIZE: Final[int]
SQLITE_IOERR_SHORT_READ: Final[int]
SQLITE_IOERR_TRUNCATE: Final[int]
SQLITE_IOERR_UNLOCK: Final[int]
SQLITE_IOERR_VNODE: Final[int]
SQLITE_IOERR_WRITE: Final[int]
SQLITE_LIMIT_ATTACHED: Final[int]
SQLITE_LIMIT_COLUMN: Final[int]
SQLITE_LIMIT_COMPOUND_SELECT: Final[int]
SQLITE_LIMIT_EXPR_DEPTH: Final[int]
SQLITE_LIMIT_FUNCTION_ARG: Final[int]
SQLITE_LIMIT_LENGTH: Final[int]
SQLITE_LIMIT_LIKE_PATTERN_LENGTH: Final[int]
SQLITE_LIMIT_SQL_LENGTH: Final[int]
SQLITE_LIMIT_TRIGGER_DEPTH: Final[int]
SQLITE_LIMIT_VARIABLE_NUMBER: Final[int]
SQLITE_LIMIT_VDBE_OP: Final[int]
SQLITE_LIMIT_WORKER_THREADS: Final[int]
SQLITE_LOCKED: Final[int]
SQLITE_LOCKED_SHAREDCACHE: Final[int]
SQLITE_LOCKED_VTAB: Final[int]
SQLITE_MISMATCH: Final[int]
SQLITE_MISUSE: Final[int]
SQLITE_NOLFS: Final[int]
SQLITE_NOMEM: Final[int]
SQLITE_NOTADB: Final[int]
SQLITE_NOTFOUND: Final[int]
SQLITE_NOTICE: Final[int]
SQLITE_NOTICE_RECOVER_ROLLBACK: Final[int]
SQLITE_NOTICE_RECOVER_WAL: Final[int]
SQLITE_OK_LOAD_PERMANENTLY: Final[int]
SQLITE_OK_SYMLINK: Final[int]
SQLITE_PERM: Final[int]
SQLITE_PROTOCOL: Final[int]
SQLITE_RANGE: Final[int]
SQLITE_READONLY: Final[int]
SQLITE_READONLY_CANTINIT: Final[int]
SQLITE_READONLY_CANTLOCK: Final[int]
SQLITE_READONLY_DBMOVED: Final[int]
SQLITE_READONLY_DIRECTORY: Final[int]
SQLITE_READONLY_RECOVERY: Final[int]
SQLITE_READONLY_ROLLBACK: Final[int]
SQLITE_ROW: Final[int]
SQLITE_SCHEMA: Final[int]
SQLITE_TOOBIG: Final[int]
SQLITE_WARNING: Final[int]
SQLITE_WARNING_AUTOINDEX: Final[int]
threadsafety: Final[int]
SQLITE_ABORT: Final = 4
SQLITE_ABORT_ROLLBACK: Final = 516
SQLITE_AUTH: Final = 23
SQLITE_AUTH_USER: Final = 279
SQLITE_BUSY: Final = 5
SQLITE_BUSY_RECOVERY: Final = 261
SQLITE_BUSY_SNAPSHOT: Final = 517
SQLITE_BUSY_TIMEOUT: Final = 773
SQLITE_CANTOPEN: Final = 14
SQLITE_CANTOPEN_CONVPATH: Final = 1038
SQLITE_CANTOPEN_DIRTYWAL: Final = 1294
SQLITE_CANTOPEN_FULLPATH: Final = 782
SQLITE_CANTOPEN_ISDIR: Final = 526
SQLITE_CANTOPEN_NOTEMPDIR: Final = 270
SQLITE_CANTOPEN_SYMLINK: Final = 1550
SQLITE_CONSTRAINT: Final = 19
SQLITE_CONSTRAINT_CHECK: Final = 275
SQLITE_CONSTRAINT_COMMITHOOK: Final = 531
SQLITE_CONSTRAINT_FOREIGNKEY: Final = 787
SQLITE_CONSTRAINT_FUNCTION: Final = 1043
SQLITE_CONSTRAINT_NOTNULL: Final = 1299
SQLITE_CONSTRAINT_PINNED: Final = 2835
SQLITE_CONSTRAINT_PRIMARYKEY: Final = 1555
SQLITE_CONSTRAINT_ROWID: Final = 2579
SQLITE_CONSTRAINT_TRIGGER: Final = 1811
SQLITE_CONSTRAINT_UNIQUE: Final = 2067
SQLITE_CONSTRAINT_VTAB: Final = 2323
SQLITE_CORRUPT: Final = 11
SQLITE_CORRUPT_INDEX: Final = 779
SQLITE_CORRUPT_SEQUENCE: Final = 523
SQLITE_CORRUPT_VTAB: Final = 267
SQLITE_EMPTY: Final = 16
SQLITE_ERROR: Final = 1
SQLITE_ERROR_MISSING_COLLSEQ: Final = 257
SQLITE_ERROR_RETRY: Final = 513
SQLITE_ERROR_SNAPSHOT: Final = 769
SQLITE_FORMAT: Final = 24
SQLITE_FULL: Final = 13
SQLITE_INTERNAL: Final = 2
SQLITE_INTERRUPT: Final = 9
SQLITE_IOERR: Final = 10
SQLITE_IOERR_ACCESS: Final = 3338
SQLITE_IOERR_AUTH: Final = 7178
SQLITE_IOERR_BEGIN_ATOMIC: Final = 7434
SQLITE_IOERR_BLOCKED: Final = 2826
SQLITE_IOERR_CHECKRESERVEDLOCK: Final = 3594
SQLITE_IOERR_CLOSE: Final = 4106
SQLITE_IOERR_COMMIT_ATOMIC: Final = 7690
SQLITE_IOERR_CONVPATH: Final = 6666
SQLITE_IOERR_CORRUPTFS: Final = 8458
SQLITE_IOERR_DATA: Final = 8202
SQLITE_IOERR_DELETE: Final = 2570
SQLITE_IOERR_DELETE_NOENT: Final = 5898
SQLITE_IOERR_DIR_CLOSE: Final = 4362
SQLITE_IOERR_DIR_FSYNC: Final = 1290
SQLITE_IOERR_FSTAT: Final = 1802
SQLITE_IOERR_FSYNC: Final = 1034
SQLITE_IOERR_GETTEMPPATH: Final = 6410
SQLITE_IOERR_LOCK: Final = 3850
SQLITE_IOERR_MMAP: Final = 6154
SQLITE_IOERR_NOMEM: Final = 3082
SQLITE_IOERR_RDLOCK: Final = 2314
SQLITE_IOERR_READ: Final = 266
SQLITE_IOERR_ROLLBACK_ATOMIC: Final = 7946
SQLITE_IOERR_SEEK: Final = 5642
SQLITE_IOERR_SHMLOCK: Final = 5130
SQLITE_IOERR_SHMMAP: Final = 5386
SQLITE_IOERR_SHMOPEN: Final = 4618
SQLITE_IOERR_SHMSIZE: Final = 4874
SQLITE_IOERR_SHORT_READ: Final = 522
SQLITE_IOERR_TRUNCATE: Final = 1546
SQLITE_IOERR_UNLOCK: Final = 2058
SQLITE_IOERR_VNODE: Final = 6922
SQLITE_IOERR_WRITE: Final = 778
SQLITE_LIMIT_ATTACHED: Final = 7
SQLITE_LIMIT_COLUMN: Final = 22
SQLITE_LIMIT_COMPOUND_SELECT: Final = 4
SQLITE_LIMIT_EXPR_DEPTH: Final = 3
SQLITE_LIMIT_FUNCTION_ARG: Final = 6
SQLITE_LIMIT_LENGTH: Final = 0
SQLITE_LIMIT_LIKE_PATTERN_LENGTH: Final = 8
SQLITE_LIMIT_SQL_LENGTH: Final = 1
SQLITE_LIMIT_TRIGGER_DEPTH: Final = 10
SQLITE_LIMIT_VARIABLE_NUMBER: Final = 9
SQLITE_LIMIT_VDBE_OP: Final = 5
SQLITE_LIMIT_WORKER_THREADS: Final = 11
SQLITE_LOCKED: Final = 6
SQLITE_LOCKED_SHAREDCACHE: Final = 262
SQLITE_LOCKED_VTAB: Final = 518
SQLITE_MISMATCH: Final = 20
SQLITE_MISUSE: Final = 21
SQLITE_NOLFS: Final = 22
SQLITE_NOMEM: Final = 7
SQLITE_NOTADB: Final = 26
SQLITE_NOTFOUND: Final = 12
SQLITE_NOTICE: Final = 27
SQLITE_NOTICE_RECOVER_ROLLBACK: Final = 539
SQLITE_NOTICE_RECOVER_WAL: Final = 283
SQLITE_OK_LOAD_PERMANENTLY: Final = 256
SQLITE_OK_SYMLINK: Final = 512
SQLITE_PERM: Final = 3
SQLITE_PROTOCOL: Final = 15
SQLITE_RANGE: Final = 25
SQLITE_READONLY: Final = 8
SQLITE_READONLY_CANTINIT: Final = 1288
SQLITE_READONLY_CANTLOCK: Final = 520
SQLITE_READONLY_DBMOVED: Final = 1032
SQLITE_READONLY_DIRECTORY: Final = 1544
SQLITE_READONLY_RECOVERY: Final = 264
SQLITE_READONLY_ROLLBACK: Final = 776
SQLITE_ROW: Final = 100
SQLITE_SCHEMA: Final = 17
SQLITE_TOOBIG: Final = 18
SQLITE_WARNING: Final = 28
SQLITE_WARNING_AUTOINDEX: Final = 284
threadsafety: Literal[0, 1, 3]
# Can take or return anything depending on what's in the registry.
@overload
@@ -225,7 +226,7 @@ if sys.version_info >= (3, 12):
database: StrOrBytesPath,
timeout: float = 5.0,
detect_types: int = 0,
isolation_level: Literal["DEFERRED", "EXCLUSIVE", "IMMEDIATE"] | None = "DEFERRED",
isolation_level: _IsolationLevel = "DEFERRED",
check_same_thread: bool = True,
cached_statements: int = 128,
uri: bool = False,
@@ -237,7 +238,7 @@ if sys.version_info >= (3, 12):
database: StrOrBytesPath,
timeout: float,
detect_types: int,
isolation_level: Literal["DEFERRED", "EXCLUSIVE", "IMMEDIATE"] | None,
isolation_level: _IsolationLevel,
check_same_thread: bool,
factory: type[_ConnectionT],
cached_statements: int = 128,
@@ -250,7 +251,7 @@ if sys.version_info >= (3, 12):
database: StrOrBytesPath,
timeout: float = 5.0,
detect_types: int = 0,
isolation_level: Literal["DEFERRED", "EXCLUSIVE", "IMMEDIATE"] | None = "DEFERRED",
isolation_level: _IsolationLevel = "DEFERRED",
check_same_thread: bool = True,
*,
factory: type[_ConnectionT],
@@ -265,7 +266,7 @@ else:
database: StrOrBytesPath,
timeout: float = 5.0,
detect_types: int = 0,
isolation_level: Literal["DEFERRED", "EXCLUSIVE", "IMMEDIATE"] | None = "DEFERRED",
isolation_level: _IsolationLevel = "DEFERRED",
check_same_thread: bool = True,
cached_statements: int = 128,
uri: bool = False,
@@ -275,7 +276,7 @@ else:
database: StrOrBytesPath,
timeout: float,
detect_types: int,
isolation_level: Literal["DEFERRED", "EXCLUSIVE", "IMMEDIATE"] | None,
isolation_level: _IsolationLevel,
check_same_thread: bool,
factory: type[_ConnectionT],
cached_statements: int = 128,
@@ -286,7 +287,7 @@ else:
database: StrOrBytesPath,
timeout: float = 5.0,
detect_types: int = 0,
isolation_level: Literal["DEFERRED", "EXCLUSIVE", "IMMEDIATE"] | None = "DEFERRED",
isolation_level: _IsolationLevel = "DEFERRED",
check_same_thread: bool = True,
*,
factory: type[_ConnectionT],
+108 -106
View File
@@ -12,14 +12,15 @@ from ssl import (
SSLWantWriteError as SSLWantWriteError,
SSLZeroReturnError as SSLZeroReturnError,
)
from typing import Any, ClassVar, Literal, TypedDict, final, overload
from typing_extensions import NotRequired, Self, TypeAlias
from typing import Any, ClassVar, Final, Literal, TypedDict, final, overload, type_check_only
from typing_extensions import NotRequired, Self, TypeAlias, deprecated
_PasswordType: TypeAlias = Callable[[], str | bytes | bytearray] | str | bytes | bytearray
_PCTRTT: TypeAlias = tuple[tuple[str, str], ...]
_PCTRTTT: TypeAlias = tuple[_PCTRTT, ...]
_PeerCertRetDictType: TypeAlias = dict[str, str | _PCTRTTT | _PCTRTT]
@type_check_only
class _Cipher(TypedDict):
aead: bool
alg_bits: int
@@ -33,6 +34,7 @@ class _Cipher(TypedDict):
strength_bits: int
symmetric: str
@type_check_only
class _CertInfo(TypedDict):
subject: tuple[tuple[tuple[str, str], ...], ...]
issuer: tuple[tuple[tuple[str, str], ...], ...]
@@ -49,6 +51,7 @@ def RAND_add(string: str | ReadableBuffer, entropy: float, /) -> None: ...
def RAND_bytes(n: int, /) -> bytes: ...
if sys.version_info < (3, 12):
@deprecated("Deprecated since Python 3.6; removed in Python 3.12. Use `ssl.RAND_bytes()` instead.")
def RAND_pseudo_bytes(n: int, /) -> tuple[bytes, bool]: ...
if sys.version_info < (3, 10):
@@ -159,135 +162,134 @@ if sys.version_info < (3, 12):
err_names_to_codes: dict[str, tuple[int, int]]
lib_codes_to_names: dict[int, str]
_DEFAULT_CIPHERS: str
_DEFAULT_CIPHERS: Final[str]
# SSL error numbers
SSL_ERROR_ZERO_RETURN: int
SSL_ERROR_WANT_READ: int
SSL_ERROR_WANT_WRITE: int
SSL_ERROR_WANT_X509_LOOKUP: int
SSL_ERROR_SYSCALL: int
SSL_ERROR_SSL: int
SSL_ERROR_WANT_CONNECT: int
SSL_ERROR_EOF: int
SSL_ERROR_INVALID_ERROR_CODE: int
SSL_ERROR_ZERO_RETURN: Final = 6
SSL_ERROR_WANT_READ: Final = 2
SSL_ERROR_WANT_WRITE: Final = 3
SSL_ERROR_WANT_X509_LOOKUP: Final = 4
SSL_ERROR_SYSCALL: Final = 5
SSL_ERROR_SSL: Final = 1
SSL_ERROR_WANT_CONNECT: Final = 7
SSL_ERROR_EOF: Final = 8
SSL_ERROR_INVALID_ERROR_CODE: Final = 10
# verify modes
CERT_NONE: int
CERT_OPTIONAL: int
CERT_REQUIRED: int
CERT_NONE: Final = 0
CERT_OPTIONAL: Final = 1
CERT_REQUIRED: Final = 2
# verify flags
VERIFY_DEFAULT: int
VERIFY_CRL_CHECK_LEAF: int
VERIFY_CRL_CHECK_CHAIN: int
VERIFY_X509_STRICT: int
VERIFY_X509_TRUSTED_FIRST: int
VERIFY_DEFAULT: Final = 0
VERIFY_CRL_CHECK_LEAF: Final = 0x4
VERIFY_CRL_CHECK_CHAIN: Final = 0x8
VERIFY_X509_STRICT: Final = 0x20
VERIFY_X509_TRUSTED_FIRST: Final = 0x8000
if sys.version_info >= (3, 10):
VERIFY_ALLOW_PROXY_CERTS: int
VERIFY_X509_PARTIAL_CHAIN: int
VERIFY_ALLOW_PROXY_CERTS: Final = 0x40
VERIFY_X509_PARTIAL_CHAIN: Final = 0x80000
# alert descriptions
ALERT_DESCRIPTION_CLOSE_NOTIFY: int
ALERT_DESCRIPTION_UNEXPECTED_MESSAGE: int
ALERT_DESCRIPTION_BAD_RECORD_MAC: int
ALERT_DESCRIPTION_RECORD_OVERFLOW: int
ALERT_DESCRIPTION_DECOMPRESSION_FAILURE: int
ALERT_DESCRIPTION_HANDSHAKE_FAILURE: int
ALERT_DESCRIPTION_BAD_CERTIFICATE: int
ALERT_DESCRIPTION_UNSUPPORTED_CERTIFICATE: int
ALERT_DESCRIPTION_CERTIFICATE_REVOKED: int
ALERT_DESCRIPTION_CERTIFICATE_EXPIRED: int
ALERT_DESCRIPTION_CERTIFICATE_UNKNOWN: int
ALERT_DESCRIPTION_ILLEGAL_PARAMETER: int
ALERT_DESCRIPTION_UNKNOWN_CA: int
ALERT_DESCRIPTION_ACCESS_DENIED: int
ALERT_DESCRIPTION_DECODE_ERROR: int
ALERT_DESCRIPTION_DECRYPT_ERROR: int
ALERT_DESCRIPTION_PROTOCOL_VERSION: int
ALERT_DESCRIPTION_INSUFFICIENT_SECURITY: int
ALERT_DESCRIPTION_INTERNAL_ERROR: int
ALERT_DESCRIPTION_USER_CANCELLED: int
ALERT_DESCRIPTION_NO_RENEGOTIATION: int
ALERT_DESCRIPTION_UNSUPPORTED_EXTENSION: int
ALERT_DESCRIPTION_CERTIFICATE_UNOBTAINABLE: int
ALERT_DESCRIPTION_UNRECOGNIZED_NAME: int
ALERT_DESCRIPTION_BAD_CERTIFICATE_STATUS_RESPONSE: int
ALERT_DESCRIPTION_BAD_CERTIFICATE_HASH_VALUE: int
ALERT_DESCRIPTION_UNKNOWN_PSK_IDENTITY: int
ALERT_DESCRIPTION_CLOSE_NOTIFY: Final = 0
ALERT_DESCRIPTION_UNEXPECTED_MESSAGE: Final = 10
ALERT_DESCRIPTION_BAD_RECORD_MAC: Final = 20
ALERT_DESCRIPTION_RECORD_OVERFLOW: Final = 22
ALERT_DESCRIPTION_DECOMPRESSION_FAILURE: Final = 30
ALERT_DESCRIPTION_HANDSHAKE_FAILURE: Final = 40
ALERT_DESCRIPTION_BAD_CERTIFICATE: Final = 42
ALERT_DESCRIPTION_UNSUPPORTED_CERTIFICATE: Final = 43
ALERT_DESCRIPTION_CERTIFICATE_REVOKED: Final = 44
ALERT_DESCRIPTION_CERTIFICATE_EXPIRED: Final = 45
ALERT_DESCRIPTION_CERTIFICATE_UNKNOWN: Final = 46
ALERT_DESCRIPTION_ILLEGAL_PARAMETER: Final = 47
ALERT_DESCRIPTION_UNKNOWN_CA: Final = 48
ALERT_DESCRIPTION_ACCESS_DENIED: Final = 49
ALERT_DESCRIPTION_DECODE_ERROR: Final = 50
ALERT_DESCRIPTION_DECRYPT_ERROR: Final = 51
ALERT_DESCRIPTION_PROTOCOL_VERSION: Final = 70
ALERT_DESCRIPTION_INSUFFICIENT_SECURITY: Final = 71
ALERT_DESCRIPTION_INTERNAL_ERROR: Final = 80
ALERT_DESCRIPTION_USER_CANCELLED: Final = 90
ALERT_DESCRIPTION_NO_RENEGOTIATION: Final = 100
ALERT_DESCRIPTION_UNSUPPORTED_EXTENSION: Final = 110
ALERT_DESCRIPTION_CERTIFICATE_UNOBTAINABLE: Final = 111
ALERT_DESCRIPTION_UNRECOGNIZED_NAME: Final = 112
ALERT_DESCRIPTION_BAD_CERTIFICATE_STATUS_RESPONSE: Final = 113
ALERT_DESCRIPTION_BAD_CERTIFICATE_HASH_VALUE: Final = 114
ALERT_DESCRIPTION_UNKNOWN_PSK_IDENTITY: Final = 115
# protocol versions
PROTOCOL_SSLv23: int
PROTOCOL_TLS: int
PROTOCOL_TLS_CLIENT: int
PROTOCOL_TLS_SERVER: int
PROTOCOL_TLSv1: int
PROTOCOL_TLSv1_1: int
PROTOCOL_TLSv1_2: int
PROTOCOL_SSLv23: Final = 2
PROTOCOL_TLS: Final = 2
PROTOCOL_TLS_CLIENT: Final = 16
PROTOCOL_TLS_SERVER: Final = 17
PROTOCOL_TLSv1: Final = 3
PROTOCOL_TLSv1_1: Final = 4
PROTOCOL_TLSv1_2: Final = 5
# protocol options
OP_ALL: int
OP_NO_SSLv2: int
OP_NO_SSLv3: int
OP_NO_TLSv1: int
OP_NO_TLSv1_1: int
OP_NO_TLSv1_2: int
OP_NO_TLSv1_3: int
OP_CIPHER_SERVER_PREFERENCE: int
OP_SINGLE_DH_USE: int
OP_NO_TICKET: int
OP_SINGLE_ECDH_USE: int
OP_NO_COMPRESSION: int
OP_ENABLE_MIDDLEBOX_COMPAT: int
OP_NO_RENEGOTIATION: int
OP_ALL: Final = 0x80000050
OP_NO_SSLv2: Final = 0x0
OP_NO_SSLv3: Final = 0x2000000
OP_NO_TLSv1: Final = 0x4000000
OP_NO_TLSv1_1: Final = 0x10000000
OP_NO_TLSv1_2: Final = 0x8000000
OP_NO_TLSv1_3: Final = 0x20000000
OP_CIPHER_SERVER_PREFERENCE: Final = 0x400000
OP_SINGLE_DH_USE: Final = 0x0
OP_NO_TICKET: Final = 0x4000
OP_SINGLE_ECDH_USE: Final = 0x0
OP_NO_COMPRESSION: Final = 0x20000
OP_ENABLE_MIDDLEBOX_COMPAT: Final = 0x100000
OP_NO_RENEGOTIATION: Final = 0x40000000
if sys.version_info >= (3, 11) or sys.platform == "linux":
OP_IGNORE_UNEXPECTED_EOF: int
OP_IGNORE_UNEXPECTED_EOF: Final = 0x80
if sys.version_info >= (3, 12):
OP_LEGACY_SERVER_CONNECT: int
OP_ENABLE_KTLS: int
OP_LEGACY_SERVER_CONNECT: Final = 0x4
OP_ENABLE_KTLS: Final = 0x8
# host flags
HOSTFLAG_ALWAYS_CHECK_SUBJECT: int
HOSTFLAG_NEVER_CHECK_SUBJECT: int
HOSTFLAG_NO_WILDCARDS: int
HOSTFLAG_NO_PARTIAL_WILDCARDS: int
HOSTFLAG_MULTI_LABEL_WILDCARDS: int
HOSTFLAG_SINGLE_LABEL_SUBDOMAINS: int
HOSTFLAG_ALWAYS_CHECK_SUBJECT: Final = 0x1
HOSTFLAG_NEVER_CHECK_SUBJECT: Final = 0x20
HOSTFLAG_NO_WILDCARDS: Final = 0x2
HOSTFLAG_NO_PARTIAL_WILDCARDS: Final = 0x4
HOSTFLAG_MULTI_LABEL_WILDCARDS: Final = 0x8
HOSTFLAG_SINGLE_LABEL_SUBDOMAINS: Final = 0x10
if sys.version_info >= (3, 10):
# certificate file types
# Typed as Literal so the overload on Certificate.public_bytes can work properly.
ENCODING_PEM: Literal[1]
ENCODING_DER: Literal[2]
ENCODING_PEM: Final = 1
ENCODING_DER: Final = 2
# protocol versions
PROTO_MINIMUM_SUPPORTED: int
PROTO_MAXIMUM_SUPPORTED: int
PROTO_SSLv3: int
PROTO_TLSv1: int
PROTO_TLSv1_1: int
PROTO_TLSv1_2: int
PROTO_TLSv1_3: int
PROTO_MINIMUM_SUPPORTED: Final = -2
PROTO_MAXIMUM_SUPPORTED: Final = -1
PROTO_SSLv3: Final[int]
PROTO_TLSv1: Final[int]
PROTO_TLSv1_1: Final[int]
PROTO_TLSv1_2: Final[int]
PROTO_TLSv1_3: Final[int]
# feature support
HAS_SNI: bool
HAS_TLS_UNIQUE: bool
HAS_ECDH: bool
HAS_NPN: bool
HAS_SNI: Final[bool]
HAS_TLS_UNIQUE: Final[bool]
HAS_ECDH: Final[bool]
HAS_NPN: Final[bool]
if sys.version_info >= (3, 13):
HAS_PSK: bool
HAS_ALPN: bool
HAS_SSLv2: bool
HAS_SSLv3: bool
HAS_TLSv1: bool
HAS_TLSv1_1: bool
HAS_TLSv1_2: bool
HAS_TLSv1_3: bool
HAS_PSK: Final[bool]
HAS_ALPN: Final[bool]
HAS_SSLv2: Final[bool]
HAS_SSLv3: Final[bool]
HAS_TLSv1: Final[bool]
HAS_TLSv1_1: Final[bool]
HAS_TLSv1_2: Final[bool]
HAS_TLSv1_3: Final[bool]
if sys.version_info >= (3, 14):
HAS_PHA: bool
HAS_PHA: Final[bool]
# version info
OPENSSL_VERSION_NUMBER: int
OPENSSL_VERSION_INFO: tuple[int, int, int, int, int]
OPENSSL_VERSION: str
_OPENSSL_API_VERSION: tuple[int, int, int, int, int]
OPENSSL_VERSION_NUMBER: Final[int]
OPENSSL_VERSION_INFO: Final[tuple[int, int, int, int, int]]
OPENSSL_VERSION: Final[str]
_OPENSSL_API_VERSION: Final[tuple[int, int, int, int, int]]
+2 -2
View File
@@ -73,7 +73,7 @@ def start_new(function: Callable[[Unpack[_Ts]], object], args: tuple[Unpack[_Ts]
def start_new(function: Callable[..., object], args: tuple[Any, ...], kwargs: dict[str, Any], /) -> int: ...
if sys.version_info >= (3, 10):
def interrupt_main(signum: signal.Signals = ..., /) -> None: ...
def interrupt_main(signum: signal.Signals = signal.SIGINT, /) -> None: ...
else:
def interrupt_main() -> None: ...
@@ -85,7 +85,7 @@ def allocate() -> LockType: ... # Obsolete synonym for allocate_lock()
def get_ident() -> int: ...
def stack_size(size: int = 0, /) -> int: ...
TIMEOUT_MAX: float
TIMEOUT_MAX: Final[float]
def get_native_id() -> int: ... # only available on some platforms
@final
@@ -7,6 +7,7 @@ __all__ = ["local"]
_LocalDict: TypeAlias = dict[Any, Any]
class _localimpl:
__slots__ = ("key", "dicts", "localargs", "locallock", "__weakref__")
key: str
dicts: dict[int, tuple[ReferenceType[Any], _LocalDict]]
# Keep localargs in sync with the *args, **kwargs annotation on local.__new__
@@ -16,6 +17,7 @@ class _localimpl:
def create_dict(self) -> _LocalDict: ...
class local:
__slots__ = ("_local__impl", "__dict__")
def __new__(cls, /, *args: Any, **kw: Any) -> Self: ...
def __getattribute__(self, name: str) -> Any: ...
def __setattr__(self, name: str, value: Any) -> None: ...
+2 -1
View File
@@ -1,7 +1,7 @@
import sys
from collections.abc import Callable
from typing import Any, ClassVar, Final, final
from typing_extensions import TypeAlias
from typing_extensions import TypeAlias, deprecated
# _tkinter is meant to be only used internally by tkinter, but some tkinter
# functions e.g. return _tkinter.Tcl_Obj objects. Tcl_Obj represents a Tcl
@@ -84,6 +84,7 @@ class TkappType:
def record(self, script, /): ...
def setvar(self, *ags, **kwargs): ...
if sys.version_info < (3, 11):
@deprecated("Deprecated since Python 3.9; removed in Python 3.11. Use `splitlist()` instead.")
def split(self, arg, /): ...
def splitlist(self, arg, /): ...
@@ -3,7 +3,7 @@
# See the README.md file in this directory for more information.
import sys
from collections.abc import Awaitable, Callable, Iterable, Sequence, Set as AbstractSet, Sized
from collections.abc import Awaitable, Callable, Iterable, Iterator, Sequence, Set as AbstractSet, Sized
from dataclasses import Field
from os import PathLike
from types import FrameType, TracebackType
@@ -65,10 +65,10 @@ MaybeNone: TypeAlias = Any # stable
# In cases where the sentinel object is exported and can be used by user code,
# a construct like this is better:
#
# _SentinelType = NewType("_SentinelType", object)
# sentinel: _SentinelType
# _SentinelType = NewType("_SentinelType", object) # does not exist at runtime
# sentinel: Final[_SentinelType]
# def foo(x: int | None | _SentinelType = ...) -> None: ...
sentinel: Any
sentinel: Any # stable
# stable
class IdentityFunction(Protocol):
@@ -82,19 +82,21 @@ class SupportsNext(Protocol[_T_co]):
class SupportsAnext(Protocol[_T_co]):
def __anext__(self) -> Awaitable[_T_co]: ...
# Comparison protocols
class SupportsBool(Protocol):
def __bool__(self) -> bool: ...
# Comparison protocols
class SupportsDunderLT(Protocol[_T_contra]):
def __lt__(self, other: _T_contra, /) -> bool: ...
def __lt__(self, other: _T_contra, /) -> SupportsBool: ...
class SupportsDunderGT(Protocol[_T_contra]):
def __gt__(self, other: _T_contra, /) -> bool: ...
def __gt__(self, other: _T_contra, /) -> SupportsBool: ...
class SupportsDunderLE(Protocol[_T_contra]):
def __le__(self, other: _T_contra, /) -> bool: ...
def __le__(self, other: _T_contra, /) -> SupportsBool: ...
class SupportsDunderGE(Protocol[_T_contra]):
def __ge__(self, other: _T_contra, /) -> bool: ...
def __ge__(self, other: _T_contra, /) -> SupportsBool: ...
class SupportsAllComparisons(
SupportsDunderLT[Any], SupportsDunderGT[Any], SupportsDunderLE[Any], SupportsDunderGE[Any], Protocol
@@ -273,6 +275,16 @@ class SupportsWrite(Protocol[_T_contra]):
class SupportsFlush(Protocol):
def flush(self) -> object: ...
# Suitable for dictionary view objects
class Viewable(Protocol[_T_co]):
def __len__(self) -> int: ...
def __iter__(self) -> Iterator[_T_co]: ...
class SupportsGetItemViewable(Protocol[_KT, _VT_co]):
def __len__(self) -> int: ...
def __iter__(self) -> Iterator[_KT]: ...
def __getitem__(self, key: _KT, /) -> _VT_co: ...
# Unfortunately PEP 688 does not allow us to distinguish read-only
# from writable buffers. We use these aliases for readability for now.
# Perhaps a future extension of the buffer protocol will allow us to
+17 -14
View File
@@ -128,21 +128,21 @@ if sys.platform == "win32":
WAIT_TIMEOUT: Final = 258
if sys.version_info >= (3, 10):
LOCALE_NAME_INVARIANT: str
LOCALE_NAME_MAX_LENGTH: int
LOCALE_NAME_SYSTEM_DEFAULT: str
LOCALE_NAME_USER_DEFAULT: str | None
LOCALE_NAME_INVARIANT: Final[str]
LOCALE_NAME_MAX_LENGTH: Final[int]
LOCALE_NAME_SYSTEM_DEFAULT: Final[str]
LOCALE_NAME_USER_DEFAULT: Final[str | None]
LCMAP_FULLWIDTH: int
LCMAP_HALFWIDTH: int
LCMAP_HIRAGANA: int
LCMAP_KATAKANA: int
LCMAP_LINGUISTIC_CASING: int
LCMAP_LOWERCASE: int
LCMAP_SIMPLIFIED_CHINESE: int
LCMAP_TITLECASE: int
LCMAP_TRADITIONAL_CHINESE: int
LCMAP_UPPERCASE: int
LCMAP_FULLWIDTH: Final[int]
LCMAP_HALFWIDTH: Final[int]
LCMAP_HIRAGANA: Final[int]
LCMAP_KATAKANA: Final[int]
LCMAP_LINGUISTIC_CASING: Final[int]
LCMAP_LOWERCASE: Final[int]
LCMAP_SIMPLIFIED_CHINESE: Final[int]
LCMAP_TITLECASE: Final[int]
LCMAP_TRADITIONAL_CHINESE: Final[int]
LCMAP_UPPERCASE: Final[int]
if sys.version_info >= (3, 12):
COPYFILE2_CALLBACK_CHUNK_STARTED: Final = 1
@@ -172,6 +172,9 @@ if sys.platform == "win32":
ERROR_ACCESS_DENIED: Final = 5
ERROR_PRIVILEGE_NOT_HELD: Final = 1314
if sys.version_info >= (3, 14):
COPY_FILE_DIRECTORY: Final = 0x00000080
def CloseHandle(handle: int, /) -> None: ...
@overload
def ConnectNamedPipe(handle: int, overlapped: Literal[True]) -> Overlapped: ...
+1
View File
@@ -52,6 +52,7 @@ class ZstdCompressor:
self, /, data: ReadableBuffer, mode: _ZstdCompressorContinue | _ZstdCompressorFlushBlock | _ZstdCompressorFlushFrame = 0
) -> bytes: ...
def flush(self, /, mode: _ZstdCompressorFlushBlock | _ZstdCompressorFlushFrame = 2) -> bytes: ...
def set_pledged_input_size(self, size: int | None, /) -> None: ...
@property
def last_mode(self) -> _ZstdCompressorContinue | _ZstdCompressorFlushBlock | _ZstdCompressorFlushFrame: ...
+3 -3
View File
@@ -28,17 +28,17 @@ class ABCMeta(type):
def register(cls: ABCMeta, subclass: type[_T]) -> type[_T]: ...
def abstractmethod(funcobj: _FuncT) -> _FuncT: ...
@deprecated("Use 'classmethod' with 'abstractmethod' instead")
@deprecated("Deprecated since Python 3.3. Use `@classmethod` stacked on top of `@abstractmethod` instead.")
class abstractclassmethod(classmethod[_T, _P, _R_co]):
__isabstractmethod__: Literal[True]
def __init__(self, callable: Callable[Concatenate[type[_T], _P], _R_co]) -> None: ...
@deprecated("Use 'staticmethod' with 'abstractmethod' instead")
@deprecated("Deprecated since Python 3.3. Use `@staticmethod` stacked on top of `@abstractmethod` instead.")
class abstractstaticmethod(staticmethod[_P, _R_co]):
__isabstractmethod__: Literal[True]
def __init__(self, callable: Callable[_P, _R_co]) -> None: ...
@deprecated("Use 'property' with 'abstractmethod' instead")
@deprecated("Deprecated since Python 3.3. Use `@property` stacked on top of `@abstractmethod` instead.")
class abstractproperty(property):
__isabstractmethod__: Literal[True]
@@ -64,7 +64,7 @@ if sys.version_info >= (3, 14):
owner: object = None,
format: Format = Format.VALUE, # noqa: Y011
) -> AnnotationForm: ...
@deprecated("Use ForwardRef.evaluate() or typing.evaluate_forward_ref() instead.")
@deprecated("Use `ForwardRef.evaluate()` or `typing.evaluate_forward_ref()` instead.")
def _evaluate(
self,
globalns: dict[str, Any] | None,
+47 -22
View File
@@ -2,7 +2,7 @@ import sys
from _typeshed import SupportsWrite, sentinel
from collections.abc import Callable, Generator, Iterable, Sequence
from re import Pattern
from typing import IO, Any, ClassVar, Final, Generic, NoReturn, Protocol, TypeVar, overload
from typing import IO, Any, ClassVar, Final, Generic, NoReturn, Protocol, TypeVar, overload, type_check_only
from typing_extensions import Self, TypeAlias, deprecated
__all__ = [
@@ -112,6 +112,7 @@ class _ActionsContainer:
def _handle_conflict_error(self, action: Action, conflicting_actions: Iterable[tuple[str, Action]]) -> NoReturn: ...
def _handle_conflict_resolve(self, action: Action, conflicting_actions: Iterable[tuple[str, Action]]) -> None: ...
@type_check_only
class _FormatterClass(Protocol):
def __call__(self, *, prog: str) -> HelpFormatter: ...
@@ -281,7 +282,7 @@ class HelpFormatter:
if sys.version_info >= (3, 14):
def __init__(
self, prog: str, indent_increment: int = 2, max_help_position: int = 24, width: int | None = None, color: bool = False
self, prog: str, indent_increment: int = 2, max_help_position: int = 24, width: int | None = None, color: bool = True
) -> None: ...
else:
def __init__(
@@ -467,7 +468,7 @@ class Namespace(_AttributeHolder):
__hash__: ClassVar[None] # type: ignore[assignment]
if sys.version_info >= (3, 14):
@deprecated("Deprecated in Python 3.14; Simply open files after parsing arguments")
@deprecated("Deprecated since Python 3.14. Open files after parsing arguments instead.")
class FileType:
# undocumented
_mode: str
@@ -495,16 +496,40 @@ else:
class _ArgumentGroup(_ActionsContainer):
title: str | None
_group_actions: list[Action]
def __init__(
self,
container: _ActionsContainer,
title: str | None = None,
description: str | None = None,
*,
prefix_chars: str = ...,
argument_default: Any = ...,
conflict_handler: str = ...,
) -> None: ...
if sys.version_info >= (3, 14):
@overload
def __init__(
self,
container: _ActionsContainer,
title: str | None = None,
description: str | None = None,
*,
argument_default: Any = ...,
conflict_handler: str = ...,
) -> None: ...
@overload
@deprecated("Undocumented `prefix_chars` parameter is deprecated since Python 3.14.")
def __init__(
self,
container: _ActionsContainer,
title: str | None = None,
description: str | None = None,
*,
prefix_chars: str,
argument_default: Any = ...,
conflict_handler: str = ...,
) -> None: ...
else:
def __init__(
self,
container: _ActionsContainer,
title: str | None = None,
description: str | None = None,
*,
prefix_chars: str = ...,
argument_default: Any = ...,
conflict_handler: str = ...,
) -> None: ...
# undocumented
class _MutuallyExclusiveGroup(_ArgumentGroup):
@@ -738,9 +763,9 @@ class _SubParsersAction(Action, Generic[_ArgumentParserT]):
fromfile_prefix_chars: str | None = ...,
argument_default: Any = ...,
conflict_handler: str = ...,
add_help: bool = ...,
allow_abbrev: bool = ...,
exit_on_error: bool = ...,
add_help: bool = True,
allow_abbrev: bool = True,
exit_on_error: bool = True,
suggest_on_error: bool = False,
color: bool = False,
**kwargs: Any, # Accepting any additional kwargs for custom parser classes
@@ -764,9 +789,9 @@ class _SubParsersAction(Action, Generic[_ArgumentParserT]):
fromfile_prefix_chars: str | None = ...,
argument_default: Any = ...,
conflict_handler: str = ...,
add_help: bool = ...,
allow_abbrev: bool = ...,
exit_on_error: bool = ...,
add_help: bool = True,
allow_abbrev: bool = True,
exit_on_error: bool = True,
**kwargs: Any, # Accepting any additional kwargs for custom parser classes
) -> _ArgumentParserT: ...
else:
@@ -787,9 +812,9 @@ class _SubParsersAction(Action, Generic[_ArgumentParserT]):
fromfile_prefix_chars: str | None = ...,
argument_default: Any = ...,
conflict_handler: str = ...,
add_help: bool = ...,
allow_abbrev: bool = ...,
exit_on_error: bool = ...,
add_help: bool = True,
allow_abbrev: bool = True,
exit_on_error: bool = True,
**kwargs: Any, # Accepting any additional kwargs for custom parser classes
) -> _ArgumentParserT: ...
+23 -6
View File
@@ -3,11 +3,14 @@ from _typeshed import ReadableBuffer, SupportsRead, SupportsWrite
from collections.abc import Iterable, MutableSequence
from types import GenericAlias
from typing import Any, ClassVar, Literal, SupportsIndex, TypeVar, overload
from typing_extensions import Self, TypeAlias
from typing_extensions import Self, TypeAlias, deprecated
_IntTypeCode: TypeAlias = Literal["b", "B", "h", "H", "i", "I", "l", "L", "q", "Q"]
_FloatTypeCode: TypeAlias = Literal["f", "d"]
_UnicodeTypeCode: TypeAlias = Literal["u"]
if sys.version_info >= (3, 13):
_UnicodeTypeCode: TypeAlias = Literal["u", "w"]
else:
_UnicodeTypeCode: TypeAlias = Literal["u"]
_TypeCode: TypeAlias = _IntTypeCode | _FloatTypeCode | _UnicodeTypeCode
_T = TypeVar("_T", int, float, str)
@@ -27,10 +30,23 @@ class array(MutableSequence[_T]):
def __new__(
cls: type[array[float]], typecode: _FloatTypeCode, initializer: bytes | bytearray | Iterable[float] = ..., /
) -> array[float]: ...
@overload
def __new__(
cls: type[array[str]], typecode: _UnicodeTypeCode, initializer: bytes | bytearray | Iterable[str] = ..., /
) -> array[str]: ...
if sys.version_info >= (3, 13):
@overload
def __new__(
cls: type[array[str]], typecode: Literal["w"], initializer: bytes | bytearray | Iterable[str] = ..., /
) -> array[str]: ...
@overload
@deprecated("Deprecated since Python 3.3; will be removed in Python 3.16. Use 'w' typecode instead.")
def __new__(
cls: type[array[str]], typecode: Literal["u"], initializer: bytes | bytearray | Iterable[str] = ..., /
) -> array[str]: ...
else:
@overload
@deprecated("Deprecated since Python 3.3; will be removed in Python 3.16.")
def __new__(
cls: type[array[str]], typecode: Literal["u"], initializer: bytes | bytearray | Iterable[str] = ..., /
) -> array[str]: ...
@overload
def __new__(cls, typecode: str, initializer: Iterable[_T], /) -> Self: ...
@overload
@@ -58,6 +74,7 @@ class array(MutableSequence[_T]):
def tounicode(self) -> str: ...
__hash__: ClassVar[None] # type: ignore[assignment]
def __contains__(self, value: object, /) -> bool: ...
def __len__(self) -> int: ...
@overload
def __getitem__(self, key: SupportsIndex, /) -> _T: ...
+90 -86
View File
@@ -1,3 +1,4 @@
import ast
import builtins
import os
import sys
@@ -9,7 +10,7 @@ from _ast import (
)
from _typeshed import ReadableBuffer, Unused
from collections.abc import Iterable, Iterator, Sequence
from typing import Any, ClassVar, Generic, Literal, TypedDict, TypeVar as _TypeVar, overload
from typing import Any, ClassVar, Generic, Literal, TypedDict, TypeVar as _TypeVar, overload, type_check_only
from typing_extensions import Self, Unpack, deprecated
if sys.version_info >= (3, 13):
@@ -19,6 +20,7 @@ if sys.version_info >= (3, 13):
_EndPositionT = typing_extensions.TypeVar("_EndPositionT", int, int | None, default=int | None)
# Corresponds to the names in the `_attributes` class variable which is non-empty in certain AST nodes
@type_check_only
class _Attributes(TypedDict, Generic[_EndPositionT], total=False):
lineno: int
col_offset: int
@@ -623,21 +625,6 @@ class AsyncWith(stmt):
**kwargs: Unpack[_Attributes],
) -> Self: ...
if sys.version_info >= (3, 10):
class Match(stmt):
__match_args__ = ("subject", "cases")
subject: expr
cases: list[match_case]
if sys.version_info >= (3, 13):
def __init__(self, subject: expr, cases: list[match_case] = ..., **kwargs: Unpack[_Attributes]) -> None: ...
else:
def __init__(self, subject: expr, cases: list[match_case], **kwargs: Unpack[_Attributes]) -> None: ...
if sys.version_info >= (3, 14):
def __replace__(
self, *, subject: expr = ..., cases: list[match_case] = ..., **kwargs: Unpack[_Attributes]
) -> Self: ...
class Raise(stmt):
if sys.version_info >= (3, 10):
__match_args__ = ("exc", "cause")
@@ -1076,13 +1063,13 @@ if sys.version_info >= (3, 14):
value: expr
str: builtins.str
conversion: int
format_spec: builtins.str | None = None
format_spec: expr | None = None
def __init__(
self,
value: expr = ...,
str: builtins.str = ...,
conversion: int = ...,
format_spec: builtins.str | None = ...,
format_spec: expr | None = ...,
**kwargs: Unpack[_Attributes],
) -> None: ...
def __replace__(
@@ -1091,7 +1078,7 @@ if sys.version_info >= (3, 14):
value: expr = ...,
str: builtins.str = ...,
conversion: int = ...,
format_spec: builtins.str | None = ...,
format_spec: expr | None = ...,
**kwargs: Unpack[_Attributes],
) -> Self: ...
@@ -1110,8 +1097,18 @@ class Constant(expr):
kind: str | None
if sys.version_info < (3, 14):
# Aliases for value, for backwards compatibility
s: _ConstantValue
n: _ConstantValue
@property
@deprecated("Removed in Python 3.14. Use `value` instead.")
def n(self) -> _ConstantValue: ...
@n.setter
@deprecated("Removed in Python 3.14. Use `value` instead.")
def n(self, value: _ConstantValue) -> None: ...
@property
@deprecated("Removed in Python 3.14. Use `value` instead.")
def s(self) -> _ConstantValue: ...
@s.setter
@deprecated("Removed in Python 3.14. Use `value` instead.")
def s(self, value: _ConstantValue) -> None: ...
def __init__(self, value: _ConstantValue, kind: str | None = None, **kwargs: Unpack[_Attributes]) -> None: ...
@@ -1135,13 +1132,13 @@ class Subscript(expr):
if sys.version_info >= (3, 10):
__match_args__ = ("value", "slice", "ctx")
value: expr
slice: _Slice
slice: expr
ctx: expr_context # Not present in Python < 3.13 if not passed to `__init__`
def __init__(self, value: expr, slice: _Slice, ctx: expr_context = ..., **kwargs: Unpack[_Attributes]) -> None: ...
def __init__(self, value: expr, slice: expr, ctx: expr_context = ..., **kwargs: Unpack[_Attributes]) -> None: ...
if sys.version_info >= (3, 14):
def __replace__(
self, *, value: expr = ..., slice: _Slice = ..., ctx: expr_context = ..., **kwargs: Unpack[_Attributes]
self, *, value: expr = ..., slice: expr = ..., ctx: expr_context = ..., **kwargs: Unpack[_Attributes]
) -> Self: ...
class Starred(expr):
@@ -1194,36 +1191,28 @@ class Tuple(expr):
@deprecated("Deprecated since Python 3.9.")
class slice(AST): ...
_Slice: typing_extensions.TypeAlias = expr
_SliceAttributes: typing_extensions.TypeAlias = _Attributes
class Slice(_Slice):
class Slice(expr):
if sys.version_info >= (3, 10):
__match_args__ = ("lower", "upper", "step")
lower: expr | None
upper: expr | None
step: expr | None
def __init__(
self, lower: expr | None = None, upper: expr | None = None, step: expr | None = None, **kwargs: Unpack[_SliceAttributes]
self, lower: expr | None = None, upper: expr | None = None, step: expr | None = None, **kwargs: Unpack[_Attributes]
) -> None: ...
if sys.version_info >= (3, 14):
def __replace__(
self,
*,
lower: expr | None = ...,
upper: expr | None = ...,
step: expr | None = ...,
**kwargs: Unpack[_SliceAttributes],
self, *, lower: expr | None = ..., upper: expr | None = ..., step: expr | None = ..., **kwargs: Unpack[_Attributes]
) -> Self: ...
@deprecated("Deprecated since Python 3.9. Use ast.Tuple instead.")
@deprecated("Deprecated since Python 3.9. Use `ast.Tuple` instead.")
class ExtSlice(slice):
def __new__(cls, dims: Iterable[slice] = (), **kwargs: Unpack[_SliceAttributes]) -> Tuple: ... # type: ignore[misc]
def __new__(cls, dims: Iterable[slice] = (), **kwargs: Unpack[_Attributes]) -> Tuple: ... # type: ignore[misc]
@deprecated("Deprecated since Python 3.9. Use the index value directly instead.")
class Index(slice):
def __new__(cls, value: expr, **kwargs: Unpack[_SliceAttributes]) -> expr: ... # type: ignore[misc]
def __new__(cls, value: expr, **kwargs: Unpack[_Attributes]) -> expr: ... # type: ignore[misc]
class expr_context(AST): ...
@@ -1465,22 +1454,6 @@ class withitem(AST):
def __replace__(self, *, context_expr: expr = ..., optional_vars: expr | None = ...) -> Self: ...
if sys.version_info >= (3, 10):
class match_case(AST):
__match_args__ = ("pattern", "guard", "body")
pattern: _Pattern
guard: expr | None
body: list[stmt]
if sys.version_info >= (3, 13):
def __init__(self, pattern: _Pattern, guard: expr | None = None, body: list[stmt] = ...) -> None: ...
else:
@overload
def __init__(self, pattern: _Pattern, guard: expr | None, body: list[stmt]) -> None: ...
@overload
def __init__(self, pattern: _Pattern, guard: expr | None = None, *, body: list[stmt]) -> None: ...
if sys.version_info >= (3, 14):
def __replace__(self, *, pattern: _Pattern = ..., guard: expr | None = ..., body: list[stmt] = ...) -> Self: ...
class pattern(AST):
lineno: int
col_offset: int
@@ -1493,8 +1466,35 @@ if sys.version_info >= (3, 10):
self, *, lineno: int = ..., col_offset: int = ..., end_lineno: int = ..., end_col_offset: int = ...
) -> Self: ...
# Without the alias, Pyright complains variables named pattern are recursively defined
_Pattern: typing_extensions.TypeAlias = pattern
class match_case(AST):
__match_args__ = ("pattern", "guard", "body")
pattern: ast.pattern
guard: expr | None
body: list[stmt]
if sys.version_info >= (3, 13):
def __init__(self, pattern: ast.pattern, guard: expr | None = None, body: list[stmt] = ...) -> None: ...
elif sys.version_info >= (3, 10):
@overload
def __init__(self, pattern: ast.pattern, guard: expr | None, body: list[stmt]) -> None: ...
@overload
def __init__(self, pattern: ast.pattern, guard: expr | None = None, *, body: list[stmt]) -> None: ...
if sys.version_info >= (3, 14):
def __replace__(self, *, pattern: ast.pattern = ..., guard: expr | None = ..., body: list[stmt] = ...) -> Self: ...
class Match(stmt):
__match_args__ = ("subject", "cases")
subject: expr
cases: list[match_case]
if sys.version_info >= (3, 13):
def __init__(self, subject: expr, cases: list[match_case] = ..., **kwargs: Unpack[_Attributes]) -> None: ...
else:
def __init__(self, subject: expr, cases: list[match_case], **kwargs: Unpack[_Attributes]) -> None: ...
if sys.version_info >= (3, 14):
def __replace__(
self, *, subject: expr = ..., cases: list[match_case] = ..., **kwargs: Unpack[_Attributes]
) -> Self: ...
class MatchValue(pattern):
__match_args__ = ("value",)
@@ -1506,11 +1506,11 @@ if sys.version_info >= (3, 10):
class MatchSingleton(pattern):
__match_args__ = ("value",)
value: Literal[True, False] | None
def __init__(self, value: Literal[True, False] | None, **kwargs: Unpack[_Attributes[int]]) -> None: ...
value: bool | None
def __init__(self, value: bool | None, **kwargs: Unpack[_Attributes[int]]) -> None: ...
if sys.version_info >= (3, 14):
def __replace__(self, *, value: Literal[True, False] | None = ..., **kwargs: Unpack[_Attributes[int]]) -> Self: ...
def __replace__(self, *, value: bool | None = ..., **kwargs: Unpack[_Attributes[int]]) -> Self: ...
class MatchSequence(pattern):
__match_args__ = ("patterns",)
@@ -1590,22 +1590,22 @@ if sys.version_info >= (3, 10):
class MatchStar(pattern):
__match_args__ = ("name",)
name: str | None
def __init__(self, name: str | None, **kwargs: Unpack[_Attributes[int]]) -> None: ...
def __init__(self, name: str | None = None, **kwargs: Unpack[_Attributes[int]]) -> None: ...
if sys.version_info >= (3, 14):
def __replace__(self, *, name: str | None = ..., **kwargs: Unpack[_Attributes[int]]) -> Self: ...
class MatchAs(pattern):
__match_args__ = ("pattern", "name")
pattern: _Pattern | None
pattern: ast.pattern | None
name: str | None
def __init__(
self, pattern: _Pattern | None = None, name: str | None = None, **kwargs: Unpack[_Attributes[int]]
self, pattern: ast.pattern | None = None, name: str | None = None, **kwargs: Unpack[_Attributes[int]]
) -> None: ...
if sys.version_info >= (3, 14):
def __replace__(
self, *, pattern: _Pattern | None = ..., name: str | None = ..., **kwargs: Unpack[_Attributes[int]]
self, *, pattern: ast.pattern | None = ..., name: str | None = ..., **kwargs: Unpack[_Attributes[int]]
) -> Self: ...
class MatchOr(pattern):
@@ -1701,31 +1701,35 @@ if sys.version_info >= (3, 12):
self, *, name: str = ..., default_value: expr | None = ..., **kwargs: Unpack[_Attributes[int]]
) -> Self: ...
class _ABC(type):
def __init__(cls, *args: Unused) -> None: ...
if sys.version_info >= (3, 14):
@type_check_only
class _ABC(type):
def __init__(cls, *args: Unused) -> None: ...
else:
class _ABC(type):
def __init__(cls, *args: Unused) -> None: ...
if sys.version_info < (3, 14):
@deprecated("Replaced by ast.Constant; removed in Python 3.14")
@deprecated("Removed in Python 3.14. Use `ast.Constant` instead.")
class Num(Constant, metaclass=_ABC):
value: int | float | complex
def __new__(cls, n: complex, **kwargs: Unpack[_Attributes]) -> Constant: ... # type: ignore[misc] # pyright: ignore[reportInconsistentConstructor]
@deprecated("Replaced by ast.Constant; removed in Python 3.14")
@deprecated("Removed in Python 3.14. Use `ast.Constant` instead.")
class Str(Constant, metaclass=_ABC):
value: str
# Aliases for value, for backwards compatibility
s: str
def __new__(cls, s: str, **kwargs: Unpack[_Attributes]) -> Constant: ... # type: ignore[misc] # pyright: ignore[reportInconsistentConstructor]
@deprecated("Replaced by ast.Constant; removed in Python 3.14")
@deprecated("Removed in Python 3.14. Use `ast.Constant` instead.")
class Bytes(Constant, metaclass=_ABC):
value: bytes
# Aliases for value, for backwards compatibility
s: bytes
def __new__(cls, s: bytes, **kwargs: Unpack[_Attributes]) -> Constant: ... # type: ignore[misc] # pyright: ignore[reportInconsistentConstructor]
@deprecated("Replaced by ast.Constant; removed in Python 3.14")
class NameConstant(Constant, metaclass=_ABC): ...
@deprecated("Removed in Python 3.14. Use `ast.Constant` instead.")
class NameConstant(Constant, metaclass=_ABC):
def __new__(cls, value: _ConstantValue, kind: str | None, **kwargs: Unpack[_Attributes]) -> Constant: ... # type: ignore[misc] # pyright: ignore[reportInconsistentConstructor]
@deprecated("Replaced by ast.Constant; removed in Python 3.14")
class Ellipsis(Constant, metaclass=_ABC): ...
@deprecated("Removed in Python 3.14. Use `ast.Constant` instead.")
class Ellipsis(Constant, metaclass=_ABC):
def __new__(cls, **kwargs: Unpack[_Attributes]) -> Constant: ... # type: ignore[misc] # pyright: ignore[reportInconsistentConstructor]
# everything below here is defined in ast.py
@@ -1808,7 +1812,7 @@ if sys.version_info >= (3, 13):
type_comments: bool = False,
feature_version: None | int | tuple[int, int] = None,
optimize: Literal[-1, 0, 1, 2] = -1,
) -> AST: ...
) -> mod: ...
else:
@overload
@@ -1879,7 +1883,7 @@ else:
*,
type_comments: bool = False,
feature_version: None | int | tuple[int, int] = None,
) -> AST: ...
) -> mod: ...
def literal_eval(node_or_string: str | AST) -> Any: ...
@@ -2042,15 +2046,15 @@ class NodeVisitor:
def visit_Param(self, node: Param) -> Any: ...
if sys.version_info < (3, 14):
@deprecated("Replaced by visit_Constant; removed in Python 3.14")
@deprecated("Removed in Python 3.14. Use `visit_Constant` instead.")
def visit_Num(self, node: Num) -> Any: ... # type: ignore[deprecated]
@deprecated("Replaced by visit_Constant; removed in Python 3.14")
@deprecated("Removed in Python 3.14. Use `visit_Constant` instead.")
def visit_Str(self, node: Str) -> Any: ... # type: ignore[deprecated]
@deprecated("Replaced by visit_Constant; removed in Python 3.14")
@deprecated("Removed in Python 3.14. Use `visit_Constant` instead.")
def visit_Bytes(self, node: Bytes) -> Any: ... # type: ignore[deprecated]
@deprecated("Replaced by visit_Constant; removed in Python 3.14")
@deprecated("Removed in Python 3.14. Use `visit_Constant` instead.")
def visit_NameConstant(self, node: NameConstant) -> Any: ... # type: ignore[deprecated]
@deprecated("Replaced by visit_Constant; removed in Python 3.14")
@deprecated("Removed in Python 3.14. Use `visit_Constant` instead.")
def visit_Ellipsis(self, node: Ellipsis) -> Any: ... # type: ignore[deprecated]
class NodeTransformer(NodeVisitor):
@@ -1,4 +1,4 @@
# ruff: noqa: PLR5501 # This condition is so big, it's clearer to keep to platform condition in two blocks
# This condition is so big, it's clearer to keep to platform condition in two blocks
# Can't NOQA on a specific line: https://github.com/plinss/flake8-noqa/issues/22
import sys
from collections.abc import Awaitable, Coroutine, Generator
@@ -41,14 +41,11 @@ if sys.platform == "win32":
"Server", # from base_events
"iscoroutinefunction", # from coroutines
"iscoroutine", # from coroutines
"_AbstractEventLoopPolicy", # from events
"AbstractEventLoop", # from events
"AbstractServer", # from events
"Handle", # from events
"TimerHandle", # from events
"_get_event_loop_policy", # from events
"get_event_loop_policy", # from events
"_set_event_loop_policy", # from events
"set_event_loop_policy", # from events
"get_event_loop", # from events
"set_event_loop", # from events
@@ -517,14 +514,11 @@ else:
"Server", # from base_events
"iscoroutinefunction", # from coroutines
"iscoroutine", # from coroutines
"_AbstractEventLoopPolicy", # from events
"AbstractEventLoop", # from events
"AbstractServer", # from events
"Handle", # from events
"TimerHandle", # from events
"_get_event_loop_policy", # from events
"get_event_loop_policy", # from events
"_set_event_loop_policy", # from events
"set_event_loop_policy", # from events
"get_event_loop", # from events
"set_event_loop", # from events
@@ -610,7 +604,6 @@ else:
"DatagramTransport", # from transports
"SubprocessTransport", # from transports
"SelectorEventLoop", # from unix_events
"_DefaultEventLoopPolicy", # from unix_events
"EventLoop", # from unix_events
)
elif sys.version_info >= (3, 13):
@@ -1,19 +1,17 @@
from _asyncio import Future
from collections.abc import Callable, Sequence
from contextvars import Context
from typing import Any, Final
from typing_extensions import TypeIs
from . import futures
__all__ = ()
# asyncio defines 'isfuture()' in base_futures.py and re-imports it in futures.py
# but it leads to circular import error in pytype tool.
# That's why the import order is reversed.
from .futures import isfuture as isfuture
_PENDING: Final = "PENDING" # undocumented
_CANCELLED: Final = "CANCELLED" # undocumented
_FINISHED: Final = "FINISHED" # undocumented
def isfuture(obj: object) -> TypeIs[Future[Any]]: ...
def _format_callbacks(cb: Sequence[tuple[Callable[[futures.Future[Any]], None], Context]]) -> str: ... # undocumented
def _future_repr_info(future: futures.Future[Any]) -> list[str]: ... # undocumented
@@ -1,7 +1,7 @@
import sys
from collections.abc import Awaitable, Callable, Coroutine
from typing import Any, TypeVar, overload
from typing_extensions import ParamSpec, TypeGuard, TypeIs
from typing_extensions import ParamSpec, TypeGuard, TypeIs, deprecated
# Keep asyncio.__all__ updated with any changes to __all__ here
if sys.version_info >= (3, 11):
@@ -14,6 +14,7 @@ _FunctionT = TypeVar("_FunctionT", bound=Callable[..., Any])
_P = ParamSpec("_P")
if sys.version_info < (3, 11):
@deprecated("Deprecated since Python 3.8; removed in Python 3.11. Use `async def` instead.")
def coroutine(func: _FunctionT) -> _FunctionT: ...
@overload
@@ -12,7 +12,7 @@ from collections.abc import Callable, Sequence
from concurrent.futures import Executor
from contextvars import Context
from socket import AddressFamily, SocketKind, _Address, _RetAddress, socket
from typing import IO, Any, Literal, Protocol, TypeVar, overload
from typing import IO, Any, Literal, Protocol, TypeVar, overload, type_check_only
from typing_extensions import Self, TypeAlias, TypeVarTuple, Unpack, deprecated
from . import _AwaitableLike, _CoroutineLike
@@ -28,14 +28,11 @@ if sys.version_info < (3, 14):
# Keep asyncio.__all__ updated with any changes to __all__ here
if sys.version_info >= (3, 14):
__all__ = (
"_AbstractEventLoopPolicy",
"AbstractEventLoop",
"AbstractServer",
"Handle",
"TimerHandle",
"_get_event_loop_policy",
"get_event_loop_policy",
"_set_event_loop_policy",
"set_event_loop_policy",
"get_event_loop",
"set_event_loop",
@@ -71,10 +68,12 @@ _ExceptionHandler: TypeAlias = Callable[[AbstractEventLoop, _Context], object]
_ProtocolFactory: TypeAlias = Callable[[], BaseProtocol]
_SSLContext: TypeAlias = bool | None | ssl.SSLContext
@type_check_only
class _TaskFactory(Protocol):
def __call__(self, loop: AbstractEventLoop, factory: _CoroutineLike[_T], /) -> Future[_T]: ...
class Handle:
__slots__ = ("_callback", "_args", "_cancelled", "_loop", "_source_traceback", "_repr", "__weakref__", "_context")
_cancelled: bool
_args: Sequence[Any]
def __init__(
@@ -87,6 +86,7 @@ class Handle:
def get_context(self) -> Context: ...
class TimerHandle(Handle):
__slots__ = ["_scheduled", "_when"]
def __init__(
self,
when: float,
@@ -602,6 +602,9 @@ class AbstractEventLoop:
@abstractmethod
async def shutdown_default_executor(self) -> None: ...
# This class does not exist at runtime, but stubtest complains if it's marked as
# @type_check_only because it has an alias that does exist at runtime. See mypy#19568.
# @type_check_only
class _AbstractEventLoopPolicy:
@abstractmethod
def get_event_loop(self) -> AbstractEventLoop: ...
@@ -613,10 +616,10 @@ class _AbstractEventLoopPolicy:
if sys.version_info < (3, 14):
if sys.version_info >= (3, 12):
@abstractmethod
@deprecated("Deprecated as of Python 3.12; will be removed in Python 3.14")
@deprecated("Deprecated since Python 3.12; removed in Python 3.14.")
def get_child_watcher(self) -> AbstractChildWatcher: ...
@abstractmethod
@deprecated("Deprecated as of Python 3.12; will be removed in Python 3.14")
@deprecated("Deprecated since Python 3.12; removed in Python 3.14.")
def set_child_watcher(self, watcher: AbstractChildWatcher) -> None: ...
else:
@abstractmethod
@@ -642,9 +645,9 @@ else:
if sys.version_info >= (3, 14):
def _get_event_loop_policy() -> _AbstractEventLoopPolicy: ...
def _set_event_loop_policy(policy: _AbstractEventLoopPolicy | None) -> None: ...
@deprecated("Deprecated as of Python 3.14; will be removed in Python 3.16")
@deprecated("Deprecated since Python 3.14; will be removed in Python 3.16.")
def get_event_loop_policy() -> _AbstractEventLoopPolicy: ...
@deprecated("Deprecated as of Python 3.14; will be removed in Python 3.16")
@deprecated("Deprecated since Python 3.14; will be removed in Python 3.16.")
def set_event_loop_policy(policy: _AbstractEventLoopPolicy | None) -> None: ...
else:
@@ -656,9 +659,9 @@ def new_event_loop() -> AbstractEventLoop: ...
if sys.version_info < (3, 14):
if sys.version_info >= (3, 12):
@deprecated("Deprecated as of Python 3.12; will be removed in Python 3.14")
@deprecated("Deprecated since Python 3.12; removed in Python 3.14.")
def get_child_watcher() -> AbstractChildWatcher: ...
@deprecated("Deprecated as of Python 3.12; will be removed in Python 3.14")
@deprecated("Deprecated since Python 3.12; removed in Python 3.14.")
def set_child_watcher(watcher: AbstractChildWatcher) -> None: ...
else:
@@ -3,9 +3,10 @@ import sys
import traceback
from collections.abc import Iterable
from types import FrameType, FunctionType
from typing import Any, overload
from typing import Any, overload, type_check_only
from typing_extensions import TypeAlias
@type_check_only
class _HasWrapper:
__wrapper__: _HasWrapper | FunctionType
@@ -1,9 +1,9 @@
import sys
from _asyncio import Future as Future
from concurrent.futures._base import Future as _ConcurrentFuture
from typing import Any, TypeVar
from typing_extensions import TypeIs
from typing import TypeVar
from .base_futures import isfuture as isfuture
from .events import AbstractEventLoop
# Keep asyncio.__all__ updated with any changes to __all__ here
@@ -16,8 +16,4 @@ else:
_T = TypeVar("_T")
# asyncio defines 'isfuture()' in base_futures.py and re-imports it in futures.py
# but it leads to circular import error in pytype tool.
# That's why the import order is reversed.
def isfuture(obj: object) -> TypeIs[Future[Any]]: ...
def wrap_future(future: _ConcurrentFuture[_T] | Future[_T], *, loop: AbstractEventLoop | None = None) -> Future[_T]: ...
@@ -6,21 +6,26 @@ from typing import Any
__all__ = ("BaseProtocol", "Protocol", "DatagramProtocol", "SubprocessProtocol", "BufferedProtocol")
class BaseProtocol:
__slots__ = ()
def connection_made(self, transport: transports.BaseTransport) -> None: ...
def connection_lost(self, exc: Exception | None) -> None: ...
def pause_writing(self) -> None: ...
def resume_writing(self) -> None: ...
class Protocol(BaseProtocol):
# Need annotation or mypy will complain about 'Cannot determine type of "__slots__" in base class'
__slots__: tuple[()] = ()
def data_received(self, data: bytes) -> None: ...
def eof_received(self) -> bool | None: ...
class BufferedProtocol(BaseProtocol):
__slots__ = ()
def get_buffer(self, sizehint: int) -> ReadableBuffer: ...
def buffer_updated(self, nbytes: int) -> None: ...
def eof_received(self) -> bool | None: ...
class DatagramProtocol(BaseProtocol):
__slots__ = ()
def connection_made(self, transport: transports.DatagramTransport) -> None: ... # type: ignore[override]
# addr can be a tuple[int, int] for some unusual protocols like socket.AF_NETLINK.
# Use tuple[str | Any, int] to not cause typechecking issues on most usual cases.
@@ -30,6 +35,7 @@ class DatagramProtocol(BaseProtocol):
def error_received(self, exc: Exception) -> None: ...
class SubprocessProtocol(BaseProtocol):
__slots__: tuple[()] = ()
def pipe_data_received(self, fd: int, data: bytes) -> None: ...
def pipe_connection_lost(self, fd: int, exc: Exception | None) -> None: ...
def process_exited(self) -> None: ...
@@ -1,4 +1,5 @@
import sys
from _typeshed import SupportsRichComparisonT
from asyncio.events import AbstractEventLoop
from types import GenericAlias
from typing import Any, Generic, TypeVar
@@ -50,5 +51,5 @@ class Queue(Generic[_T], _LoopBoundMixin): # noqa: Y059
if sys.version_info >= (3, 13):
def shutdown(self, immediate: bool = False) -> None: ...
class PriorityQueue(Queue[_T]): ...
class PriorityQueue(Queue[SupportsRichComparisonT]): ...
class LifoQueue(Queue[_T]): ...
@@ -26,7 +26,7 @@ if sys.version_info >= (3, 11):
if sys.version_info >= (3, 12):
def run(
main: Coroutine[Any, Any, _T], *, debug: bool | None = ..., loop_factory: Callable[[], AbstractEventLoop] | None = ...
main: Coroutine[Any, Any, _T], *, debug: bool | None = None, loop_factory: Callable[[], AbstractEventLoop] | None = None
) -> _T: ...
else:
@@ -3,7 +3,7 @@ import sys
from _typeshed import ReadableBuffer, StrPath
from collections.abc import Awaitable, Callable, Iterable, Sequence, Sized
from types import ModuleType
from typing import Any, Protocol, SupportsIndex
from typing import Any, Protocol, SupportsIndex, type_check_only
from typing_extensions import Self, TypeAlias
from . import events, protocols, transports
@@ -25,6 +25,7 @@ else:
_ClientConnectedCallback: TypeAlias = Callable[[StreamReader, StreamWriter], Awaitable[None] | None]
@type_check_only
class _ReaduntilBuffer(ReadableBuffer, Sized, Protocol): ...
if sys.version_info >= (3, 10):
@@ -8,7 +8,7 @@ from _asyncio import (
_unregister_task as _unregister_task,
)
from collections.abc import AsyncIterator, Awaitable, Coroutine, Generator, Iterable, Iterator
from typing import Any, Literal, Protocol, TypeVar, overload
from typing import Any, Final, Literal, Protocol, TypeVar, overload, type_check_only
from typing_extensions import TypeAlias
from . import _CoroutineLike
@@ -82,11 +82,12 @@ else:
_TaskYieldType: TypeAlias = Future[object] | None
FIRST_COMPLETED = concurrent.futures.FIRST_COMPLETED
FIRST_EXCEPTION = concurrent.futures.FIRST_EXCEPTION
ALL_COMPLETED = concurrent.futures.ALL_COMPLETED
FIRST_COMPLETED: Final = concurrent.futures.FIRST_COMPLETED
FIRST_EXCEPTION: Final = concurrent.futures.FIRST_EXCEPTION
ALL_COMPLETED: Final = concurrent.futures.ALL_COMPLETED
if sys.version_info >= (3, 13):
@type_check_only
class _SyncAndAsyncIterator(Iterator[_T_co], AsyncIterator[_T_co], Protocol[_T_co]): ...
def as_completed(fs: Iterable[_FutureLike[_T]], *, timeout: float | None = None) -> _SyncAndAsyncIterator[Future[_T]]: ...
@@ -445,6 +446,7 @@ elif sys.version_info >= (3, 12):
if sys.version_info >= (3, 12):
_TaskT_co = TypeVar("_TaskT_co", bound=Task[Any], covariant=True)
@type_check_only
class _CustomTaskConstructor(Protocol[_TaskT_co]):
def __call__(
self,
@@ -457,6 +459,7 @@ if sys.version_info >= (3, 12):
eager_start: bool,
) -> _TaskT_co: ...
@type_check_only
class _EagerTaskFactoryType(Protocol[_TaskT_co]):
def __call__(
self,
@@ -0,0 +1,41 @@
from collections.abc import Iterable
from enum import Enum
from typing import NamedTuple, SupportsIndex, type_check_only
@type_check_only
class _AwaitedInfo(NamedTuple): # AwaitedInfo_Type from _remote_debugging
thread_id: int
awaited_by: list[_TaskInfo]
@type_check_only
class _TaskInfo(NamedTuple): # TaskInfo_Type from _remote_debugging
task_id: int
task_name: str
coroutine_stack: list[_CoroInfo]
awaited_by: list[_CoroInfo]
@type_check_only
class _CoroInfo(NamedTuple): # CoroInfo_Type from _remote_debugging
call_stack: list[_FrameInfo]
task_name: int | str
@type_check_only
class _FrameInfo(NamedTuple): # FrameInfo_Type from _remote_debugging
filename: str
lineno: int
funcname: str
class NodeType(Enum):
COROUTINE = 1
TASK = 2
class CycleFoundException(Exception):
cycles: list[list[int]]
id2name: dict[int, str]
def __init__(self, cycles: list[list[int]], id2name: dict[int, str]) -> None: ...
def get_all_awaited_by(pid: SupportsIndex) -> list[_AwaitedInfo]: ...
def build_async_tree(result: Iterable[_AwaitedInfo], task_emoji: str = "(T)", cor_emoji: str = "") -> list[list[str]]: ...
def build_task_table(result: Iterable[_AwaitedInfo]) -> list[list[int | str]]: ...
def display_awaited_by_tasks_table(pid: SupportsIndex) -> None: ...
def display_awaited_by_tasks_tree(pid: SupportsIndex) -> None: ...
@@ -8,6 +8,7 @@ from typing import Any
__all__ = ("BaseTransport", "ReadTransport", "WriteTransport", "Transport", "DatagramTransport", "SubprocessTransport")
class BaseTransport:
__slots__ = ("_extra",)
def __init__(self, extra: Mapping[str, Any] | None = None) -> None: ...
def get_extra_info(self, name: str, default: Any = None) -> Any: ...
def is_closing(self) -> bool: ...
@@ -16,11 +17,13 @@ class BaseTransport:
def get_protocol(self) -> BaseProtocol: ...
class ReadTransport(BaseTransport):
__slots__ = ()
def is_reading(self) -> bool: ...
def pause_reading(self) -> None: ...
def resume_reading(self) -> None: ...
class WriteTransport(BaseTransport):
__slots__ = ()
def set_write_buffer_limits(self, high: int | None = None, low: int | None = None) -> None: ...
def get_write_buffer_size(self) -> int: ...
def get_write_buffer_limits(self) -> tuple[int, int]: ...
@@ -32,13 +35,16 @@ class WriteTransport(BaseTransport):
def can_write_eof(self) -> bool: ...
def abort(self) -> None: ...
class Transport(ReadTransport, WriteTransport): ...
class Transport(ReadTransport, WriteTransport):
__slots__ = ()
class DatagramTransport(BaseTransport):
__slots__ = ()
def sendto(self, data: bytes | bytearray | memoryview, addr: _Address | None = None) -> None: ...
def abort(self) -> None: ...
class SubprocessTransport(BaseTransport):
__slots__ = ()
def get_pid(self) -> int: ...
def get_returncode(self) -> int | None: ...
def get_pipe_transport(self, fd: int) -> BaseTransport | None: ...
@@ -47,4 +53,5 @@ class SubprocessTransport(BaseTransport):
def kill(self) -> None: ...
class _FlowControlMixin(Transport):
__slots__ = ("_loop", "_protocol_paused", "_high_water", "_low_water")
def __init__(self, extra: Mapping[str, Any] | None = None, loop: AbstractEventLoop | None = None) -> None: ...
@@ -5,7 +5,7 @@ from builtins import type as Type # alias to avoid name clashes with property n
from collections.abc import Iterable
from types import TracebackType
from typing import Any, BinaryIO, NoReturn, overload
from typing_extensions import TypeAlias
from typing_extensions import TypeAlias, deprecated
# These are based in socket, maybe move them out into _typeshed.pyi or such
_Address: TypeAlias = socket._Address
@@ -14,6 +14,7 @@ _WriteBuffer: TypeAlias = bytearray | memoryview
_CMSG: TypeAlias = tuple[int, int, bytes]
class TransportSocket:
__slots__ = ("_sock",)
def __init__(self, sock: socket.socket) -> None: ...
@property
def family(self) -> int: ...
@@ -42,53 +43,82 @@ class TransportSocket:
def setblocking(self, flag: bool) -> None: ...
if sys.version_info < (3, 11):
def _na(self, what: str) -> None: ...
@deprecated("Removed in Python 3.11")
def accept(self) -> tuple[socket.socket, _RetAddress]: ...
@deprecated("Removed in Python 3.11")
def connect(self, address: _Address) -> None: ...
@deprecated("Removed in Python 3.11")
def connect_ex(self, address: _Address) -> int: ...
@deprecated("Removed in Python 3.11")
def bind(self, address: _Address) -> None: ...
if sys.platform == "win32":
@deprecated("Removed in Python 3.11")
def ioctl(self, control: int, option: int | tuple[int, int, int] | bool) -> None: ...
else:
@deprecated("Removed in Python 3.11")
def ioctl(self, control: int, option: int | tuple[int, int, int] | bool) -> NoReturn: ...
@deprecated("Removed in Python 3.11")
def listen(self, backlog: int = ..., /) -> None: ...
@deprecated("Removed in Python 3.11")
def makefile(self) -> BinaryIO: ...
@deprecated("Rmoved in Python 3.11")
def sendfile(self, file: BinaryIO, offset: int = ..., count: int | None = ...) -> int: ...
@deprecated("Removed in Python 3.11")
def close(self) -> None: ...
@deprecated("Removed in Python 3.11")
def detach(self) -> int: ...
if sys.platform == "linux":
@deprecated("Removed in Python 3.11")
def sendmsg_afalg(
self, msg: Iterable[ReadableBuffer] = ..., *, op: int, iv: Any = ..., assoclen: int = ..., flags: int = ...
) -> int: ...
else:
@deprecated("Removed in Python 3.11.")
def sendmsg_afalg(
self, msg: Iterable[ReadableBuffer] = ..., *, op: int, iv: Any = ..., assoclen: int = ..., flags: int = ...
) -> NoReturn: ...
@deprecated("Removed in Python 3.11.")
def sendmsg(
self, buffers: Iterable[ReadableBuffer], ancdata: Iterable[_CMSG] = ..., flags: int = ..., address: _Address = ..., /
) -> int: ...
@overload
@deprecated("Removed in Python 3.11.")
def sendto(self, data: ReadableBuffer, address: _Address) -> int: ...
@overload
@deprecated("Removed in Python 3.11.")
def sendto(self, data: ReadableBuffer, flags: int, address: _Address) -> int: ...
@deprecated("Removed in Python 3.11.")
def send(self, data: ReadableBuffer, flags: int = ...) -> int: ...
@deprecated("Removed in Python 3.11.")
def sendall(self, data: ReadableBuffer, flags: int = ...) -> None: ...
@deprecated("Removed in Python 3.11.")
def set_inheritable(self, inheritable: bool) -> None: ...
if sys.platform == "win32":
@deprecated("Removed in Python 3.11.")
def share(self, process_id: int) -> bytes: ...
else:
@deprecated("Removed in Python 3.11.")
def share(self, process_id: int) -> NoReturn: ...
@deprecated("Removed in Python 3.11.")
def recv_into(self, buffer: _WriteBuffer, nbytes: int = ..., flags: int = ...) -> int: ...
@deprecated("Removed in Python 3.11.")
def recvfrom_into(self, buffer: _WriteBuffer, nbytes: int = ..., flags: int = ...) -> tuple[int, _RetAddress]: ...
@deprecated("Removed in Python 3.11.")
def recvmsg_into(
self, buffers: Iterable[_WriteBuffer], ancbufsize: int = ..., flags: int = ..., /
) -> tuple[int, list[_CMSG], int, Any]: ...
@deprecated("Removed in Python 3.11.")
def recvmsg(self, bufsize: int, ancbufsize: int = ..., flags: int = ..., /) -> tuple[bytes, list[_CMSG], int, Any]: ...
@deprecated("Removed in Python 3.11.")
def recvfrom(self, bufsize: int, flags: int = ...) -> tuple[bytes, _RetAddress]: ...
@deprecated("Removed in Python 3.11.")
def recv(self, bufsize: int, flags: int = ...) -> bytes: ...
@deprecated("Removed in Python 3.11.")
def __enter__(self) -> socket.socket: ...
@deprecated("Removed in Python 3.11.")
def __exit__(
self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None
) -> None: ...
@@ -16,7 +16,7 @@ _Ts = TypeVarTuple("_Ts")
# Keep asyncio.__all__ updated with any changes to __all__ here
if sys.platform != "win32":
if sys.version_info >= (3, 14):
__all__ = ("SelectorEventLoop", "_DefaultEventLoopPolicy", "EventLoop")
__all__ = ("SelectorEventLoop", "EventLoop")
elif sys.version_info >= (3, 13):
# Adds EventLoop
__all__ = (
@@ -48,7 +48,7 @@ if sys.platform != "win32":
# So, it is special cased.
if sys.version_info < (3, 14):
if sys.version_info >= (3, 12):
@deprecated("Deprecated as of Python 3.12; will be removed in Python 3.14")
@deprecated("Deprecated since Python 3.12; removed in Python 3.14.")
class AbstractChildWatcher:
@abstractmethod
def add_child_handler(
@@ -100,7 +100,7 @@ if sys.platform != "win32":
def is_active(self) -> bool: ...
def attach_loop(self, loop: events.AbstractEventLoop | None) -> None: ...
@deprecated("Deprecated as of Python 3.12; will be removed in Python 3.14")
@deprecated("Deprecated since Python 3.12; removed in Python 3.14.")
class SafeChildWatcher(BaseChildWatcher):
def __enter__(self) -> Self: ...
def __exit__(
@@ -111,7 +111,7 @@ if sys.platform != "win32":
) -> None: ...
def remove_child_handler(self, pid: int) -> bool: ...
@deprecated("Deprecated as of Python 3.12; will be removed in Python 3.14")
@deprecated("Deprecated since Python 3.12; removed in Python 3.14.")
class FastChildWatcher(BaseChildWatcher):
def __enter__(self) -> Self: ...
def __exit__(
@@ -171,9 +171,9 @@ if sys.platform != "win32":
else:
class _UnixDefaultEventLoopPolicy(events.BaseDefaultEventLoopPolicy):
if sys.version_info >= (3, 12):
@deprecated("Deprecated as of Python 3.12; will be removed in Python 3.14")
@deprecated("Deprecated since Python 3.12; removed in Python 3.14.")
def get_child_watcher(self) -> AbstractChildWatcher: ...
@deprecated("Deprecated as of Python 3.12; will be removed in Python 3.14")
@deprecated("Deprecated since Python 3.12; removed in Python 3.14.")
def set_child_watcher(self, watcher: AbstractChildWatcher | None) -> None: ...
else:
def get_child_watcher(self) -> AbstractChildWatcher: ...
@@ -191,7 +191,7 @@ if sys.platform != "win32":
if sys.version_info < (3, 14):
if sys.version_info >= (3, 12):
@deprecated("Deprecated as of Python 3.12; will be removed in Python 3.14")
@deprecated("Deprecated since Python 3.12; removed in Python 3.14.")
class MultiLoopChildWatcher(AbstractChildWatcher):
def is_active(self) -> bool: ...
def close(self) -> None: ...

Some files were not shown because too many files have changed in this diff Show More