From 7bdd61f2d89ecd2cee4ebe6eb2375a72b29f0b10 Mon Sep 17 00:00:00 2001 From: Ali Hamdan Date: Mon, 5 Feb 2024 01:41:24 +0100 Subject: [PATCH 01/54] stubgen: Fix crash on star unpack of TypeVarTuple (#16869) Fixes #16864 --- mypy/stubgen.py | 4 +++ mypy/test/teststubgen.py | 4 +++ test-data/unit/stubgen.test | 50 +++++++++++++++++++++++++++++++++++++ 3 files changed, 58 insertions(+) diff --git a/mypy/stubgen.py b/mypy/stubgen.py index 1f7a01e6ae3c..c314fabc882d 100755 --- a/mypy/stubgen.py +++ b/mypy/stubgen.py @@ -100,6 +100,7 @@ OpExpr, OverloadedFuncDef, SetExpr, + StarExpr, Statement, StrExpr, TempNode, @@ -339,6 +340,9 @@ def visit_ellipsis(self, node: EllipsisExpr) -> str: def visit_op_expr(self, o: OpExpr) -> str: return f"{o.left.accept(self)} {o.op} {o.right.accept(self)}" + def visit_star_expr(self, o: StarExpr) -> str: + return f"*{o.expr.accept(self)}" + def find_defined_names(file: MypyFile) -> set[str]: finder = DefinitionFinder() diff --git a/mypy/test/teststubgen.py b/mypy/test/teststubgen.py index c138f9953918..3669772854cb 100644 --- a/mypy/test/teststubgen.py +++ b/mypy/test/teststubgen.py @@ -10,6 +10,8 @@ from types import ModuleType from typing import Any +import pytest + from mypy.errors import CompileError from mypy.moduleinspect import InspectError, ModuleInspect from mypy.stubdoc import ( @@ -698,6 +700,8 @@ def run_case_inner(self, testcase: DataDrivenTestCase) -> None: f.write(content) options = self.parse_flags(source, extra) + if sys.version_info < options.pyversion: + pytest.skip() modules = self.parse_modules(source) out_dir = "out" try: diff --git a/test-data/unit/stubgen.test b/test-data/unit/stubgen.test index 751a1a7fbbcf..3b3bc658a14a 100644 --- a/test-data/unit/stubgen.test +++ b/test-data/unit/stubgen.test @@ -1211,6 +1211,56 @@ T = TypeVar('T') class D(Generic[T]): ... +[case testGenericClassTypeVarTuple] +from typing import Generic +from typing_extensions import TypeVarTuple, Unpack +Ts = TypeVarTuple('Ts') +class D(Generic[Unpack[Ts]]): ... +[out] +from typing import Generic +from typing_extensions import TypeVarTuple, Unpack + +Ts = TypeVarTuple('Ts') + +class D(Generic[Unpack[Ts]]): ... + +[case testGenericClassTypeVarTuple_semanal] +from typing import Generic +from typing_extensions import TypeVarTuple, Unpack +Ts = TypeVarTuple('Ts') +class D(Generic[Unpack[Ts]]): ... +[out] +from typing import Generic +from typing_extensions import TypeVarTuple, Unpack + +Ts = TypeVarTuple('Ts') + +class D(Generic[Unpack[Ts]]): ... + +[case testGenericClassTypeVarTuplePy311] +# flags: --python-version=3.11 +from typing import Generic, TypeVarTuple +Ts = TypeVarTuple('Ts') +class D(Generic[*Ts]): ... +[out] +from typing import Generic, TypeVarTuple + +Ts = TypeVarTuple('Ts') + +class D(Generic[*Ts]): ... + +[case testGenericClassTypeVarTuplePy311_semanal] +# flags: --python-version=3.11 +from typing import Generic, TypeVarTuple +Ts = TypeVarTuple('Ts') +class D(Generic[*Ts]): ... +[out] +from typing import Generic, TypeVarTuple + +Ts = TypeVarTuple('Ts') + +class D(Generic[*Ts]): ... + [case testObjectBaseClass] class A(object): ... [out] From ede0b200a10186a095378516d840389f8da4edd4 Mon Sep 17 00:00:00 2001 From: Alex Waygood Date: Mon, 5 Feb 2024 00:42:13 +0000 Subject: [PATCH 02/54] Bump ruff to 0.2.0 (#16870) Fix this deprecation warning when running ruff on the repository directly: ``` warning: The top-level linter settings are deprecated in favour of their counterparts in the `lint` section. Please update the following options in `pyproject.toml`: - 'ignore' -> 'lint.ignore' - 'select' -> 'lint.select' - 'unfixable' -> 'lint.unfixable' - 'isort' -> 'lint.isort' ``` Note that you don't see the deprecation warnings if you run ruff via pre-commit (only if you run ruff directly, e.g. via ruff .), since pre-commit [swallows all output from a tool if the tool exits with code 0](https://stackoverflow.com/questions/72895720/pre-commit-hook-does-not-echo-on-terminal/72898524#72898524). --- .pre-commit-config.yaml | 2 +- pyproject.toml | 29 +++++++++++++++-------------- test-requirements.in | 2 +- test-requirements.txt | 2 +- 4 files changed, 18 insertions(+), 17 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index eec410457641..4cfb8297a66a 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -11,7 +11,7 @@ repos: - id: black exclude: '^(test-data/)' - repo: https://github.com/astral-sh/ruff-pre-commit - rev: v0.1.15 # must match test-requirements.txt + rev: v0.2.0 # must match test-requirements.txt hooks: - id: ruff args: [--exit-non-zero-on-fix] diff --git a/pyproject.toml b/pyproject.toml index 5fc0cee3f65c..fa6cf876b647 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -30,6 +30,20 @@ line-length = 99 target-version = "py38" fix = true +extend-exclude = [ + "@*", + # Sphinx configuration is irrelevant + "docs/source/conf.py", + "mypyc/doc/conf.py", + # tests have more relaxed styling requirements + # fixtures have their own .pyi-specific configuration + "test-data/*", + "mypyc/test-data/*", + # typeshed has its own .pyi-specific configuration + "mypy/typeshed/*", +] + +[tool.ruff.lint] select = [ "E", # pycodestyle (error) "F", # pyflakes @@ -66,20 +80,7 @@ unfixable = [ "UP036", # sometimes it's better to just noqa this ] -extend-exclude = [ - "@*", - # Sphinx configuration is irrelevant - "docs/source/conf.py", - "mypyc/doc/conf.py", - # tests have more relaxed styling requirements - # fixtures have their own .pyi-specific configuration - "test-data/*", - "mypyc/test-data/*", - # typeshed has its own .pyi-specific configuration - "mypy/typeshed/*", -] - -[tool.ruff.isort] +[tool.ruff.lint.isort] combine-as-imports = true extra-standard-library = ["typing_extensions"] diff --git a/test-requirements.in b/test-requirements.in index a158f5c05ee1..8eeef206018e 100644 --- a/test-requirements.in +++ b/test-requirements.in @@ -14,6 +14,6 @@ psutil>=4.0 pytest>=7.4.0 pytest-xdist>=1.34.0 pytest-cov>=2.10.0 -ruff==0.1.15 # must match version in .pre-commit-config.yaml +ruff==0.2.0 # must match version in .pre-commit-config.yaml setuptools>=65.5.1 tomli>=1.1.0 # needed even on py311+ so the self check passes with --python-version 3.8 diff --git a/test-requirements.txt b/test-requirements.txt index dcd250970a15..525edbc252d8 100644 --- a/test-requirements.txt +++ b/test-requirements.txt @@ -67,7 +67,7 @@ ruamel-yaml==0.17.40 # via pre-commit-hooks ruamel-yaml-clib==0.2.8 # via ruamel-yaml -ruff==0.1.15 +ruff==0.2.0 # via -r test-requirements.in tomli==2.0.1 # via -r test-requirements.in From b956e6a57c4dd36d670097a3eccf7dc092348fec Mon Sep 17 00:00:00 2001 From: Sebastian Rittau Date: Mon, 5 Feb 2024 14:17:43 +0100 Subject: [PATCH 03/54] stubtest: Private parameters can be omitted (#16507) Fixes #16443 --- CHANGELOG.md | 3 ++ mypy/stubtest.py | 14 ++++++-- mypy/test/teststubtest.py | 72 +++++++++++++++++++++++++++++++++++++++ 3 files changed, 87 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 82d79b415f5d..bae881656865 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,9 @@ ## Next release +Stubtest will ignore private function/method parameters when they are missing from the stub. Private parameters +names start with a single underscore and have a default (PR [16507](https://github.com/python/mypy/pull/16507)). + ## Mypy 1.8 We’ve just uploaded mypy 1.8 to the Python Package Index ([PyPI](https://pypi.org/project/mypy/)). Mypy is a static type checker for Python. This release includes new features, performance improvements and bug fixes. You can install it as follows: diff --git a/mypy/stubtest.py b/mypy/stubtest.py index 225c1c35c1be..0e8a1c3ceac2 100644 --- a/mypy/stubtest.py +++ b/mypy/stubtest.py @@ -940,7 +940,8 @@ def _verify_signature( elif len(stub.pos) < len(runtime.pos): for runtime_arg in runtime.pos[len(stub.pos) :]: if runtime_arg.name not in stub.kwonly: - yield f'stub does not have argument "{runtime_arg.name}"' + if not _is_private_parameter(runtime_arg): + yield f'stub does not have argument "{runtime_arg.name}"' else: yield f'runtime argument "{runtime_arg.name}" is not keyword-only' @@ -980,7 +981,8 @@ def _verify_signature( ): yield f'stub argument "{arg}" is not keyword-only' else: - yield f'stub does not have argument "{arg}"' + if not _is_private_parameter(runtime.kwonly[arg]): + yield f'stub does not have argument "{arg}"' # Checks involving **kwargs if stub.varkw is None and runtime.varkw is not None: @@ -995,6 +997,14 @@ def _verify_signature( yield f'runtime does not have **kwargs argument "{stub.varkw.variable.name}"' +def _is_private_parameter(arg: inspect.Parameter) -> bool: + return ( + arg.name.startswith("_") + and not arg.name.startswith("__") + and arg.default is not inspect.Parameter.empty + ) + + @verify.register(nodes.FuncItem) def verify_funcitem( stub: nodes.FuncItem, runtime: MaybeMissing[Any], object_path: list[str] diff --git a/mypy/test/teststubtest.py b/mypy/test/teststubtest.py index 55f35200a7f5..418308e2e65e 100644 --- a/mypy/test/teststubtest.py +++ b/mypy/test/teststubtest.py @@ -346,6 +346,78 @@ def test_arg_kind(self) -> Iterator[Case]: error="stub_posonly_570", ) + @collect_cases + def test_private_parameters(self) -> Iterator[Case]: + # Private parameters can optionally be omitted. + yield Case( + stub="def priv_pos_arg_missing() -> None: ...", + runtime="def priv_pos_arg_missing(_p1=None): pass", + error=None, + ) + yield Case( + stub="def multi_priv_args() -> None: ...", + runtime="def multi_priv_args(_p='', _q=''): pass", + error=None, + ) + yield Case( + stub="def priv_kwarg_missing() -> None: ...", + runtime="def priv_kwarg_missing(*, _p2=''): pass", + error=None, + ) + # But if they are included, they must be correct. + yield Case( + stub="def priv_pos_arg_wrong(_p: int = ...) -> None: ...", + runtime="def priv_pos_arg_wrong(_p=None): pass", + error="priv_pos_arg_wrong", + ) + yield Case( + stub="def priv_kwarg_wrong(*, _p: int = ...) -> None: ...", + runtime="def priv_kwarg_wrong(*, _p=None): pass", + error="priv_kwarg_wrong", + ) + # Private parameters must have a default and start with exactly one + # underscore. + yield Case( + stub="def pos_arg_no_default() -> None: ...", + runtime="def pos_arg_no_default(_np): pass", + error="pos_arg_no_default", + ) + yield Case( + stub="def kwarg_no_default() -> None: ...", + runtime="def kwarg_no_default(*, _np): pass", + error="kwarg_no_default", + ) + yield Case( + stub="def double_underscore_pos_arg() -> None: ...", + runtime="def double_underscore_pos_arg(__np = None): pass", + error="double_underscore_pos_arg", + ) + yield Case( + stub="def double_underscore_kwarg() -> None: ...", + runtime="def double_underscore_kwarg(*, __np = None): pass", + error="double_underscore_kwarg", + ) + # But spot parameters that are accidentally not marked kw-only and + # vice-versa. + yield Case( + stub="def priv_arg_is_kwonly(_p=...) -> None: ...", + runtime="def priv_arg_is_kwonly(*, _p=''): pass", + error="priv_arg_is_kwonly", + ) + yield Case( + stub="def priv_arg_is_positional(*, _p=...) -> None: ...", + runtime="def priv_arg_is_positional(_p=''): pass", + error="priv_arg_is_positional", + ) + # Private parameters not at the end of the parameter list must be + # included so that users can pass the following arguments using + # positional syntax. + yield Case( + stub="def priv_args_not_at_end(*, q='') -> None: ...", + runtime="def priv_args_not_at_end(_p='', q=''): pass", + error="priv_args_not_at_end", + ) + @collect_cases def test_default_presence(self) -> Iterator[Case]: yield Case( From 5c5f3ad412bcd0ea510f5918578ed24325829033 Mon Sep 17 00:00:00 2001 From: James Braza Date: Tue, 6 Feb 2024 16:49:52 -0800 Subject: [PATCH 04/54] Docs: adding missing `mutable-override` to section title (#16886) Closes https://github.com/python/mypy/issues/16880 Supercedes https://github.com/python/mypy/pull/16881 --- docs/source/error_code_list2.rst | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/source/error_code_list2.rst b/docs/source/error_code_list2.rst index 60f870c57db9..c966fe1f7ea6 100644 --- a/docs/source/error_code_list2.rst +++ b/docs/source/error_code_list2.rst @@ -484,11 +484,11 @@ Example: .. _code-mutable-override: -Check that overrides of mutable attributes are safe ---------------------------------------------------- +Check that overrides of mutable attributes are safe [mutable-override] +---------------------------------------------------------------------- -This will enable the check for unsafe overrides of mutable attributes. For -historical reasons, and because this is a relatively common pattern in Python, +`mutable-override` will enable the check for unsafe overrides of mutable attributes. +For historical reasons, and because this is a relatively common pattern in Python, this check is not enabled by default. The example below is unsafe, and will be flagged when this error code is enabled: From 780a29d0b1b93848d7ce3faf8e819a6cc140b2e5 Mon Sep 17 00:00:00 2001 From: Marc Mueller <30130371+cdce8p@users.noreply.github.com> Date: Wed, 7 Feb 2024 15:28:03 +0100 Subject: [PATCH 05/54] Bump version to 1.10.0+dev (#16888) The release branch has been cut: https://github.com/python/mypy/tree/release-1.9.0 Increase the dev version. --- mypy/version.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mypy/version.py b/mypy/version.py index 74e80839308c..93ab6463c573 100644 --- a/mypy/version.py +++ b/mypy/version.py @@ -8,7 +8,7 @@ # - Release versions have the form "1.2.3". # - Dev versions have the form "1.2.3+dev" (PLUS sign to conform to PEP 440). # - Before 1.0 we had the form "0.NNN". -__version__ = "1.9.0+dev" +__version__ = "1.10.0+dev" base_version = __version__ mypy_dir = os.path.abspath(os.path.dirname(os.path.dirname(__file__))) From 517f5aee23ba218f615bcd4427bca62f120bc222 Mon Sep 17 00:00:00 2001 From: Alex Waygood Date: Fri, 9 Feb 2024 13:27:33 +0000 Subject: [PATCH 06/54] Stubtest: ignore a new protocol dunder (#16895) This is added to all protocol classes on Python 3.12.2+ (it was added in a patch release of 3.12 as part of a bugfix). There's no reason why you'd want to explicitly include it in a stub (and doing so would lead the type checker to incorrectly conclude that you wanted a member literally called `__non_callable_proto_members__`) Cf. https://github.com/python/typeshed/pull/11384 and https://github.com/python/typeshed/issues/11383 --- mypy/stubtest.py | 1 + 1 file changed, 1 insertion(+) diff --git a/mypy/stubtest.py b/mypy/stubtest.py index 0e8a1c3ceac2..c2f82c98d089 100644 --- a/mypy/stubtest.py +++ b/mypy/stubtest.py @@ -1486,6 +1486,7 @@ def verify_typealias( # Added to all protocol classes on 3.12+ (or if using typing_extensions.Protocol) "__protocol_attrs__", "__callable_proto_members_only__", + "__non_callable_proto_members__", # typing implementation details, consider removing some of these: "__parameters__", "__origin__", From d8e3d591048cfe16dbc9cfa2ff88db38c587e3d0 Mon Sep 17 00:00:00 2001 From: jhance Date: Fri, 9 Feb 2024 18:28:10 -0800 Subject: [PATCH 07/54] Unsupport targetting 3.7. (#16883) This syncs up this constant to the actual minimum version that typeshed is now targetting. --------- Co-authored-by: Marc Mueller <30130371+cdce8p@users.noreply.github.com> --- mypy/defaults.py | 2 +- test-data/unit/cmdline.test | 12 ++++++------ 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/mypy/defaults.py b/mypy/defaults.py index 6a09a61a461e..2bbae23d7e2d 100644 --- a/mypy/defaults.py +++ b/mypy/defaults.py @@ -10,7 +10,7 @@ # Earliest Python 3.x version supported via --python-version 3.x. To run # mypy, at least version PYTHON3_VERSION is needed. -PYTHON3_VERSION_MIN: Final = (3, 7) # Keep in sync with typeshed's python support +PYTHON3_VERSION_MIN: Final = (3, 8) # Keep in sync with typeshed's python support CACHE_DIR: Final = ".mypy_cache" CONFIG_FILE: Final = ["mypy.ini", ".mypy.ini"] diff --git a/test-data/unit/cmdline.test b/test-data/unit/cmdline.test index f286f4781ed5..2262b7e7280c 100644 --- a/test-data/unit/cmdline.test +++ b/test-data/unit/cmdline.test @@ -592,7 +592,7 @@ main.py:1: error: Cannot find implementation or library stub for module named "a \[tool.mypy] python_version = 3.10 [out] -pyproject.toml: [mypy]: python_version: Python 3.1 is not supported (must be 3.7 or higher). You may need to put quotes around your Python version +pyproject.toml: [mypy]: python_version: Python 3.1 is not supported (must be 3.8 or higher). You may need to put quotes around your Python version == Return code: 0 [case testPythonVersionTooOld10] @@ -604,13 +604,13 @@ python_version = 1.0 mypy.ini: [mypy]: python_version: Python major version '1' out of range (must be 3) == Return code: 0 -[case testPythonVersionTooOld36] +[case testPythonVersionTooOld37] # cmd: mypy -c pass [file mypy.ini] \[mypy] -python_version = 3.6 +python_version = 3.7 [out] -mypy.ini: [mypy]: python_version: Python 3.6 is not supported (must be 3.7 or higher) +mypy.ini: [mypy]: python_version: Python 3.7 is not supported (must be 3.8 or higher) == Return code: 0 [case testPythonVersionTooNew40] @@ -633,11 +633,11 @@ usage: mypy [-h] [-v] [-V] [more options; see below] mypy: error: Mypy no longer supports checking Python 2 code. Consider pinning to mypy<0.980 if you need to check Python 2 code. == Return code: 2 -[case testPythonVersionAccepted37] +[case testPythonVersionAccepted38] # cmd: mypy -c pass [file mypy.ini] \[mypy] -python_version = 3.7 +python_version = 3.8 [out] [case testPythonVersionAccepted311] From 996544fe21aa21ee29d1ed5a178e2026edbe6bce Mon Sep 17 00:00:00 2001 From: Marc Mueller <30130371+cdce8p@users.noreply.github.com> Date: Sat, 10 Feb 2024 15:53:39 +0100 Subject: [PATCH 08/54] Update CI actions (#16901) Update `actions/setup-python` from `v4` to `v5` and `actions/github-script` from `v6` to `v7`. https://github.com/actions/setup-python/releases/tag/v5.0.0 https://github.com/actions/github-script/releases/tag/v7.0.0 --- .github/workflows/build_wheels.yml | 2 +- .github/workflows/docs.yml | 2 +- .github/workflows/mypy_primer.yml | 2 +- .github/workflows/mypy_primer_comment.yml | 2 +- .github/workflows/sync_typeshed.yml | 2 +- .github/workflows/test.yml | 2 +- .github/workflows/test_stubgenc.yml | 2 +- 7 files changed, 7 insertions(+), 7 deletions(-) diff --git a/.github/workflows/build_wheels.yml b/.github/workflows/build_wheels.yml index f1438279673d..8055cfd24180 100644 --- a/.github/workflows/build_wheels.yml +++ b/.github/workflows/build_wheels.yml @@ -14,7 +14,7 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - - uses: actions/setup-python@v4 + - uses: actions/setup-python@v5 with: python-version: '3.11' - name: Trigger script diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index ad6b57c53fd9..f13a3de1f2e3 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -34,7 +34,7 @@ jobs: VERIFY_MYPY_ERROR_CODES: 1 steps: - uses: actions/checkout@v4 - - uses: actions/setup-python@v4 + - uses: actions/setup-python@v5 with: python-version: '3.8' - name: Install tox diff --git a/.github/workflows/mypy_primer.yml b/.github/workflows/mypy_primer.yml index f8991e27970a..07a1d0863eb2 100644 --- a/.github/workflows/mypy_primer.yml +++ b/.github/workflows/mypy_primer.yml @@ -37,7 +37,7 @@ jobs: with: path: mypy_to_test fetch-depth: 0 - - uses: actions/setup-python@v4 + - uses: actions/setup-python@v5 with: python-version: "3.10" - name: Install dependencies diff --git a/.github/workflows/mypy_primer_comment.yml b/.github/workflows/mypy_primer_comment.yml index 6e3bb590364f..492e03aff16e 100644 --- a/.github/workflows/mypy_primer_comment.yml +++ b/.github/workflows/mypy_primer_comment.yml @@ -44,7 +44,7 @@ jobs: - name: Post comment id: post-comment - uses: actions/github-script@v6 + uses: actions/github-script@v7 with: github-token: ${{ secrets.GITHUB_TOKEN }} script: | diff --git a/.github/workflows/sync_typeshed.yml b/.github/workflows/sync_typeshed.yml index de9e0aad599f..b545e7b0662b 100644 --- a/.github/workflows/sync_typeshed.yml +++ b/.github/workflows/sync_typeshed.yml @@ -20,7 +20,7 @@ jobs: fetch-depth: 0 # TODO: use whatever solution ends up working for # https://github.com/python/typeshed/issues/8434 - - uses: actions/setup-python@v4 + - uses: actions/setup-python@v5 with: python-version: "3.10" - name: git config diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 4613605425c3..e4e44c671287 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -120,7 +120,7 @@ jobs: PYTEST_ADDOPTS: --color=yes steps: - uses: actions/checkout@v4 - - uses: actions/setup-python@v4 + - uses: actions/setup-python@v5 with: python-version: ${{ matrix.python }} architecture: ${{ matrix.arch }} diff --git a/.github/workflows/test_stubgenc.yml b/.github/workflows/test_stubgenc.yml index 7bdcfdb305bb..519f63ac2bd7 100644 --- a/.github/workflows/test_stubgenc.yml +++ b/.github/workflows/test_stubgenc.yml @@ -30,7 +30,7 @@ jobs: - uses: actions/checkout@v4 - name: Setup 🐍 3.8 - uses: actions/setup-python@v4 + uses: actions/setup-python@v5 with: python-version: 3.8 From 837f7e0ed4f87869f314ec102c0d6e47ec3272ec Mon Sep 17 00:00:00 2001 From: Sam Xifaras Date: Sun, 11 Feb 2024 04:04:28 -0500 Subject: [PATCH 09/54] stubtest: correct type annotations in _Arguments (#16897) Two fields in the `_Arguments` class, `mypy_config_file` and `custom_typeshed_dir`, can take on a None value, but they are not marked as such. Calling `stubtest.parse_options` on an empty list of arguments reproduces the situation where these two fields are None. --- mypy/stubtest.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/mypy/stubtest.py b/mypy/stubtest.py index c2f82c98d089..dd43c472d67f 100644 --- a/mypy/stubtest.py +++ b/mypy/stubtest.py @@ -1878,8 +1878,8 @@ class _Arguments: allowlist: list[str] generate_allowlist: bool ignore_unused_allowlist: bool - mypy_config_file: str - custom_typeshed_dir: str + mypy_config_file: str | None + custom_typeshed_dir: str | None check_typeshed: bool version: str @@ -1922,7 +1922,7 @@ def test_stubs(args: _Arguments, use_builtins_fixtures: bool = False) -> int: options.incremental = False options.custom_typeshed_dir = args.custom_typeshed_dir if options.custom_typeshed_dir: - options.abs_custom_typeshed_dir = os.path.abspath(args.custom_typeshed_dir) + options.abs_custom_typeshed_dir = os.path.abspath(options.custom_typeshed_dir) options.config_file = args.mypy_config_file options.use_builtins_fixtures = use_builtins_fixtures From 4a9c1e95457f253f87ef5db970ad8d59209c4715 Mon Sep 17 00:00:00 2001 From: Ali Hamdan Date: Sun, 11 Feb 2024 16:55:59 +0100 Subject: [PATCH 10/54] stubgen: Add support for PEP 570 positional-only parameters (#16904) This only adds support for Python modules (x-ref #14138) --- mypy/stubgen.py | 9 +++++++++ test-data/unit/stubgen.test | 22 ++++++++++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/mypy/stubgen.py b/mypy/stubgen.py index c314fabc882d..36e8bd2acfb4 100755 --- a/mypy/stubgen.py +++ b/mypy/stubgen.py @@ -110,6 +110,7 @@ Var, ) from mypy.options import Options as MypyOptions +from mypy.sharedparse import MAGIC_METHODS_POS_ARGS_ONLY from mypy.stubdoc import ArgSig, FunctionSig from mypy.stubgenc import InspectionStubGenerator, generate_stub_for_c_module from mypy.stubutil import ( @@ -480,6 +481,9 @@ def get_default_function_sig(self, func_def: FuncDef, ctx: FunctionContext) -> F def _get_func_args(self, o: FuncDef, ctx: FunctionContext) -> list[ArgSig]: args: list[ArgSig] = [] + # Ignore pos-only status of magic methods whose args names are elided by mypy at parse + actually_pos_only_args = o.name not in MAGIC_METHODS_POS_ARGS_ONLY + pos_only_marker_position = 0 # Where to insert "/", if any for i, arg_ in enumerate(o.arguments): var = arg_.variable kind = arg_.kind @@ -500,6 +504,9 @@ def _get_func_args(self, o: FuncDef, ctx: FunctionContext) -> list[ArgSig]: if not isinstance(get_proper_type(annotated_type), AnyType): typename = self.print_annotation(annotated_type) + if actually_pos_only_args and arg_.pos_only: + pos_only_marker_position += 1 + if kind.is_named() and not any(arg.name.startswith("*") for arg in args): args.append(ArgSig("*")) @@ -518,6 +525,8 @@ def _get_func_args(self, o: FuncDef, ctx: FunctionContext) -> list[ArgSig]: args.append( ArgSig(name, typename, default=bool(arg_.initializer), default_value=default) ) + if pos_only_marker_position: + args.insert(pos_only_marker_position, ArgSig("/")) if ctx.class_info is not None and all( arg.type is None and arg.default is False for arg in args diff --git a/test-data/unit/stubgen.test b/test-data/unit/stubgen.test index 3b3bc658a14a..b5bccaa4cdbd 100644 --- a/test-data/unit/stubgen.test +++ b/test-data/unit/stubgen.test @@ -4231,3 +4231,25 @@ o = int | None def f1(a: int | tuple[int, int | None] | None) -> int: ... def f2(a: int | x.Union[int, int] | float | None) -> int: ... + +[case testPEP570PosOnlyParams] +def f(x=0, /): ... +def f1(x: int, /): ... +def f2(x: int, y: float = 1, /): ... +def f3(x: int, /, y: float): ... +def f4(x: int, /, y: float = 1): ... +def f5(x: int, /, *, y: float): ... +def f6(x: int = 0, /, *, y: float): ... +def f7(x: int, /, *, y: float = 1): ... +def f8(x: int = 0, /, *, y: float = 1): ... + +[out] +def f(x: int = 0, /) -> None: ... +def f1(x: int, /): ... +def f2(x: int, y: float = 1, /): ... +def f3(x: int, /, y: float): ... +def f4(x: int, /, y: float = 1): ... +def f5(x: int, /, *, y: float): ... +def f6(x: int = 0, /, *, y: float): ... +def f7(x: int, /, *, y: float = 1): ... +def f8(x: int = 0, /, *, y: float = 1): ... From b6e91d46b299bfd0af36b37586d3337a20e14b0e Mon Sep 17 00:00:00 2001 From: Ali Hamdan Date: Sun, 11 Feb 2024 23:09:22 +0100 Subject: [PATCH 11/54] stubgen: Preserve empty tuple annotation (#16907) --- mypy/stubutil.py | 2 ++ test-data/unit/stubgen.test | 14 ++++++++++++++ 2 files changed, 16 insertions(+) diff --git a/mypy/stubutil.py b/mypy/stubutil.py index 1a9c2357c58e..69af643efab2 100644 --- a/mypy/stubutil.py +++ b/mypy/stubutil.py @@ -250,6 +250,8 @@ def visit_unbound_type(self, t: UnboundType) -> str: self.stubgen.import_tracker.require_name(s) if t.args: s += f"[{self.args_str(t.args)}]" + elif t.empty_tuple_index: + s += "[()]" return s def visit_none_type(self, t: NoneType) -> str: diff --git a/test-data/unit/stubgen.test b/test-data/unit/stubgen.test index b5bccaa4cdbd..c56f6b40b74d 100644 --- a/test-data/unit/stubgen.test +++ b/test-data/unit/stubgen.test @@ -4253,3 +4253,17 @@ def f5(x: int, /, *, y: float): ... def f6(x: int = 0, /, *, y: float): ... def f7(x: int, /, *, y: float = 1): ... def f8(x: int = 0, /, *, y: float = 1): ... + +[case testPreserveEmptyTuple] +ann: tuple[()] +alias = tuple[()] +def f(x: tuple[()]): ... +class C(tuple[()]): ... + +[out] +ann: tuple[()] +alias = tuple[()] + +def f(x: tuple[()]): ... + +class C(tuple[()]): ... From c26f1297d4f19d2d1124a30efc97caebb8c28616 Mon Sep 17 00:00:00 2001 From: Spencer Brown Date: Tue, 13 Feb 2024 00:19:09 +1000 Subject: [PATCH 12/54] Allow inferring +int to be a Literal (#16910) This makes unary positive on integers preserve the literal value of the integer, allowing `var: Literal[1] = +1` to be accepted. Basically I looked for code handling `__neg__` and added a branch for `__pos__` as well. Fixes #16728. --- mypy/checkexpr.py | 4 ++++ mypy/exprtotype.py | 9 ++++++--- mypy/plugins/default.py | 25 +++++++++++++++++++------ test-data/unit/check-literal.test | 13 ++++++++++++- test-data/unit/check-tuples.test | 4 +++- test-data/unit/fixtures/tuple.pyi | 1 + 6 files changed, 45 insertions(+), 11 deletions(-) diff --git a/mypy/checkexpr.py b/mypy/checkexpr.py index ff7b7fa2ff58..2842606b7b18 100644 --- a/mypy/checkexpr.py +++ b/mypy/checkexpr.py @@ -4437,6 +4437,10 @@ def try_getting_int_literals(self, index: Expression) -> list[int] | None: operand = index.expr if isinstance(operand, IntExpr): return [-1 * operand.value] + if index.op == "+": + operand = index.expr + if isinstance(operand, IntExpr): + return [operand.value] typ = get_proper_type(self.accept(index)) if isinstance(typ, Instance) and typ.last_known_value is not None: typ = typ.last_known_value diff --git a/mypy/exprtotype.py b/mypy/exprtotype.py index 7a50429b81d1..2218a950788c 100644 --- a/mypy/exprtotype.py +++ b/mypy/exprtotype.py @@ -183,9 +183,12 @@ def expr_to_unanalyzed_type( elif isinstance(expr, UnaryExpr): typ = expr_to_unanalyzed_type(expr.expr, options, allow_new_syntax) if isinstance(typ, RawExpressionType): - if isinstance(typ.literal_value, int) and expr.op == "-": - typ.literal_value *= -1 - return typ + if isinstance(typ.literal_value, int): + if expr.op == "-": + typ.literal_value *= -1 + return typ + elif expr.op == "+": + return typ raise TypeTranslationError() elif isinstance(expr, IntExpr): return RawExpressionType(expr.value, "builtins.int", line=expr.line, column=expr.column) diff --git a/mypy/plugins/default.py b/mypy/plugins/default.py index ddcc37f465fe..93fff5320cd5 100644 --- a/mypy/plugins/default.py +++ b/mypy/plugins/default.py @@ -100,6 +100,8 @@ def get_method_hook(self, fullname: str) -> Callable[[MethodContext], Type] | No return int_pow_callback elif fullname == "builtins.int.__neg__": return int_neg_callback + elif fullname == "builtins.int.__pos__": + return int_pos_callback elif fullname in ("builtins.tuple.__mul__", "builtins.tuple.__rmul__"): return tuple_mul_callback elif fullname in {n + ".setdefault" for n in TPDICT_FB_NAMES}: @@ -471,32 +473,43 @@ def int_pow_callback(ctx: MethodContext) -> Type: return ctx.default_return_type -def int_neg_callback(ctx: MethodContext) -> Type: - """Infer a more precise return type for int.__neg__. +def int_neg_callback(ctx: MethodContext, multiplier: int = -1) -> Type: + """Infer a more precise return type for int.__neg__ and int.__pos__. This is mainly used to infer the return type as LiteralType - if the original underlying object is a LiteralType object + if the original underlying object is a LiteralType object. """ if isinstance(ctx.type, Instance) and ctx.type.last_known_value is not None: value = ctx.type.last_known_value.value fallback = ctx.type.last_known_value.fallback if isinstance(value, int): if is_literal_type_like(ctx.api.type_context[-1]): - return LiteralType(value=-value, fallback=fallback) + return LiteralType(value=multiplier * value, fallback=fallback) else: return ctx.type.copy_modified( last_known_value=LiteralType( - value=-value, fallback=ctx.type, line=ctx.type.line, column=ctx.type.column + value=multiplier * value, + fallback=ctx.type, + line=ctx.type.line, + column=ctx.type.column, ) ) elif isinstance(ctx.type, LiteralType): value = ctx.type.value fallback = ctx.type.fallback if isinstance(value, int): - return LiteralType(value=-value, fallback=fallback) + return LiteralType(value=multiplier * value, fallback=fallback) return ctx.default_return_type +def int_pos_callback(ctx: MethodContext) -> Type: + """Infer a more precise return type for int.__pos__. + + This is identical to __neg__, except the value is not inverted. + """ + return int_neg_callback(ctx, +1) + + def tuple_mul_callback(ctx: MethodContext) -> Type: """Infer a more precise return type for tuple.__mul__ and tuple.__rmul__. diff --git a/test-data/unit/check-literal.test b/test-data/unit/check-literal.test index de4440ce7f49..5604cc4b5893 100644 --- a/test-data/unit/check-literal.test +++ b/test-data/unit/check-literal.test @@ -397,29 +397,36 @@ from typing_extensions import Literal a1: Literal[4] b1: Literal[0x2a] c1: Literal[-300] +d1: Literal[+8] reveal_type(a1) # N: Revealed type is "Literal[4]" reveal_type(b1) # N: Revealed type is "Literal[42]" reveal_type(c1) # N: Revealed type is "Literal[-300]" +reveal_type(d1) # N: Revealed type is "Literal[8]" a2t = Literal[4] b2t = Literal[0x2a] c2t = Literal[-300] +d2t = Literal[+8] a2: a2t b2: b2t c2: c2t +d2: d2t reveal_type(a2) # N: Revealed type is "Literal[4]" reveal_type(b2) # N: Revealed type is "Literal[42]" reveal_type(c2) # N: Revealed type is "Literal[-300]" +reveal_type(d2) # N: Revealed type is "Literal[8]" def f1(x: Literal[4]) -> Literal[4]: pass def f2(x: Literal[0x2a]) -> Literal[0x2a]: pass def f3(x: Literal[-300]) -> Literal[-300]: pass +def f4(x: Literal[+8]) -> Literal[+8]: pass reveal_type(f1) # N: Revealed type is "def (x: Literal[4]) -> Literal[4]" reveal_type(f2) # N: Revealed type is "def (x: Literal[42]) -> Literal[42]" reveal_type(f3) # N: Revealed type is "def (x: Literal[-300]) -> Literal[-300]" +reveal_type(f4) # N: Revealed type is "def (x: Literal[8]) -> Literal[8]" [builtins fixtures/tuple.pyi] [out] @@ -2747,6 +2754,9 @@ d: Literal[1] = 1 e: Literal[2] = 2 f: Literal[+1] = 1 g: Literal[+2] = 2 +h: Literal[1] = +1 +i: Literal[+2] = 2 +j: Literal[+3] = +3 x: Literal[+True] = True # E: Invalid type: Literal[...] cannot contain arbitrary expressions y: Literal[-True] = -1 # E: Invalid type: Literal[...] cannot contain arbitrary expressions @@ -2759,6 +2769,7 @@ from typing_extensions import Literal, Final ONE: Final = 1 x: Literal[-1] = -ONE +y: Literal[+1] = +ONE TWO: Final = 2 THREE: Final = 3 @@ -2766,7 +2777,7 @@ THREE: Final = 3 err_code = -TWO if bool(): err_code = -THREE -[builtins fixtures/float.pyi] +[builtins fixtures/ops.pyi] [case testAliasForEnumTypeAsLiteral] from typing_extensions import Literal diff --git a/test-data/unit/check-tuples.test b/test-data/unit/check-tuples.test index 66115ca0c30d..ad4893c2890a 100644 --- a/test-data/unit/check-tuples.test +++ b/test-data/unit/check-tuples.test @@ -337,10 +337,12 @@ if int(): b = t1[-1] if int(): a = t1[(0)] +if int(): + b = t1[+1] if int(): x = t3[0:3] # type (A, B, C) if int(): - y = t3[0:5:2] # type (A, C, E) + y = t3[0:+5:2] # type (A, C, E) if int(): x = t3[:-2] # type (A, B, C) diff --git a/test-data/unit/fixtures/tuple.pyi b/test-data/unit/fixtures/tuple.pyi index cb6347e9f2fd..eb89de8c86ef 100644 --- a/test-data/unit/fixtures/tuple.pyi +++ b/test-data/unit/fixtures/tuple.pyi @@ -32,6 +32,7 @@ class classmethod: pass # We need int and slice for indexing tuples. class int: def __neg__(self) -> 'int': pass + def __pos__(self) -> 'int': pass class float: pass class slice: pass class bool(int): pass From 5ffa6dde6e295c7cd1bc237dcc252672a39c625e Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Wed, 14 Feb 2024 22:09:41 -0800 Subject: [PATCH 13/54] Sync typeshed (#16918) Source commit: https://github.com/python/typeshed/commit/48a0497b2310e8e4bcb81c72aed7517b2a3a3bfd --- mypy/typeshed/stdlib/_ast.pyi | 6 +- mypy/typeshed/stdlib/_curses.pyi | 1 + mypy/typeshed/stdlib/_msi.pyi | 1 + mypy/typeshed/stdlib/_thread.pyi | 1 + mypy/typeshed/stdlib/asyncio/sslproto.pyi | 4 +- mypy/typeshed/stdlib/asyncio/unix_events.pyi | 3 + .../stdlib/asyncio/windows_events.pyi | 2 + mypy/typeshed/stdlib/calendar.pyi | 4 +- mypy/typeshed/stdlib/contextlib.pyi | 1 + mypy/typeshed/stdlib/dbm/gnu.pyi | 1 + mypy/typeshed/stdlib/dbm/ndbm.pyi | 1 + mypy/typeshed/stdlib/enum.pyi | 3 + mypy/typeshed/stdlib/ftplib.pyi | 12 +- mypy/typeshed/stdlib/grp.pyi | 1 + .../stdlib/importlib/metadata/__init__.pyi | 1 + mypy/typeshed/stdlib/inspect.pyi | 1 + mypy/typeshed/stdlib/io.pyi | 42 +- mypy/typeshed/stdlib/msilib/__init__.pyi | 1 + .../stdlib/multiprocessing/reduction.pyi | 1 + mypy/typeshed/stdlib/os/__init__.pyi | 7 + mypy/typeshed/stdlib/pstats.pyi | 1 + mypy/typeshed/stdlib/pwd.pyi | 1 + mypy/typeshed/stdlib/pyexpat/__init__.pyi | 9 +- mypy/typeshed/stdlib/resource.pyi | 2 + mypy/typeshed/stdlib/select.pyi | 3 + mypy/typeshed/stdlib/signal.pyi | 3 + mypy/typeshed/stdlib/spwd.pyi | 1 + mypy/typeshed/stdlib/string.pyi | 2 +- mypy/typeshed/stdlib/subprocess.pyi | 9 +- mypy/typeshed/stdlib/sys/__init__.pyi | 2 + mypy/typeshed/stdlib/time.pyi | 1 + mypy/typeshed/stdlib/tkinter/__init__.pyi | 707 +++++++++--------- mypy/typeshed/stdlib/tkinter/ttk.pyi | 357 ++++----- mypy/typeshed/stdlib/typing.pyi | 3 + mypy/typeshed/stdlib/unicodedata.pyi | 10 +- mypy/typeshed/stdlib/unittest/result.pyi | 1 + 36 files changed, 653 insertions(+), 553 deletions(-) diff --git a/mypy/typeshed/stdlib/_ast.pyi b/mypy/typeshed/stdlib/_ast.pyi index fc3f035cc779..0758450dfa7c 100644 --- a/mypy/typeshed/stdlib/_ast.pyi +++ b/mypy/typeshed/stdlib/_ast.pyi @@ -6,6 +6,10 @@ PyCF_ONLY_AST: Literal[1024] PyCF_TYPE_COMMENTS: Literal[4096] PyCF_ALLOW_TOP_LEVEL_AWAIT: Literal[8192] +# Alias used for fields that must always be valid identifiers +# A string `x` counts as a valid identifier if both the following are True +# (1) `x.isidentifier()` evaluates to `True` +# (2) `keyword.iskeyword(x)` evaluates to `False` _Identifier: typing_extensions.TypeAlias = str class AST: @@ -499,7 +503,7 @@ class keyword(AST): class alias(AST): if sys.version_info >= (3, 10): __match_args__ = ("name", "asname") - name: _Identifier + name: str asname: _Identifier | None class withitem(AST): diff --git a/mypy/typeshed/stdlib/_curses.pyi b/mypy/typeshed/stdlib/_curses.pyi index adb09a50f47c..20189cb285c5 100644 --- a/mypy/typeshed/stdlib/_curses.pyi +++ b/mypy/typeshed/stdlib/_curses.pyi @@ -553,5 +553,6 @@ if sys.platform != "win32": major: int minor: int patch: int + ncurses_version: _ncurses_version window = _CursesWindow # undocumented diff --git a/mypy/typeshed/stdlib/_msi.pyi b/mypy/typeshed/stdlib/_msi.pyi index 160406a6d8d5..22239cbfff04 100644 --- a/mypy/typeshed/stdlib/_msi.pyi +++ b/mypy/typeshed/stdlib/_msi.pyi @@ -45,6 +45,7 @@ if sys.platform == "win32": # Don't exist at runtime __new__: None # type: ignore[assignment] __init__: None # type: ignore[assignment] + def UuidCreate() -> str: ... def FCICreate(__cabname: str, __files: list[str]) -> None: ... def OpenDatabase(__path: str, __persist: int) -> _Database: ... diff --git a/mypy/typeshed/stdlib/_thread.pyi b/mypy/typeshed/stdlib/_thread.pyi index 8b43a81cac8a..ff9bd1a12eb1 100644 --- a/mypy/typeshed/stdlib/_thread.pyi +++ b/mypy/typeshed/stdlib/_thread.pyi @@ -32,6 +32,7 @@ def get_native_id() -> int: ... # only available on some platforms class _ExceptHookArgs(structseq[Any], tuple[type[BaseException], BaseException | None, TracebackType | None, Thread | None]): if sys.version_info >= (3, 10): __match_args__: Final = ("exc_type", "exc_value", "exc_traceback", "thread") + @property def exc_type(self) -> type[BaseException]: ... @property diff --git a/mypy/typeshed/stdlib/asyncio/sslproto.pyi b/mypy/typeshed/stdlib/asyncio/sslproto.pyi index 5dcca950e819..04197c8d2978 100644 --- a/mypy/typeshed/stdlib/asyncio/sslproto.pyi +++ b/mypy/typeshed/stdlib/asyncio/sslproto.pyi @@ -25,6 +25,7 @@ if sys.version_info >= (3, 11): STATE_CON_MADE: str STATE_EOF: str STATE_CON_LOST: str + def add_flowcontrol_defaults(high: int | None, low: int | None, kb: int) -> tuple[int, int]: ... else: @@ -155,9 +156,10 @@ class SSLProtocol(_SSLProtocolBase): def _check_handshake_timeout(self) -> None: ... def _on_handshake_complete(self, handshake_exc: BaseException | None) -> None: ... def _fatal_error(self, exc: BaseException, message: str = "Fatal error on transport") -> None: ... - def _abort(self) -> None: ... if sys.version_info >= (3, 11): + def _abort(self, exc: BaseException | None) -> None: ... def get_buffer(self, n: int) -> memoryview: ... else: + def _abort(self) -> None: ... def _finalize(self) -> None: ... def _process_write_backlog(self) -> None: ... diff --git a/mypy/typeshed/stdlib/asyncio/unix_events.pyi b/mypy/typeshed/stdlib/asyncio/unix_events.pyi index d2a2fef5c33b..2fbc0a4e6049 100644 --- a/mypy/typeshed/stdlib/asyncio/unix_events.pyi +++ b/mypy/typeshed/stdlib/asyncio/unix_events.pyi @@ -96,6 +96,7 @@ if sys.platform != "win32": def __exit__(self, a: type[BaseException] | None, b: BaseException | None, c: types.TracebackType | None) -> None: ... def add_child_handler(self, pid: int, callback: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts]) -> None: ... def remove_child_handler(self, pid: int) -> bool: ... + else: class SafeChildWatcher(BaseChildWatcher): def __enter__(self) -> Self: ... @@ -120,6 +121,7 @@ if sys.platform != "win32": else: def get_child_watcher(self) -> AbstractChildWatcher: ... def set_child_watcher(self, watcher: AbstractChildWatcher | None) -> None: ... + SelectorEventLoop = _UnixSelectorEventLoop DefaultEventLoopPolicy = _UnixDefaultEventLoopPolicy @@ -136,6 +138,7 @@ if sys.platform != "win32": def add_child_handler(self, pid: int, callback: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts]) -> None: ... def remove_child_handler(self, pid: int) -> bool: ... def attach_loop(self, loop: AbstractEventLoop | None) -> None: ... + else: class MultiLoopChildWatcher(AbstractChildWatcher): def is_active(self) -> bool: ... diff --git a/mypy/typeshed/stdlib/asyncio/windows_events.pyi b/mypy/typeshed/stdlib/asyncio/windows_events.pyi index fdf43d3ea91c..9c150ee16beb 100644 --- a/mypy/typeshed/stdlib/asyncio/windows_events.pyi +++ b/mypy/typeshed/stdlib/asyncio/windows_events.pyi @@ -69,6 +69,7 @@ if sys.platform == "win32": def recvfrom_into( self, conn: socket.socket, buf: WriteableBuffer, flags: int = 0 ) -> futures.Future[tuple[int, socket._RetAddress]]: ... + SelectorEventLoop = _WindowsSelectorEventLoop class WindowsSelectorEventLoopPolicy(events.BaseDefaultEventLoopPolicy): @@ -80,4 +81,5 @@ if sys.platform == "win32": _loop_factory: ClassVar[type[ProactorEventLoop]] def get_child_watcher(self) -> NoReturn: ... def set_child_watcher(self, watcher: Any) -> NoReturn: ... + DefaultEventLoopPolicy = WindowsSelectorEventLoopPolicy diff --git a/mypy/typeshed/stdlib/calendar.pyi b/mypy/typeshed/stdlib/calendar.pyi index cac39a498ac9..5cc49e102fdf 100644 --- a/mypy/typeshed/stdlib/calendar.pyi +++ b/mypy/typeshed/stdlib/calendar.pyi @@ -124,7 +124,7 @@ class HTMLCalendar(Calendar): def formatyear(self, theyear: int, width: int = 3) -> str: ... def formatyearpage( self, theyear: int, width: int = 3, css: str | None = "calendar.css", encoding: str | None = None - ) -> str: ... + ) -> bytes: ... class different_locale: def __init__(self, locale: _LocaleType) -> None: ... @@ -166,6 +166,7 @@ if sys.version_info >= (3, 12): OCTOBER: Literal[10] NOVEMBER: Literal[11] DECEMBER: Literal[12] + JANUARY = Month.JANUARY FEBRUARY = Month.FEBRUARY MARCH = Month.MARCH @@ -187,6 +188,7 @@ if sys.version_info >= (3, 12): FRIDAY: Literal[4] SATURDAY: Literal[5] SUNDAY: Literal[6] + MONDAY = Day.MONDAY TUESDAY = Day.TUESDAY WEDNESDAY = Day.WEDNESDAY diff --git a/mypy/typeshed/stdlib/contextlib.pyi b/mypy/typeshed/stdlib/contextlib.pyi index ce46d0d39830..eb4e95b33509 100644 --- a/mypy/typeshed/stdlib/contextlib.pyi +++ b/mypy/typeshed/stdlib/contextlib.pyi @@ -118,6 +118,7 @@ class closing(AbstractContextManager[_SupportsCloseT]): if sys.version_info >= (3, 10): class _SupportsAclose(Protocol): def aclose(self) -> Awaitable[object]: ... + _SupportsAcloseT = TypeVar("_SupportsAcloseT", bound=_SupportsAclose) class aclosing(AbstractAsyncContextManager[_SupportsAcloseT]): diff --git a/mypy/typeshed/stdlib/dbm/gnu.pyi b/mypy/typeshed/stdlib/dbm/gnu.pyi index 3dc66a30c370..0f818ed5e7f5 100644 --- a/mypy/typeshed/stdlib/dbm/gnu.pyi +++ b/mypy/typeshed/stdlib/dbm/gnu.pyi @@ -37,4 +37,5 @@ if sys.platform != "win32": # Don't exist at runtime __new__: None # type: ignore[assignment] __init__: None # type: ignore[assignment] + def open(__filename: str, __flags: str = "r", __mode: int = 0o666) -> _gdbm: ... diff --git a/mypy/typeshed/stdlib/dbm/ndbm.pyi b/mypy/typeshed/stdlib/dbm/ndbm.pyi index 1106fb2a8e7e..a7a6d52d8f19 100644 --- a/mypy/typeshed/stdlib/dbm/ndbm.pyi +++ b/mypy/typeshed/stdlib/dbm/ndbm.pyi @@ -33,4 +33,5 @@ if sys.platform != "win32": # Don't exist at runtime __new__: None # type: ignore[assignment] __init__: None # type: ignore[assignment] + def open(__filename: str, __flags: str = "r", __mode: int = 0o666) -> _dbm: ... diff --git a/mypy/typeshed/stdlib/enum.pyi b/mypy/typeshed/stdlib/enum.pyi index 42d0c19d39e7..96cb2264ea20 100644 --- a/mypy/typeshed/stdlib/enum.pyi +++ b/mypy/typeshed/stdlib/enum.pyi @@ -175,6 +175,7 @@ if sys.version_info >= (3, 11): name: str clsname: str member: Enum | None + _magic_enum_attr = property else: _magic_enum_attr = types.DynamicClassAttribute @@ -261,6 +262,7 @@ if sys.version_info >= (3, 11): CONTINUOUS: str NAMED_FLAGS: str UNIQUE: str + CONTINUOUS = EnumCheck.CONTINUOUS NAMED_FLAGS = EnumCheck.NAMED_FLAGS UNIQUE = EnumCheck.UNIQUE @@ -274,6 +276,7 @@ if sys.version_info >= (3, 11): CONFORM: str EJECT: str KEEP: str + STRICT = FlagBoundary.STRICT CONFORM = FlagBoundary.CONFORM EJECT = FlagBoundary.EJECT diff --git a/mypy/typeshed/stdlib/ftplib.pyi b/mypy/typeshed/stdlib/ftplib.pyi index 3bc03a0ff121..9e7097ddc56e 100644 --- a/mypy/typeshed/stdlib/ftplib.pyi +++ b/mypy/typeshed/stdlib/ftplib.pyi @@ -31,7 +31,7 @@ class FTP: sock: socket | None welcome: str | None passiveserver: int - timeout: int + timeout: float | None af: int lastresp: str file: TextIO | None @@ -48,7 +48,7 @@ class FTP: user: str = "", passwd: str = "", acct: str = "", - timeout: float = ..., + timeout: float | None = ..., source_address: tuple[str, int] | None = None, *, encoding: str = "utf-8", @@ -60,7 +60,7 @@ class FTP: user: str = "", passwd: str = "", acct: str = "", - timeout: float = ..., + timeout: float | None = ..., source_address: tuple[str, int] | None = None, ) -> None: ... @@ -127,7 +127,7 @@ class FTP_TLS(FTP): acct: str = "", *, context: SSLContext | None = None, - timeout: float = ..., + timeout: float | None = ..., source_address: tuple[str, int] | None = None, encoding: str = "utf-8", ) -> None: ... @@ -141,7 +141,7 @@ class FTP_TLS(FTP): keyfile: str | None = None, certfile: str | None = None, context: SSLContext | None = None, - timeout: float = ..., + timeout: float | None = ..., source_address: tuple[str, int] | None = None, *, encoding: str = "utf-8", @@ -156,7 +156,7 @@ class FTP_TLS(FTP): keyfile: str | None = None, certfile: str | None = None, context: SSLContext | None = None, - timeout: float = ..., + timeout: float | None = ..., source_address: tuple[str, int] | None = None, ) -> None: ... ssl_version: int diff --git a/mypy/typeshed/stdlib/grp.pyi b/mypy/typeshed/stdlib/grp.pyi index bb0d65180918..965ecece2a56 100644 --- a/mypy/typeshed/stdlib/grp.pyi +++ b/mypy/typeshed/stdlib/grp.pyi @@ -7,6 +7,7 @@ if sys.platform != "win32": class struct_group(structseq[Any], tuple[str, str | None, int, list[str]]): if sys.version_info >= (3, 10): __match_args__: Final = ("gr_name", "gr_passwd", "gr_gid", "gr_mem") + @property def gr_name(self) -> str: ... @property diff --git a/mypy/typeshed/stdlib/importlib/metadata/__init__.pyi b/mypy/typeshed/stdlib/importlib/metadata/__init__.pyi index a936eece1d3f..eb4db39ebf40 100644 --- a/mypy/typeshed/stdlib/importlib/metadata/__init__.pyi +++ b/mypy/typeshed/stdlib/importlib/metadata/__init__.pyi @@ -43,6 +43,7 @@ class PackageNotFoundError(ModuleNotFoundError): if sys.version_info >= (3, 11): class DeprecatedTuple: def __getitem__(self, item: int) -> str: ... + _EntryPointBase = DeprecatedTuple else: class _EntryPointBase(NamedTuple): diff --git a/mypy/typeshed/stdlib/inspect.pyi b/mypy/typeshed/stdlib/inspect.pyi index a26dc67f9945..06a8ff6a3462 100644 --- a/mypy/typeshed/stdlib/inspect.pyi +++ b/mypy/typeshed/stdlib/inspect.pyi @@ -430,6 +430,7 @@ if sys.version_info < (3, 11): varargs: str | None keywords: str | None defaults: tuple[Any, ...] + def getargspec(func: object) -> ArgSpec: ... class FullArgSpec(NamedTuple): diff --git a/mypy/typeshed/stdlib/io.pyi b/mypy/typeshed/stdlib/io.pyi index d949971048b0..659b216c43dc 100644 --- a/mypy/typeshed/stdlib/io.pyi +++ b/mypy/typeshed/stdlib/io.pyi @@ -6,7 +6,7 @@ from _typeshed import FileDescriptorOrPath, ReadableBuffer, WriteableBuffer from collections.abc import Callable, Iterable, Iterator from os import _Opener from types import TracebackType -from typing import IO, Any, BinaryIO, Literal, TextIO, TypeVar, overload +from typing import IO, Any, BinaryIO, Literal, Protocol, TextIO, TypeVar, overload, type_check_only from typing_extensions import Self __all__ = [ @@ -94,7 +94,10 @@ class BufferedIOBase(IOBase): class FileIO(RawIOBase, BinaryIO): # type: ignore[misc] # incompatible definitions of writelines in the base classes mode: str - name: FileDescriptorOrPath + # The type of "name" equals the argument passed in to the constructor, + # but that can make FileIO incompatible with other I/O types that assume + # "name" is a str. In the future, making FileIO generic might help. + name: Any def __init__( self, file: FileDescriptorOrPath, mode: str = ..., closefd: bool = ..., opener: _Opener | None = ... ) -> None: ... @@ -146,16 +149,43 @@ class TextIOBase(IOBase): def readlines(self, __hint: int = -1) -> list[str]: ... # type: ignore[override] def read(self, __size: int | None = ...) -> str: ... +@type_check_only +class _WrappedBuffer(Protocol): + # "name" is wrapped by TextIOWrapper. Its type is inconsistent between + # the various I/O types, see the comments on TextIOWrapper.name and + # TextIO.name. + @property + def name(self) -> Any: ... + @property + def closed(self) -> bool: ... + def read(self, size: int = ..., /) -> ReadableBuffer: ... + # Optional: def read1(self, size: int, /) -> ReadableBuffer: ... + def write(self, b: bytes, /) -> object: ... + def flush(self) -> object: ... + def close(self) -> object: ... + def seekable(self) -> bool: ... + def readable(self) -> bool: ... + def writable(self) -> bool: ... + def truncate(self, size: int, /) -> int: ... + def fileno(self) -> int: ... + def isatty(self) -> int: ... + # Optional: Only needs to be present if seekable() returns True. + # def seek(self, offset: Literal[0], whence: Literal[2]) -> int: ... + # def tell(self) -> int: ... + +# TODO: Should be generic over the buffer type, but needs to wait for +# TypeVar defaults. class TextIOWrapper(TextIOBase, TextIO): # type: ignore[misc] # incompatible definitions of write in the base classes def __init__( self, - buffer: IO[bytes], + buffer: _WrappedBuffer, encoding: str | None = ..., errors: str | None = ..., newline: str | None = ..., line_buffering: bool = ..., write_through: bool = ..., ) -> None: ... + # Equals the "buffer" argument passed in to the constructor. @property def buffer(self) -> BinaryIO: ... @property @@ -180,7 +210,11 @@ class TextIOWrapper(TextIOBase, TextIO): # type: ignore[misc] # incompatible d def writelines(self, __lines: Iterable[str]) -> None: ... # type: ignore[override] def readline(self, __size: int = -1) -> str: ... # type: ignore[override] def readlines(self, __hint: int = -1) -> list[str]: ... # type: ignore[override] - def seek(self, __cookie: int, __whence: int = 0) -> int: ... # stubtest needs this + # Equals the "buffer" argument passed in to the constructor. + def detach(self) -> BinaryIO: ... + # TextIOWrapper's version of seek only supports a limited subset of + # operations. + def seek(self, __cookie: int, __whence: int = 0) -> int: ... class StringIO(TextIOWrapper): def __init__(self, initial_value: str | None = ..., newline: str | None = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/msilib/__init__.pyi b/mypy/typeshed/stdlib/msilib/__init__.pyi index 106805dab931..3e43cbc44f52 100644 --- a/mypy/typeshed/stdlib/msilib/__init__.pyi +++ b/mypy/typeshed/stdlib/msilib/__init__.pyi @@ -56,6 +56,7 @@ if sys.platform == "win32": def gen_id(self, file: str) -> str: ... def append(self, full: str, file: str, logical: str) -> tuple[int, str]: ... def commit(self, db: _Database) -> None: ... + _directories: set[str] class Directory: diff --git a/mypy/typeshed/stdlib/multiprocessing/reduction.pyi b/mypy/typeshed/stdlib/multiprocessing/reduction.pyi index ad80169b463c..91532633e1b9 100644 --- a/mypy/typeshed/stdlib/multiprocessing/reduction.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/reduction.pyi @@ -86,4 +86,5 @@ class AbstractReducer(metaclass=ABCMeta): sendfds = _sendfds recvfds = _recvfds DupFd = _DupFd + def __init__(self, *args: Unused) -> None: ... diff --git a/mypy/typeshed/stdlib/os/__init__.pyi b/mypy/typeshed/stdlib/os/__init__.pyi index 3b277460d8f6..b57678635c07 100644 --- a/mypy/typeshed/stdlib/os/__init__.pyi +++ b/mypy/typeshed/stdlib/os/__init__.pyi @@ -341,6 +341,7 @@ class stat_result(structseq[float], tuple[int, int, int, int, int, int, int, flo # More items may be added at the end by some implementations. if sys.version_info >= (3, 10): __match_args__: Final = ("st_mode", "st_ino", "st_dev", "st_nlink", "st_uid", "st_gid", "st_size") + @property def st_mode(self) -> int: ... # protection bits, @property @@ -446,6 +447,7 @@ class statvfs_result(structseq[int], tuple[int, int, int, int, int, int, int, in "f_flag", "f_namemax", ) + @property def f_bsize(self) -> int: ... @property @@ -488,6 +490,7 @@ def umask(__mask: int) -> int: ... class uname_result(structseq[str], tuple[str, str, str, str, str]): if sys.version_info >= (3, 10): __match_args__: Final = ("sysname", "nodename", "release", "version", "machine") + @property def sysname(self) -> str: ... @property @@ -704,6 +707,7 @@ if sys.platform != "win32": class terminal_size(structseq[int], tuple[int, int]): if sys.version_info >= (3, 10): __match_args__: Final = ("columns", "lines") + @property def columns(self) -> int: ... @property @@ -925,6 +929,7 @@ def system(command: StrOrBytesPath) -> int: ... class times_result(structseq[float], tuple[float, float, float, float, float]): if sys.version_info >= (3, 10): __match_args__: Final = ("user", "system", "children_user", "children_system", "elapsed") + @property def user(self) -> float: ... @property @@ -962,6 +967,7 @@ else: class waitid_result(structseq[int], tuple[int, int, int, int, int]): if sys.version_info >= (3, 10): __match_args__: Final = ("si_pid", "si_uid", "si_signo", "si_status", "si_code") + @property def si_pid(self) -> int: ... @property @@ -1022,6 +1028,7 @@ if sys.platform != "win32": class sched_param(structseq[int], tuple[int]): if sys.version_info >= (3, 10): __match_args__: Final = ("sched_priority",) + def __new__(cls, sched_priority: int) -> Self: ... @property def sched_priority(self) -> int: ... diff --git a/mypy/typeshed/stdlib/pstats.pyi b/mypy/typeshed/stdlib/pstats.pyi index a6ffd54de005..86f88da9e712 100644 --- a/mypy/typeshed/stdlib/pstats.pyi +++ b/mypy/typeshed/stdlib/pstats.pyi @@ -36,6 +36,7 @@ if sys.version_info >= (3, 9): percall_cumtime: float file_name: str line_number: int + @dataclass(unsafe_hash=True) class StatsProfile: total_tt: float diff --git a/mypy/typeshed/stdlib/pwd.pyi b/mypy/typeshed/stdlib/pwd.pyi index 64e831bcecce..9a8e1036e550 100644 --- a/mypy/typeshed/stdlib/pwd.pyi +++ b/mypy/typeshed/stdlib/pwd.pyi @@ -7,6 +7,7 @@ if sys.platform != "win32": class struct_passwd(structseq[Any], tuple[str, str, int, int, str, str, str]): if sys.version_info >= (3, 10): __match_args__: Final = ("pw_name", "pw_passwd", "pw_uid", "pw_gid", "pw_gecos", "pw_dir", "pw_shell") + @property def pw_name(self) -> str: ... @property diff --git a/mypy/typeshed/stdlib/pyexpat/__init__.pyi b/mypy/typeshed/stdlib/pyexpat/__init__.pyi index 92d926ebd332..2188e458474c 100644 --- a/mypy/typeshed/stdlib/pyexpat/__init__.pyi +++ b/mypy/typeshed/stdlib/pyexpat/__init__.pyi @@ -52,9 +52,12 @@ class XMLParserType: EndDoctypeDeclHandler: Callable[[], Any] | None ElementDeclHandler: Callable[[str, _Model], Any] | None AttlistDeclHandler: Callable[[str, str, str, str | None, bool], Any] | None - StartElementHandler: Callable[[str, dict[str, str]], Any] | Callable[[str, list[str]], Any] | Callable[ - [str, dict[str, str], list[str]], Any - ] | None + StartElementHandler: ( + Callable[[str, dict[str, str]], Any] + | Callable[[str, list[str]], Any] + | Callable[[str, dict[str, str], list[str]], Any] + | None + ) EndElementHandler: Callable[[str], Any] | None ProcessingInstructionHandler: Callable[[str, str], Any] | None CharacterDataHandler: Callable[[str], Any] | None diff --git a/mypy/typeshed/stdlib/resource.pyi b/mypy/typeshed/stdlib/resource.pyi index 31c55111360a..f40e5ec1ea55 100644 --- a/mypy/typeshed/stdlib/resource.pyi +++ b/mypy/typeshed/stdlib/resource.pyi @@ -24,6 +24,7 @@ if sys.platform != "win32": RLIMIT_RTTIME: int RLIMIT_SIGPENDING: int RUSAGE_THREAD: int + @final class struct_rusage( structseq[float], tuple[float, float, int, int, int, int, int, int, int, int, int, int, int, int, int, int] @@ -47,6 +48,7 @@ if sys.platform != "win32": "ru_nvcsw", "ru_nivcsw", ) + @property def ru_utime(self) -> float: ... @property diff --git a/mypy/typeshed/stdlib/select.pyi b/mypy/typeshed/stdlib/select.pyi index f2cfc881c1da..afab88e18453 100644 --- a/mypy/typeshed/stdlib/select.pyi +++ b/mypy/typeshed/stdlib/select.pyi @@ -52,6 +52,7 @@ if sys.platform != "linux" and sys.platform != "win32": data: Any = ..., udata: Any = ..., ) -> None: ... + # BSD only @final class kqueue: @@ -64,6 +65,7 @@ if sys.platform != "linux" and sys.platform != "win32": def fileno(self) -> int: ... @classmethod def fromfd(cls, __fd: FileDescriptorLike) -> kqueue: ... + KQ_EV_ADD: int KQ_EV_CLEAR: int KQ_EV_DELETE: int @@ -123,6 +125,7 @@ if sys.platform == "linux": def poll(self, timeout: float | None = None, maxevents: int = -1) -> list[tuple[int, int]]: ... @classmethod def fromfd(cls, __fd: FileDescriptorLike) -> epoll: ... + EPOLLERR: int EPOLLEXCLUSIVE: int EPOLLET: int diff --git a/mypy/typeshed/stdlib/signal.pyi b/mypy/typeshed/stdlib/signal.pyi index 910424c01c31..544473df9932 100644 --- a/mypy/typeshed/stdlib/signal.pyi +++ b/mypy/typeshed/stdlib/signal.pyi @@ -126,6 +126,7 @@ else: SIG_BLOCK: int SIG_UNBLOCK: int SIG_SETMASK: int + SIG_BLOCK = Sigmasks.SIG_BLOCK SIG_UNBLOCK = Sigmasks.SIG_UNBLOCK SIG_SETMASK = Sigmasks.SIG_SETMASK @@ -153,10 +154,12 @@ else: SIGRTMIN: Signals if sys.version_info >= (3, 11): SIGSTKFLT: Signals + @final class struct_siginfo(structseq[int], tuple[int, int, int, int, int, int, int]): if sys.version_info >= (3, 10): __match_args__: Final = ("si_signo", "si_code", "si_errno", "si_pid", "si_uid", "si_status", "si_band") + @property def si_signo(self) -> int: ... @property diff --git a/mypy/typeshed/stdlib/spwd.pyi b/mypy/typeshed/stdlib/spwd.pyi index 93dfad3b38cc..d362a0b77573 100644 --- a/mypy/typeshed/stdlib/spwd.pyi +++ b/mypy/typeshed/stdlib/spwd.pyi @@ -17,6 +17,7 @@ if sys.platform != "win32": "sp_expire", "sp_flag", ) + @property def sp_namp(self) -> str: ... @property diff --git a/mypy/typeshed/stdlib/string.pyi b/mypy/typeshed/stdlib/string.pyi index 1a875a071bf5..8b60243f2333 100644 --- a/mypy/typeshed/stdlib/string.pyi +++ b/mypy/typeshed/stdlib/string.pyi @@ -80,4 +80,4 @@ class Formatter: def get_value(self, key: int | str, args: Sequence[Any], kwargs: Mapping[str, Any]) -> Any: ... def check_unused_args(self, used_args: set[int | str], args: Sequence[Any], kwargs: Mapping[str, Any]) -> None: ... def format_field(self, value: Any, format_spec: str) -> Any: ... - def convert_field(self, value: Any, conversion: str) -> Any: ... + def convert_field(self, value: Any, conversion: str | None) -> Any: ... diff --git a/mypy/typeshed/stdlib/subprocess.pyi b/mypy/typeshed/stdlib/subprocess.pyi index df1db5c82eea..d3302aba5e10 100644 --- a/mypy/typeshed/stdlib/subprocess.pyi +++ b/mypy/typeshed/stdlib/subprocess.pyi @@ -2564,12 +2564,12 @@ class Popen(Generic[AnyStr]): # The result really is always a str. if sys.version_info >= (3, 11): - def getstatusoutput(cmd: str | bytes, *, encoding: str | None = None, errors: str | None = None) -> tuple[int, str]: ... - def getoutput(cmd: str | bytes, *, encoding: str | None = None, errors: str | None = None) -> str: ... + def getstatusoutput(cmd: _CMD, *, encoding: str | None = None, errors: str | None = None) -> tuple[int, str]: ... + def getoutput(cmd: _CMD, *, encoding: str | None = None, errors: str | None = None) -> str: ... else: - def getstatusoutput(cmd: str | bytes) -> tuple[int, str]: ... - def getoutput(cmd: str | bytes) -> str: ... + def getstatusoutput(cmd: _CMD) -> tuple[int, str]: ... + def getoutput(cmd: _CMD) -> str: ... def list2cmdline(seq: Iterable[StrOrBytesPath]) -> str: ... # undocumented @@ -2592,6 +2592,7 @@ if sys.platform == "win32": wShowWindow: int lpAttributeList: Mapping[str, Any] def copy(self) -> STARTUPINFO: ... + from _winapi import ( ABOVE_NORMAL_PRIORITY_CLASS as ABOVE_NORMAL_PRIORITY_CLASS, BELOW_NORMAL_PRIORITY_CLASS as BELOW_NORMAL_PRIORITY_CLASS, diff --git a/mypy/typeshed/stdlib/sys/__init__.pyi b/mypy/typeshed/stdlib/sys/__init__.pyi index 2f847498214b..bb1d244bdac9 100644 --- a/mypy/typeshed/stdlib/sys/__init__.pyi +++ b/mypy/typeshed/stdlib/sys/__init__.pyi @@ -42,6 +42,8 @@ hexversion: int last_type: type[BaseException] | None last_value: BaseException | None last_traceback: TracebackType | None +if sys.version_info >= (3, 12): + last_exc: BaseException # or undefined. maxsize: int maxunicode: int meta_path: list[_MetaPathFinder] diff --git a/mypy/typeshed/stdlib/time.pyi b/mypy/typeshed/stdlib/time.pyi index 28752bddc4dd..b7962f0751d6 100644 --- a/mypy/typeshed/stdlib/time.pyi +++ b/mypy/typeshed/stdlib/time.pyi @@ -39,6 +39,7 @@ if sys.version_info >= (3, 9) and sys.platform == "linux": class struct_time(structseq[Any | int], _TimeTuple): if sys.version_info >= (3, 10): __match_args__: Final = ("tm_year", "tm_mon", "tm_mday", "tm_hour", "tm_min", "tm_sec", "tm_wday", "tm_yday", "tm_isdst") + @property def tm_year(self) -> int: ... @property diff --git a/mypy/typeshed/stdlib/tkinter/__init__.pyi b/mypy/typeshed/stdlib/tkinter/__init__.pyi index ff876d0bb88c..4733c31b5bae 100644 --- a/mypy/typeshed/stdlib/tkinter/__init__.pyi +++ b/mypy/typeshed/stdlib/tkinter/__init__.pyi @@ -178,13 +178,12 @@ _Compound: TypeAlias = Literal["top", "left", "center", "right", "bottom", "none _Cursor: TypeAlias = str | tuple[str] | tuple[str, str] | tuple[str, str, str] | tuple[str, str, str, str] # example when it's sequence: entry['invalidcommand'] = [entry.register(print), '%P'] _EntryValidateCommand: TypeAlias = str | list[str] | tuple[str, ...] | Callable[[], bool] -_GridIndex: TypeAlias = int | str _ImageSpec: TypeAlias = _Image | str # str can be from e.g. tkinter.image_names() _Relief: TypeAlias = Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] # manual page: Tk_GetRelief _ScreenUnits: TypeAlias = str | float # Often the right type instead of int. Manual page: Tk_GetPixels # -xscrollcommand and -yscrollcommand in 'options' manual page _XYScrollCommand: TypeAlias = str | Callable[[float, float], object] -_TakeFocusValue: TypeAlias = int | Literal[""] | Callable[[str], bool | None] # -takefocus in manual page named 'options' +_TakeFocusValue: TypeAlias = bool | Literal[0, 1, ""] | Callable[[str], bool | None] # -takefocus in manual page named 'options' if sys.version_info >= (3, 11): class _VersionInfoType(NamedTuple): @@ -262,16 +261,14 @@ class Event(Generic[_W_co]): def NoDefaultRoot() -> None: ... -_TraceMode: TypeAlias = Literal["array", "read", "write", "unset"] - class Variable: def __init__(self, master: Misc | None = None, value: Incomplete | None = None, name: str | None = None) -> None: ... def set(self, value) -> None: ... initialize = set def get(self): ... - def trace_add(self, mode: _TraceMode, callback: Callable[[str, str, str], object]) -> str: ... - def trace_remove(self, mode: _TraceMode, cbname: str) -> None: ... - def trace_info(self) -> list[tuple[tuple[_TraceMode, ...], str]]: ... + def trace_add(self, mode: Literal["array", "read", "write", "unset"], callback: Callable[[str, str, str], object]) -> str: ... + def trace_remove(self, mode: Literal["array", "read", "write", "unset"], cbname: str) -> None: ... + def trace_info(self) -> list[tuple[tuple[Literal["array", "read", "write", "unset"], ...], str]]: ... @deprecated("use trace_add() instead of trace()") def trace(self, mode, callback): ... @deprecated("use trace_add() instead of trace_variable()") @@ -505,7 +502,7 @@ class Misc: bbox = grid_bbox def grid_columnconfigure( self, - index: _GridIndex | list[int] | tuple[int, ...], + index: int | str | list[int] | tuple[int, ...], cnf: _GridIndexInfo = {}, *, minsize: _ScreenUnits = ..., @@ -515,7 +512,7 @@ class Misc: ) -> _GridIndexInfo | Any: ... # can be None but annoying to check def grid_rowconfigure( self, - index: _GridIndex | list[int] | tuple[int, ...], + index: int | str | list[int] | tuple[int, ...], cnf: _GridIndexInfo = {}, *, minsize: _ScreenUnits = ..., @@ -829,7 +826,7 @@ class Pack: after: Misc = ..., anchor: _Anchor = ..., before: Misc = ..., - expand: int = ..., + expand: bool | Literal[0, 1] = 0, fill: Literal["none", "x", "y", "both"] = ..., side: Literal["left", "right", "top", "bottom"] = ..., ipadx: _ScreenUnits = ..., @@ -949,28 +946,28 @@ class Toplevel(BaseWidget, Wm): cnf: dict[str, Any] | None = {}, *, background: str = ..., - bd: _ScreenUnits = ..., + bd: _ScreenUnits = 0, bg: str = ..., - border: _ScreenUnits = ..., - borderwidth: _ScreenUnits = ..., - class_: str = ..., - colormap: Literal["new", ""] | Misc = ..., - container: bool = ..., - cursor: _Cursor = ..., - height: _ScreenUnits = ..., + border: _ScreenUnits = 0, + borderwidth: _ScreenUnits = 0, + class_: str = "Toplevel", + colormap: Literal["new", ""] | Misc = "", + container: bool = False, + cursor: _Cursor = "", + height: _ScreenUnits = 0, highlightbackground: str = ..., highlightcolor: str = ..., - highlightthickness: _ScreenUnits = ..., + highlightthickness: _ScreenUnits = 0, menu: Menu = ..., name: str = ..., - padx: _ScreenUnits = ..., - pady: _ScreenUnits = ..., - relief: _Relief = ..., - screen: str = ..., # can't be changed after creating widget - takefocus: _TakeFocusValue = ..., + padx: _ScreenUnits = 0, + pady: _ScreenUnits = 0, + relief: _Relief = "flat", + screen: str = "", # can't be changed after creating widget + takefocus: _TakeFocusValue = 0, use: int = ..., - visual: str | tuple[str, int] = ..., - width: _ScreenUnits = ..., + visual: str | tuple[str, int] = "", + width: _ScreenUnits = 0, ) -> None: ... @overload def configure( @@ -1006,46 +1003,46 @@ class Button(Widget): *, activebackground: str = ..., activeforeground: str = ..., - anchor: _Anchor = ..., + anchor: _Anchor = "center", background: str = ..., bd: _ScreenUnits = ..., # same as borderwidth bg: str = ..., # same as background - bitmap: str = ..., + bitmap: str = "", border: _ScreenUnits = ..., # same as borderwidth borderwidth: _ScreenUnits = ..., - command: _ButtonCommand = ..., - compound: _Compound = ..., - cursor: _Cursor = ..., - default: Literal["normal", "active", "disabled"] = ..., + command: _ButtonCommand = "", + compound: _Compound = "none", + cursor: _Cursor = "", + default: Literal["normal", "active", "disabled"] = "disabled", disabledforeground: str = ..., fg: str = ..., # same as foreground - font: _FontDescription = ..., + font: _FontDescription = "TkDefaultFont", foreground: str = ..., # width and height must be int for buttons containing just text, but # ints are also valid _ScreenUnits - height: _ScreenUnits = ..., + height: _ScreenUnits = 0, highlightbackground: str = ..., highlightcolor: str = ..., - highlightthickness: _ScreenUnits = ..., - image: _ImageSpec = ..., - justify: Literal["left", "center", "right"] = ..., + highlightthickness: _ScreenUnits = 1, + image: _ImageSpec = "", + justify: Literal["left", "center", "right"] = "center", name: str = ..., - overrelief: _Relief = ..., + overrelief: _Relief | Literal[""] = "", padx: _ScreenUnits = ..., pady: _ScreenUnits = ..., relief: _Relief = ..., repeatdelay: int = ..., repeatinterval: int = ..., - state: Literal["normal", "active", "disabled"] = ..., - takefocus: _TakeFocusValue = ..., - text: float | str = ..., + state: Literal["normal", "active", "disabled"] = "normal", + takefocus: _TakeFocusValue = "", + text: float | str = "", # We allow the textvariable to be any Variable, not necessarily # StringVar. This is useful for e.g. a button that displays the value # of an IntVar. textvariable: Variable = ..., - underline: int = ..., - width: _ScreenUnits = ..., - wraplength: _ScreenUnits = ..., + underline: int = -1, + width: _ScreenUnits = 0, + wraplength: _ScreenUnits = 0, ) -> None: ... @overload def configure( @@ -1075,7 +1072,7 @@ class Button(Widget): highlightthickness: _ScreenUnits = ..., image: _ImageSpec = ..., justify: Literal["left", "center", "right"] = ..., - overrelief: _Relief = ..., + overrelief: _Relief | Literal[""] = ..., padx: _ScreenUnits = ..., pady: _ScreenUnits = ..., relief: _Relief = ..., @@ -1102,13 +1099,13 @@ class Canvas(Widget, XView, YView): cnf: dict[str, Any] | None = {}, *, background: str = ..., - bd: _ScreenUnits = ..., + bd: _ScreenUnits = 0, bg: str = ..., - border: _ScreenUnits = ..., - borderwidth: _ScreenUnits = ..., - closeenough: float = ..., - confine: bool = ..., - cursor: _Cursor = ..., + border: _ScreenUnits = 0, + borderwidth: _ScreenUnits = 0, + closeenough: float = 1.0, + confine: bool = True, + cursor: _Cursor = "", # canvas manual page has a section named COORDINATES, and the first # part of it describes _ScreenUnits. height: _ScreenUnits = ..., @@ -1116,27 +1113,27 @@ class Canvas(Widget, XView, YView): highlightcolor: str = ..., highlightthickness: _ScreenUnits = ..., insertbackground: str = ..., - insertborderwidth: _ScreenUnits = ..., - insertofftime: int = ..., - insertontime: int = ..., - insertwidth: _ScreenUnits = ..., + insertborderwidth: _ScreenUnits = 0, + insertofftime: int = 300, + insertontime: int = 600, + insertwidth: _ScreenUnits = 2, name: str = ..., offset=..., # undocumented - relief: _Relief = ..., + relief: _Relief = "flat", # Setting scrollregion to None doesn't reset it back to empty, # but setting it to () does. - scrollregion: tuple[_ScreenUnits, _ScreenUnits, _ScreenUnits, _ScreenUnits] | tuple[()] = ..., + scrollregion: tuple[_ScreenUnits, _ScreenUnits, _ScreenUnits, _ScreenUnits] | tuple[()] = (), selectbackground: str = ..., - selectborderwidth: _ScreenUnits = ..., + selectborderwidth: _ScreenUnits = 1, selectforeground: str = ..., # man page says that state can be 'hidden', but it can't - state: Literal["normal", "disabled"] = ..., - takefocus: _TakeFocusValue = ..., + state: Literal["normal", "disabled"] = "normal", + takefocus: _TakeFocusValue = "", width: _ScreenUnits = ..., - xscrollcommand: _XYScrollCommand = ..., - xscrollincrement: _ScreenUnits = ..., - yscrollcommand: _XYScrollCommand = ..., - yscrollincrement: _ScreenUnits = ..., + xscrollcommand: _XYScrollCommand = "", + xscrollincrement: _ScreenUnits = 0, + yscrollcommand: _XYScrollCommand = "", + yscrollincrement: _ScreenUnits = 0, ) -> None: ... @overload def configure( @@ -1732,7 +1729,7 @@ class Canvas(Widget, XView, YView): def select_from(self, tagOrId, index) -> None: ... def select_item(self): ... def select_to(self, tagOrId, index) -> None: ... - def type(self, tagOrId): ... + def type(self, tagOrId: str | int) -> int | None: ... class Checkbutton(Widget): def __init__( @@ -1742,27 +1739,27 @@ class Checkbutton(Widget): *, activebackground: str = ..., activeforeground: str = ..., - anchor: _Anchor = ..., + anchor: _Anchor = "center", background: str = ..., bd: _ScreenUnits = ..., bg: str = ..., - bitmap: str = ..., + bitmap: str = "", border: _ScreenUnits = ..., borderwidth: _ScreenUnits = ..., - command: _ButtonCommand = ..., - compound: _Compound = ..., - cursor: _Cursor = ..., + command: _ButtonCommand = "", + compound: _Compound = "none", + cursor: _Cursor = "", disabledforeground: str = ..., fg: str = ..., - font: _FontDescription = ..., + font: _FontDescription = "TkDefaultFont", foreground: str = ..., - height: _ScreenUnits = ..., + height: _ScreenUnits = 0, highlightbackground: str = ..., highlightcolor: str = ..., - highlightthickness: _ScreenUnits = ..., - image: _ImageSpec = ..., - indicatoron: bool = ..., - justify: Literal["left", "center", "right"] = ..., + highlightthickness: _ScreenUnits = 1, + image: _ImageSpec = "", + indicatoron: bool = True, + justify: Literal["left", "center", "right"] = "center", name: str = ..., offrelief: _Relief = ..., # The checkbutton puts a value to its variable when it's checked or @@ -1775,24 +1772,24 @@ class Checkbutton(Widget): # and list[int] are incompatible. Also, we would need a way to # specify "Checkbutton not associated with any variable", which is # done by setting variable to empty string (the default). - offvalue: Any = ..., - onvalue: Any = ..., - overrelief: _Relief = ..., - padx: _ScreenUnits = ..., - pady: _ScreenUnits = ..., - relief: _Relief = ..., + offvalue: Any = 0, + onvalue: Any = 1, + overrelief: _Relief | Literal[""] = "", + padx: _ScreenUnits = 1, + pady: _ScreenUnits = 1, + relief: _Relief = "flat", selectcolor: str = ..., - selectimage: _ImageSpec = ..., - state: Literal["normal", "active", "disabled"] = ..., - takefocus: _TakeFocusValue = ..., - text: float | str = ..., + selectimage: _ImageSpec = "", + state: Literal["normal", "active", "disabled"] = "normal", + takefocus: _TakeFocusValue = "", + text: float | str = "", textvariable: Variable = ..., - tristateimage: _ImageSpec = ..., - tristatevalue: Any = ..., - underline: int = ..., + tristateimage: _ImageSpec = "", + tristatevalue: Any = "", + underline: int = -1, variable: Variable | Literal[""] = ..., - width: _ScreenUnits = ..., - wraplength: _ScreenUnits = ..., + width: _ScreenUnits = 0, + wraplength: _ScreenUnits = 0, ) -> None: ... @overload def configure( @@ -1825,7 +1822,7 @@ class Checkbutton(Widget): offrelief: _Relief = ..., offvalue: Any = ..., onvalue: Any = ..., - overrelief: _Relief = ..., + overrelief: _Relief | Literal[""] = ..., padx: _ScreenUnits = ..., pady: _ScreenUnits = ..., relief: _Relief = ..., @@ -1851,8 +1848,6 @@ class Checkbutton(Widget): def select(self) -> None: ... def toggle(self) -> None: ... -_EntryIndex: TypeAlias = str | int # "INDICES" in manual page - class Entry(Widget, XView): def __init__( self, @@ -1864,39 +1859,39 @@ class Entry(Widget, XView): bg: str = ..., border: _ScreenUnits = ..., borderwidth: _ScreenUnits = ..., - cursor: _Cursor = ..., + cursor: _Cursor = "xterm", disabledbackground: str = ..., disabledforeground: str = ..., - exportselection: bool = ..., + exportselection: bool = True, fg: str = ..., - font: _FontDescription = ..., + font: _FontDescription = "TkTextFont", foreground: str = ..., highlightbackground: str = ..., highlightcolor: str = ..., highlightthickness: _ScreenUnits = ..., insertbackground: str = ..., - insertborderwidth: _ScreenUnits = ..., - insertofftime: int = ..., - insertontime: int = ..., + insertborderwidth: _ScreenUnits = 0, + insertofftime: int = 300, + insertontime: int = 600, insertwidth: _ScreenUnits = ..., - invalidcommand: _EntryValidateCommand = ..., - invcmd: _EntryValidateCommand = ..., # same as invalidcommand - justify: Literal["left", "center", "right"] = ..., + invalidcommand: _EntryValidateCommand = "", + invcmd: _EntryValidateCommand = "", # same as invalidcommand + justify: Literal["left", "center", "right"] = "left", name: str = ..., readonlybackground: str = ..., - relief: _Relief = ..., + relief: _Relief = "sunken", selectbackground: str = ..., selectborderwidth: _ScreenUnits = ..., selectforeground: str = ..., - show: str = ..., - state: Literal["normal", "disabled", "readonly"] = ..., - takefocus: _TakeFocusValue = ..., + show: str = "", + state: Literal["normal", "disabled", "readonly"] = "normal", + takefocus: _TakeFocusValue = "", textvariable: Variable = ..., - validate: Literal["none", "focus", "focusin", "focusout", "key", "all"] = ..., - validatecommand: _EntryValidateCommand = ..., - vcmd: _EntryValidateCommand = ..., # same as validatecommand - width: int = ..., - xscrollcommand: _XYScrollCommand = ..., + validate: Literal["none", "focus", "focusin", "focusout", "key", "all"] = "none", + validatecommand: _EntryValidateCommand = "", + vcmd: _EntryValidateCommand = "", # same as validatecommand + width: int = 20, + xscrollcommand: _XYScrollCommand = "", ) -> None: ... @overload def configure( @@ -1944,19 +1939,19 @@ class Entry(Widget, XView): @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... config = configure - def delete(self, first: _EntryIndex, last: _EntryIndex | None = None) -> None: ... + def delete(self, first: str | int, last: str | int | None = None) -> None: ... def get(self) -> str: ... - def icursor(self, index: _EntryIndex) -> None: ... - def index(self, index: _EntryIndex) -> int: ... - def insert(self, index: _EntryIndex, string: str) -> None: ... + def icursor(self, index: str | int) -> None: ... + def index(self, index: str | int) -> int: ... + def insert(self, index: str | int, string: str) -> None: ... def scan_mark(self, x) -> None: ... def scan_dragto(self, x) -> None: ... - def selection_adjust(self, index: _EntryIndex) -> None: ... + def selection_adjust(self, index: str | int) -> None: ... def selection_clear(self) -> None: ... # type: ignore[override] - def selection_from(self, index: _EntryIndex) -> None: ... + def selection_from(self, index: str | int) -> None: ... def selection_present(self) -> bool: ... - def selection_range(self, start: _EntryIndex, end: _EntryIndex) -> None: ... - def selection_to(self, index: _EntryIndex) -> None: ... + def selection_range(self, start: str | int, end: str | int) -> None: ... + def selection_to(self, index: str | int) -> None: ... select_adjust = selection_adjust select_clear = selection_clear select_from = selection_from @@ -1971,25 +1966,25 @@ class Frame(Widget): cnf: dict[str, Any] | None = {}, *, background: str = ..., - bd: _ScreenUnits = ..., + bd: _ScreenUnits = 0, bg: str = ..., - border: _ScreenUnits = ..., - borderwidth: _ScreenUnits = ..., - class_: str = ..., # can't be changed with configure() - colormap: Literal["new", ""] | Misc = ..., # can't be changed with configure() - container: bool = ..., # can't be changed with configure() - cursor: _Cursor = ..., - height: _ScreenUnits = ..., + border: _ScreenUnits = 0, + borderwidth: _ScreenUnits = 0, + class_: str = "Frame", # can't be changed with configure() + colormap: Literal["new", ""] | Misc = "", # can't be changed with configure() + container: bool = False, # can't be changed with configure() + cursor: _Cursor = "", + height: _ScreenUnits = 0, highlightbackground: str = ..., highlightcolor: str = ..., - highlightthickness: _ScreenUnits = ..., + highlightthickness: _ScreenUnits = 0, name: str = ..., - padx: _ScreenUnits = ..., - pady: _ScreenUnits = ..., - relief: _Relief = ..., - takefocus: _TakeFocusValue = ..., - visual: str | tuple[str, int] = ..., # can't be changed with configure() - width: _ScreenUnits = ..., + padx: _ScreenUnits = 0, + pady: _ScreenUnits = 0, + relief: _Relief = "flat", + takefocus: _TakeFocusValue = 0, + visual: str | tuple[str, int] = "", # can't be changed with configure() + width: _ScreenUnits = 0, ) -> None: ... @overload def configure( @@ -2024,36 +2019,36 @@ class Label(Widget): *, activebackground: str = ..., activeforeground: str = ..., - anchor: _Anchor = ..., + anchor: _Anchor = "center", background: str = ..., bd: _ScreenUnits = ..., bg: str = ..., - bitmap: str = ..., + bitmap: str = "", border: _ScreenUnits = ..., borderwidth: _ScreenUnits = ..., - compound: _Compound = ..., - cursor: _Cursor = ..., + compound: _Compound = "none", + cursor: _Cursor = "", disabledforeground: str = ..., fg: str = ..., - font: _FontDescription = ..., + font: _FontDescription = "TkDefaultFont", foreground: str = ..., - height: _ScreenUnits = ..., + height: _ScreenUnits = 0, highlightbackground: str = ..., highlightcolor: str = ..., - highlightthickness: _ScreenUnits = ..., - image: _ImageSpec = ..., - justify: Literal["left", "center", "right"] = ..., + highlightthickness: _ScreenUnits = 0, + image: _ImageSpec = "", + justify: Literal["left", "center", "right"] = "center", name: str = ..., - padx: _ScreenUnits = ..., - pady: _ScreenUnits = ..., - relief: _Relief = ..., - state: Literal["normal", "active", "disabled"] = ..., - takefocus: _TakeFocusValue = ..., - text: float | str = ..., + padx: _ScreenUnits = 1, + pady: _ScreenUnits = 1, + relief: _Relief = "flat", + state: Literal["normal", "active", "disabled"] = "normal", + takefocus: _TakeFocusValue = 0, + text: float | str = "", textvariable: Variable = ..., - underline: int = ..., - width: _ScreenUnits = ..., - wraplength: _ScreenUnits = ..., + underline: int = -1, + width: _ScreenUnits = 0, + wraplength: _ScreenUnits = 0, ) -> None: ... @overload def configure( @@ -2104,21 +2099,21 @@ class Listbox(Widget, XView, YView): *, activestyle: Literal["dotbox", "none", "underline"] = ..., background: str = ..., - bd: _ScreenUnits = ..., + bd: _ScreenUnits = 1, bg: str = ..., - border: _ScreenUnits = ..., - borderwidth: _ScreenUnits = ..., - cursor: _Cursor = ..., + border: _ScreenUnits = 1, + borderwidth: _ScreenUnits = 1, + cursor: _Cursor = "", disabledforeground: str = ..., - exportselection: int = ..., + exportselection: bool | Literal[0, 1] = 1, fg: str = ..., font: _FontDescription = ..., foreground: str = ..., - height: int = ..., + height: int = 10, highlightbackground: str = ..., highlightcolor: str = ..., highlightthickness: _ScreenUnits = ..., - justify: Literal["left", "center", "right"] = ..., + justify: Literal["left", "center", "right"] = "left", # There's no tkinter.ListVar, but seems like bare tkinter.Variable # actually works for this: # @@ -2132,20 +2127,20 @@ class Listbox(Widget, XView, YView): name: str = ..., relief: _Relief = ..., selectbackground: str = ..., - selectborderwidth: _ScreenUnits = ..., + selectborderwidth: _ScreenUnits = 0, selectforeground: str = ..., # from listbox man page: "The value of the [selectmode] option may be # arbitrary, but the default bindings expect it to be ..." # # I have never seen anyone setting this to something else than what # "the default bindings expect", but let's support it anyway. - selectmode: str = ..., - setgrid: bool = ..., - state: Literal["normal", "disabled"] = ..., - takefocus: _TakeFocusValue = ..., - width: int = ..., - xscrollcommand: _XYScrollCommand = ..., - yscrollcommand: _XYScrollCommand = ..., + selectmode: str = "browse", + setgrid: bool = False, + state: Literal["normal", "disabled"] = "normal", + takefocus: _TakeFocusValue = "", + width: int = 20, + xscrollcommand: _XYScrollCommand = "", + yscrollcommand: _XYScrollCommand = "", ) -> None: ... @overload def configure( @@ -2223,23 +2218,23 @@ class Menu(Widget): bg: str = ..., border: _ScreenUnits = ..., borderwidth: _ScreenUnits = ..., - cursor: _Cursor = ..., + cursor: _Cursor = "arrow", disabledforeground: str = ..., fg: str = ..., font: _FontDescription = ..., foreground: str = ..., name: str = ..., - postcommand: Callable[[], object] | str = ..., + postcommand: Callable[[], object] | str = "", relief: _Relief = ..., selectcolor: str = ..., - takefocus: _TakeFocusValue = ..., - tearoff: int = ..., + takefocus: _TakeFocusValue = 0, + tearoff: bool | Literal[0, 1] = 1, # I guess tearoffcommand arguments are supposed to be widget objects, # but they are widget name strings. Use nametowidget() to handle the # arguments of tearoffcommand. - tearoffcommand: Callable[[str, str], object] | str = ..., - title: str = ..., - type: Literal["menubar", "tearoff", "normal"] = ..., + tearoffcommand: Callable[[str, str], object] | str = "", + title: str = "", + type: Literal["menubar", "tearoff", "normal"] = "normal", ) -> None: ... @overload def configure( @@ -2491,35 +2486,35 @@ class Menubutton(Widget): background: str = ..., bd: _ScreenUnits = ..., bg: str = ..., - bitmap: str = ..., + bitmap: str = "", border: _ScreenUnits = ..., borderwidth: _ScreenUnits = ..., - compound: _Compound = ..., - cursor: _Cursor = ..., - direction: Literal["above", "below", "left", "right", "flush"] = ..., + compound: _Compound = "none", + cursor: _Cursor = "", + direction: Literal["above", "below", "left", "right", "flush"] = "below", disabledforeground: str = ..., fg: str = ..., - font: _FontDescription = ..., + font: _FontDescription = "TkDefaultFont", foreground: str = ..., - height: _ScreenUnits = ..., + height: _ScreenUnits = 0, highlightbackground: str = ..., highlightcolor: str = ..., - highlightthickness: _ScreenUnits = ..., - image: _ImageSpec = ..., + highlightthickness: _ScreenUnits = 0, + image: _ImageSpec = "", indicatoron: bool = ..., justify: Literal["left", "center", "right"] = ..., menu: Menu = ..., name: str = ..., padx: _ScreenUnits = ..., pady: _ScreenUnits = ..., - relief: _Relief = ..., - state: Literal["normal", "active", "disabled"] = ..., - takefocus: _TakeFocusValue = ..., - text: float | str = ..., + relief: _Relief = "flat", + state: Literal["normal", "active", "disabled"] = "normal", + takefocus: _TakeFocusValue = 0, + text: float | str = "", textvariable: Variable = ..., - underline: int = ..., - width: _ScreenUnits = ..., - wraplength: _ScreenUnits = ..., + underline: int = -1, + width: _ScreenUnits = 0, + wraplength: _ScreenUnits = 0, ) -> None: ... @overload def configure( @@ -2571,30 +2566,30 @@ class Message(Widget): master: Misc | None = None, cnf: dict[str, Any] | None = {}, *, - anchor: _Anchor = ..., - aspect: int = ..., + anchor: _Anchor = "center", + aspect: int = 150, background: str = ..., - bd: _ScreenUnits = ..., + bd: _ScreenUnits = 1, bg: str = ..., - border: _ScreenUnits = ..., - borderwidth: _ScreenUnits = ..., - cursor: _Cursor = ..., + border: _ScreenUnits = 1, + borderwidth: _ScreenUnits = 1, + cursor: _Cursor = "", fg: str = ..., - font: _FontDescription = ..., + font: _FontDescription = "TkDefaultFont", foreground: str = ..., highlightbackground: str = ..., highlightcolor: str = ..., - highlightthickness: _ScreenUnits = ..., - justify: Literal["left", "center", "right"] = ..., + highlightthickness: _ScreenUnits = 0, + justify: Literal["left", "center", "right"] = "left", name: str = ..., padx: _ScreenUnits = ..., pady: _ScreenUnits = ..., - relief: _Relief = ..., - takefocus: _TakeFocusValue = ..., - text: float | str = ..., + relief: _Relief = "flat", + takefocus: _TakeFocusValue = 0, + text: float | str = "", textvariable: Variable = ..., # there's width but no height - width: _ScreenUnits = ..., + width: _ScreenUnits = 0, ) -> None: ... @overload def configure( @@ -2636,46 +2631,46 @@ class Radiobutton(Widget): *, activebackground: str = ..., activeforeground: str = ..., - anchor: _Anchor = ..., + anchor: _Anchor = "center", background: str = ..., bd: _ScreenUnits = ..., bg: str = ..., - bitmap: str = ..., + bitmap: str = "", border: _ScreenUnits = ..., borderwidth: _ScreenUnits = ..., - command: _ButtonCommand = ..., - compound: _Compound = ..., - cursor: _Cursor = ..., + command: _ButtonCommand = "", + compound: _Compound = "none", + cursor: _Cursor = "", disabledforeground: str = ..., fg: str = ..., - font: _FontDescription = ..., + font: _FontDescription = "TkDefaultFont", foreground: str = ..., - height: _ScreenUnits = ..., + height: _ScreenUnits = 0, highlightbackground: str = ..., highlightcolor: str = ..., - highlightthickness: _ScreenUnits = ..., - image: _ImageSpec = ..., - indicatoron: bool = ..., - justify: Literal["left", "center", "right"] = ..., + highlightthickness: _ScreenUnits = 1, + image: _ImageSpec = "", + indicatoron: bool = True, + justify: Literal["left", "center", "right"] = "center", name: str = ..., offrelief: _Relief = ..., - overrelief: _Relief = ..., - padx: _ScreenUnits = ..., - pady: _ScreenUnits = ..., - relief: _Relief = ..., + overrelief: _Relief | Literal[""] = "", + padx: _ScreenUnits = 1, + pady: _ScreenUnits = 1, + relief: _Relief = "flat", selectcolor: str = ..., - selectimage: _ImageSpec = ..., - state: Literal["normal", "active", "disabled"] = ..., - takefocus: _TakeFocusValue = ..., - text: float | str = ..., + selectimage: _ImageSpec = "", + state: Literal["normal", "active", "disabled"] = "normal", + takefocus: _TakeFocusValue = "", + text: float | str = "", textvariable: Variable = ..., - tristateimage: _ImageSpec = ..., - tristatevalue: Any = ..., - underline: int = ..., - value: Any = ..., + tristateimage: _ImageSpec = "", + tristatevalue: Any = "", + underline: int = -1, + value: Any = "", variable: Variable | Literal[""] = ..., - width: _ScreenUnits = ..., - wraplength: _ScreenUnits = ..., + width: _ScreenUnits = 0, + wraplength: _ScreenUnits = 0, ) -> None: ... @overload def configure( @@ -2706,7 +2701,7 @@ class Radiobutton(Widget): indicatoron: bool = ..., justify: Literal["left", "center", "right"] = ..., offrelief: _Relief = ..., - overrelief: _Relief = ..., + overrelief: _Relief | Literal[""] = ..., padx: _ScreenUnits = ..., pady: _ScreenUnits = ..., relief: _Relief = ..., @@ -2740,40 +2735,40 @@ class Scale(Widget): *, activebackground: str = ..., background: str = ..., - bd: _ScreenUnits = ..., + bd: _ScreenUnits = 1, bg: str = ..., - bigincrement: float = ..., - border: _ScreenUnits = ..., - borderwidth: _ScreenUnits = ..., + bigincrement: float = 0.0, + border: _ScreenUnits = 1, + borderwidth: _ScreenUnits = 1, # don't know why the callback gets string instead of float - command: str | Callable[[str], object] = ..., - cursor: _Cursor = ..., - digits: int = ..., + command: str | Callable[[str], object] = "", + cursor: _Cursor = "", + digits: int = 0, fg: str = ..., - font: _FontDescription = ..., + font: _FontDescription = "TkDefaultFont", foreground: str = ..., - from_: float = ..., + from_: float = 0.0, highlightbackground: str = ..., highlightcolor: str = ..., highlightthickness: _ScreenUnits = ..., - label: str = ..., - length: _ScreenUnits = ..., + label: str = "", + length: _ScreenUnits = 100, name: str = ..., - orient: Literal["horizontal", "vertical"] = ..., - relief: _Relief = ..., - repeatdelay: int = ..., - repeatinterval: int = ..., - resolution: float = ..., - showvalue: bool = ..., - sliderlength: _ScreenUnits = ..., - sliderrelief: _Relief = ..., - state: Literal["normal", "active", "disabled"] = ..., - takefocus: _TakeFocusValue = ..., - tickinterval: float = ..., - to: float = ..., + orient: Literal["horizontal", "vertical"] = "vertical", + relief: _Relief = "flat", + repeatdelay: int = 300, + repeatinterval: int = 100, + resolution: float = 1.0, + showvalue: bool = True, + sliderlength: _ScreenUnits = 30, + sliderrelief: _Relief = "raised", + state: Literal["normal", "active", "disabled"] = "normal", + takefocus: _TakeFocusValue = "", + tickinterval: float = 0.0, + to: float = 100.0, troughcolor: str = ..., variable: IntVar | DoubleVar = ..., - width: _ScreenUnits = ..., + width: _ScreenUnits = 15, ) -> None: ... @overload def configure( @@ -2830,7 +2825,7 @@ class Scrollbar(Widget): cnf: dict[str, Any] | None = {}, *, activebackground: str = ..., - activerelief: _Relief = ..., + activerelief: _Relief = "raised", background: str = ..., bd: _ScreenUnits = ..., bg: str = ..., @@ -2840,19 +2835,19 @@ class Scrollbar(Widget): # 'SCROLLING COMMANDS' in scrollbar man page. There doesn't seem to # be any way to specify an overloaded callback function, so we say # that it can take any args while it can't in reality. - command: Callable[..., tuple[float, float] | None] | str = ..., - cursor: _Cursor = ..., - elementborderwidth: _ScreenUnits = ..., + command: Callable[..., tuple[float, float] | None] | str = "", + cursor: _Cursor = "", + elementborderwidth: _ScreenUnits = -1, highlightbackground: str = ..., highlightcolor: str = ..., - highlightthickness: _ScreenUnits = ..., - jump: bool = ..., + highlightthickness: _ScreenUnits = 0, + jump: bool = False, name: str = ..., - orient: Literal["horizontal", "vertical"] = ..., + orient: Literal["horizontal", "vertical"] = "vertical", relief: _Relief = ..., - repeatdelay: int = ..., - repeatinterval: int = ..., - takefocus: _TakeFocusValue = ..., + repeatdelay: int = 300, + repeatinterval: int = 100, + takefocus: _TakeFocusValue = "", troughcolor: str = ..., width: _ScreenUnits = ..., ) -> None: ... @@ -2901,56 +2896,56 @@ class Text(Widget, XView, YView): master: Misc | None = None, cnf: dict[str, Any] | None = {}, *, - autoseparators: bool = ..., + autoseparators: bool = True, background: str = ..., bd: _ScreenUnits = ..., bg: str = ..., - blockcursor: bool = ..., + blockcursor: bool = False, border: _ScreenUnits = ..., borderwidth: _ScreenUnits = ..., - cursor: _Cursor = ..., - endline: int | Literal[""] = ..., - exportselection: bool = ..., + cursor: _Cursor = "xterm", + endline: int | Literal[""] = "", + exportselection: bool = True, fg: str = ..., - font: _FontDescription = ..., + font: _FontDescription = "TkFixedFont", foreground: str = ..., # width is always int, but height is allowed to be ScreenUnits. # This doesn't make any sense to me, and this isn't documented. # The docs seem to say that both should be integers. - height: _ScreenUnits = ..., + height: _ScreenUnits = 24, highlightbackground: str = ..., highlightcolor: str = ..., highlightthickness: _ScreenUnits = ..., inactiveselectbackground: str = ..., insertbackground: str = ..., - insertborderwidth: _ScreenUnits = ..., - insertofftime: int = ..., - insertontime: int = ..., - insertunfocussed: Literal["none", "hollow", "solid"] = ..., + insertborderwidth: _ScreenUnits = 0, + insertofftime: int = 300, + insertontime: int = 600, + insertunfocussed: Literal["none", "hollow", "solid"] = "none", insertwidth: _ScreenUnits = ..., - maxundo: int = ..., + maxundo: int = 0, name: str = ..., - padx: _ScreenUnits = ..., - pady: _ScreenUnits = ..., + padx: _ScreenUnits = 1, + pady: _ScreenUnits = 1, relief: _Relief = ..., selectbackground: str = ..., selectborderwidth: _ScreenUnits = ..., selectforeground: str = ..., - setgrid: bool = ..., - spacing1: _ScreenUnits = ..., - spacing2: _ScreenUnits = ..., - spacing3: _ScreenUnits = ..., - startline: int | Literal[""] = ..., - state: Literal["normal", "disabled"] = ..., + setgrid: bool = False, + spacing1: _ScreenUnits = 0, + spacing2: _ScreenUnits = 0, + spacing3: _ScreenUnits = 0, + startline: int | Literal[""] = "", + state: Literal["normal", "disabled"] = "normal", # Literal inside Tuple doesn't actually work - tabs: _ScreenUnits | str | tuple[_ScreenUnits | str, ...] = ..., - tabstyle: Literal["tabular", "wordprocessor"] = ..., - takefocus: _TakeFocusValue = ..., - undo: bool = ..., - width: int = ..., - wrap: Literal["none", "char", "word"] = ..., - xscrollcommand: _XYScrollCommand = ..., - yscrollcommand: _XYScrollCommand = ..., + tabs: _ScreenUnits | str | tuple[_ScreenUnits | str, ...] = "", + tabstyle: Literal["tabular", "wordprocessor"] = "tabular", + takefocus: _TakeFocusValue = "", + undo: bool = False, + width: int = 80, + wrap: Literal["none", "char", "word"] = "char", + xscrollcommand: _XYScrollCommand = "", + yscrollcommand: _XYScrollCommand = "", ) -> None: ... @overload def configure( @@ -3371,51 +3366,51 @@ class Spinbox(Widget, XView): border: _ScreenUnits = ..., borderwidth: _ScreenUnits = ..., buttonbackground: str = ..., - buttoncursor: _Cursor = ..., + buttoncursor: _Cursor = "", buttondownrelief: _Relief = ..., buttonuprelief: _Relief = ..., # percent substitutions don't seem to be supported, it's similar to Entry's validation stuff - command: Callable[[], object] | str | list[str] | tuple[str, ...] = ..., - cursor: _Cursor = ..., + command: Callable[[], object] | str | list[str] | tuple[str, ...] = "", + cursor: _Cursor = "xterm", disabledbackground: str = ..., disabledforeground: str = ..., - exportselection: bool = ..., + exportselection: bool = True, fg: str = ..., - font: _FontDescription = ..., + font: _FontDescription = "TkTextFont", foreground: str = ..., - format: str = ..., - from_: float = ..., + format: str = "", + from_: float = 0.0, highlightbackground: str = ..., highlightcolor: str = ..., highlightthickness: _ScreenUnits = ..., - increment: float = ..., + increment: float = 1.0, insertbackground: str = ..., - insertborderwidth: _ScreenUnits = ..., - insertofftime: int = ..., - insertontime: int = ..., + insertborderwidth: _ScreenUnits = 0, + insertofftime: int = 300, + insertontime: int = 600, insertwidth: _ScreenUnits = ..., - invalidcommand: _EntryValidateCommand = ..., - invcmd: _EntryValidateCommand = ..., - justify: Literal["left", "center", "right"] = ..., + invalidcommand: _EntryValidateCommand = "", + invcmd: _EntryValidateCommand = "", + justify: Literal["left", "center", "right"] = "left", name: str = ..., readonlybackground: str = ..., - relief: _Relief = ..., - repeatdelay: int = ..., - repeatinterval: int = ..., + relief: _Relief = "sunken", + repeatdelay: int = 400, + repeatinterval: int = 100, selectbackground: str = ..., selectborderwidth: _ScreenUnits = ..., selectforeground: str = ..., - state: Literal["normal", "disabled", "readonly"] = ..., - takefocus: _TakeFocusValue = ..., + state: Literal["normal", "disabled", "readonly"] = "normal", + takefocus: _TakeFocusValue = "", textvariable: Variable = ..., - to: float = ..., - validate: Literal["none", "focus", "focusin", "focusout", "key", "all"] = ..., - validatecommand: _EntryValidateCommand = ..., - vcmd: _EntryValidateCommand = ..., + to: float = 0.0, + validate: Literal["none", "focus", "focusin", "focusout", "key", "all"] = "none", + validatecommand: _EntryValidateCommand = "", + vcmd: _EntryValidateCommand = "", values: list[str] | tuple[str, ...] = ..., - width: int = ..., - wrap: bool = ..., - xscrollcommand: _XYScrollCommand = ..., + width: int = 20, + wrap: bool = False, + xscrollcommand: _XYScrollCommand = "", ) -> None: ... @overload def configure( @@ -3481,8 +3476,8 @@ class Spinbox(Widget, XView): def get(self) -> str: ... def icursor(self, index): ... def identify(self, x: int, y: int) -> Literal["", "buttondown", "buttonup", "entry"]: ... - def index(self, index: _EntryIndex) -> int: ... - def insert(self, index: _EntryIndex, s: str) -> Literal[""]: ... + def index(self, index: str | int) -> int: ... + def insert(self, index: str | int, s: str) -> Literal[""]: ... # spinbox.invoke("asdf") gives error mentioning .invoke("none"), but it's not documented def invoke(self, element: Literal["none", "buttonup", "buttondown"]) -> Literal[""]: ... def scan(self, *args): ... @@ -3504,32 +3499,32 @@ class LabelFrame(Widget): cnf: dict[str, Any] | None = {}, *, background: str = ..., - bd: _ScreenUnits = ..., + bd: _ScreenUnits = 2, bg: str = ..., - border: _ScreenUnits = ..., - borderwidth: _ScreenUnits = ..., - class_: str = ..., # can't be changed with configure() - colormap: Literal["new", ""] | Misc = ..., # can't be changed with configure() - container: bool = ..., # undocumented, can't be changed with configure() - cursor: _Cursor = ..., + border: _ScreenUnits = 2, + borderwidth: _ScreenUnits = 2, + class_: str = "Labelframe", # can't be changed with configure() + colormap: Literal["new", ""] | Misc = "", # can't be changed with configure() + container: bool = False, # undocumented, can't be changed with configure() + cursor: _Cursor = "", fg: str = ..., - font: _FontDescription = ..., + font: _FontDescription = "TkDefaultFont", foreground: str = ..., - height: _ScreenUnits = ..., + height: _ScreenUnits = 0, highlightbackground: str = ..., highlightcolor: str = ..., - highlightthickness: _ScreenUnits = ..., + highlightthickness: _ScreenUnits = 0, # 'ne' and 'en' are valid labelanchors, but only 'ne' is a valid _Anchor. - labelanchor: Literal["nw", "n", "ne", "en", "e", "es", "se", "s", "sw", "ws", "w", "wn"] = ..., + labelanchor: Literal["nw", "n", "ne", "en", "e", "es", "se", "s", "sw", "ws", "w", "wn"] = "nw", labelwidget: Misc = ..., name: str = ..., - padx: _ScreenUnits = ..., - pady: _ScreenUnits = ..., - relief: _Relief = ..., - takefocus: _TakeFocusValue = ..., - text: float | str = ..., - visual: str | tuple[str, int] = ..., # can't be changed with configure() - width: _ScreenUnits = ..., + padx: _ScreenUnits = 0, + pady: _ScreenUnits = 0, + relief: _Relief = "groove", + takefocus: _TakeFocusValue = 0, + text: float | str = "", + visual: str | tuple[str, int] = "", # can't be changed with configure() + width: _ScreenUnits = 0, ) -> None: ... @overload def configure( @@ -3569,27 +3564,27 @@ class PanedWindow(Widget): cnf: dict[str, Any] | None = {}, *, background: str = ..., - bd: _ScreenUnits = ..., + bd: _ScreenUnits = 1, bg: str = ..., - border: _ScreenUnits = ..., - borderwidth: _ScreenUnits = ..., - cursor: _Cursor = ..., - handlepad: _ScreenUnits = ..., - handlesize: _ScreenUnits = ..., - height: _ScreenUnits = ..., + border: _ScreenUnits = 1, + borderwidth: _ScreenUnits = 1, + cursor: _Cursor = "", + handlepad: _ScreenUnits = 8, + handlesize: _ScreenUnits = 8, + height: _ScreenUnits = "", name: str = ..., - opaqueresize: bool = ..., - orient: Literal["horizontal", "vertical"] = ..., - proxybackground: str = ..., - proxyborderwidth: _ScreenUnits = ..., - proxyrelief: _Relief = ..., - relief: _Relief = ..., - sashcursor: _Cursor = ..., - sashpad: _ScreenUnits = ..., - sashrelief: _Relief = ..., - sashwidth: _ScreenUnits = ..., - showhandle: bool = ..., - width: _ScreenUnits = ..., + opaqueresize: bool = True, + orient: Literal["horizontal", "vertical"] = "horizontal", + proxybackground: str = "", + proxyborderwidth: _ScreenUnits = 2, + proxyrelief: _Relief = "flat", + relief: _Relief = "flat", + sashcursor: _Cursor = "", + sashpad: _ScreenUnits = 0, + sashrelief: _Relief = "flat", + sashwidth: _ScreenUnits = 3, + showhandle: bool = False, + width: _ScreenUnits = "", ) -> None: ... @overload def configure( diff --git a/mypy/typeshed/stdlib/tkinter/ttk.pyi b/mypy/typeshed/stdlib/tkinter/ttk.pyi index ac5accb73d9f..f1b132b33657 100644 --- a/mypy/typeshed/stdlib/tkinter/ttk.pyi +++ b/mypy/typeshed/stdlib/tkinter/ttk.pyi @@ -46,7 +46,7 @@ _Padding: TypeAlias = ( ) # from ttk_widget (aka ttk::widget) manual page, differs from tkinter._Compound -_TtkCompound: TypeAlias = Literal["text", "image", tkinter._Compound] +_TtkCompound: TypeAlias = Literal["", "text", "image", tkinter._Compound] class Style: master: Incomplete @@ -78,21 +78,21 @@ class Button(Widget): self, master: tkinter.Misc | None = None, *, - class_: str = ..., - command: tkinter._ButtonCommand = ..., - compound: _TtkCompound = ..., - cursor: tkinter._Cursor = ..., - default: Literal["normal", "active", "disabled"] = ..., - image: tkinter._ImageSpec = ..., + class_: str = "", + command: tkinter._ButtonCommand = "", + compound: _TtkCompound = "", + cursor: tkinter._Cursor = "", + default: Literal["normal", "active", "disabled"] = "normal", + image: tkinter._ImageSpec = "", name: str = ..., padding=..., # undocumented - state: str = ..., - style: str = ..., + state: str = "normal", + style: str = "", takefocus: tkinter._TakeFocusValue = ..., - text: float | str = ..., + text: float | str = "", textvariable: tkinter.Variable = ..., - underline: int = ..., - width: int | Literal[""] = ..., + underline: int = -1, + width: int | Literal[""] = "", ) -> None: ... @overload def configure( @@ -123,26 +123,26 @@ class Checkbutton(Widget): self, master: tkinter.Misc | None = None, *, - class_: str = ..., - command: tkinter._ButtonCommand = ..., - compound: _TtkCompound = ..., - cursor: tkinter._Cursor = ..., - image: tkinter._ImageSpec = ..., + class_: str = "", + command: tkinter._ButtonCommand = "", + compound: _TtkCompound = "", + cursor: tkinter._Cursor = "", + image: tkinter._ImageSpec = "", name: str = ..., - offvalue: Any = ..., - onvalue: Any = ..., + offvalue: Any = 0, + onvalue: Any = 1, padding=..., # undocumented - state: str = ..., - style: str = ..., + state: str = "normal", + style: str = "", takefocus: tkinter._TakeFocusValue = ..., - text: float | str = ..., + text: float | str = "", textvariable: tkinter.Variable = ..., - underline: int = ..., + underline: int = -1, # Seems like variable can be empty string, but actually setting it to # empty string segfaults before Tcl 8.6.9. Search for ttk::checkbutton # here: https://sourceforge.net/projects/tcl/files/Tcl/8.6.9/tcltk-release-notes-8.6.9.txt/view variable: tkinter.Variable = ..., - width: int | Literal[""] = ..., + width: int | Literal[""] = "", ) -> None: ... @overload def configure( @@ -177,23 +177,23 @@ class Entry(Widget, tkinter.Entry): widget: str | None = None, *, background: str = ..., # undocumented - class_: str = ..., + class_: str = "", cursor: tkinter._Cursor = ..., - exportselection: bool = ..., - font: _FontDescription = ..., - foreground: str = ..., - invalidcommand: tkinter._EntryValidateCommand = ..., - justify: Literal["left", "center", "right"] = ..., + exportselection: bool = True, + font: _FontDescription = "TkTextFont", + foreground: str = "", + invalidcommand: tkinter._EntryValidateCommand = "", + justify: Literal["left", "center", "right"] = "left", name: str = ..., - show: str = ..., - state: str = ..., - style: str = ..., + show: str = "", + state: str = "normal", + style: str = "", takefocus: tkinter._TakeFocusValue = ..., textvariable: tkinter.Variable = ..., - validate: Literal["none", "focus", "focusin", "focusout", "key", "all"] = ..., - validatecommand: tkinter._EntryValidateCommand = ..., - width: int = ..., - xscrollcommand: tkinter._XYScrollCommand = ..., + validate: Literal["none", "focus", "focusin", "focusout", "key", "all"] = "none", + validatecommand: tkinter._EntryValidateCommand = "", + width: int = 20, + xscrollcommand: tkinter._XYScrollCommand = "", ) -> None: ... @overload # type: ignore[override] def configure( @@ -254,25 +254,25 @@ class Combobox(Entry): master: tkinter.Misc | None = None, *, background: str = ..., # undocumented - class_: str = ..., - cursor: tkinter._Cursor = ..., - exportselection: bool = ..., + class_: str = "", + cursor: tkinter._Cursor = "", + exportselection: bool = True, font: _FontDescription = ..., # undocumented foreground: str = ..., # undocumented - height: int = ..., + height: int = 10, invalidcommand: tkinter._EntryValidateCommand = ..., # undocumented - justify: Literal["left", "center", "right"] = ..., + justify: Literal["left", "center", "right"] = "left", name: str = ..., - postcommand: Callable[[], object] | str = ..., + postcommand: Callable[[], object] | str = "", show=..., # undocumented - state: str = ..., - style: str = ..., + state: str = "normal", + style: str = "", takefocus: tkinter._TakeFocusValue = ..., textvariable: tkinter.Variable = ..., validate: Literal["none", "focus", "focusin", "focusout", "key", "all"] = ..., # undocumented validatecommand: tkinter._EntryValidateCommand = ..., # undocumented values: list[str] | tuple[str, ...] = ..., - width: int = ..., + width: int = 20, xscrollcommand: tkinter._XYScrollCommand = ..., # undocumented ) -> None: ... @overload # type: ignore[override] @@ -334,21 +334,23 @@ class Combobox(Entry): def set(self, value: Any) -> None: ... class Frame(Widget): + # This should be kept in sync with tkinter.ttk.LabeledScale.__init__() + # (all of these keyword-only arguments are also present there) def __init__( self, master: tkinter.Misc | None = None, *, border: tkinter._ScreenUnits = ..., borderwidth: tkinter._ScreenUnits = ..., - class_: str = ..., - cursor: tkinter._Cursor = ..., - height: tkinter._ScreenUnits = ..., + class_: str = "", + cursor: tkinter._Cursor = "", + height: tkinter._ScreenUnits = 0, name: str = ..., padding: _Padding = ..., relief: tkinter._Relief = ..., - style: str = ..., - takefocus: tkinter._TakeFocusValue = ..., - width: tkinter._ScreenUnits = ..., + style: str = "", + takefocus: tkinter._TakeFocusValue = "", + width: tkinter._ScreenUnits = 0, ) -> None: ... @overload def configure( @@ -375,26 +377,26 @@ class Label(Widget): master: tkinter.Misc | None = None, *, anchor: tkinter._Anchor = ..., - background: str = ..., + background: str = "", border: tkinter._ScreenUnits = ..., # alias for borderwidth borderwidth: tkinter._ScreenUnits = ..., # undocumented - class_: str = ..., - compound: _TtkCompound = ..., - cursor: tkinter._Cursor = ..., + class_: str = "", + compound: _TtkCompound = "", + cursor: tkinter._Cursor = "", font: _FontDescription = ..., - foreground: str = ..., - image: tkinter._ImageSpec = ..., + foreground: str = "", + image: tkinter._ImageSpec = "", justify: Literal["left", "center", "right"] = ..., name: str = ..., padding: _Padding = ..., relief: tkinter._Relief = ..., - state: str = ..., - style: str = ..., - takefocus: tkinter._TakeFocusValue = ..., - text: float | str = ..., + state: str = "normal", + style: str = "", + takefocus: tkinter._TakeFocusValue = "", + text: float | str = "", textvariable: tkinter.Variable = ..., - underline: int = ..., - width: int | Literal[""] = ..., + underline: int = -1, + width: int | Literal[""] = "", wraplength: tkinter._ScreenUnits = ..., ) -> None: ... @overload @@ -434,19 +436,19 @@ class Labelframe(Widget): *, border: tkinter._ScreenUnits = ..., borderwidth: tkinter._ScreenUnits = ..., # undocumented - class_: str = ..., - cursor: tkinter._Cursor = ..., - height: tkinter._ScreenUnits = ..., + class_: str = "", + cursor: tkinter._Cursor = "", + height: tkinter._ScreenUnits = 0, labelanchor: Literal["nw", "n", "ne", "en", "e", "es", "se", "s", "sw", "ws", "w", "wn"] = ..., labelwidget: tkinter.Misc = ..., name: str = ..., padding: _Padding = ..., relief: tkinter._Relief = ..., # undocumented - style: str = ..., - takefocus: tkinter._TakeFocusValue = ..., - text: float | str = ..., - underline: int = ..., - width: tkinter._ScreenUnits = ..., + style: str = "", + takefocus: tkinter._TakeFocusValue = "", + text: float | str = "", + underline: int = -1, + width: tkinter._ScreenUnits = 0, ) -> None: ... @overload def configure( @@ -478,21 +480,21 @@ class Menubutton(Widget): self, master: tkinter.Misc | None = None, *, - class_: str = ..., - compound: _TtkCompound = ..., - cursor: tkinter._Cursor = ..., - direction: Literal["above", "below", "left", "right", "flush"] = ..., - image: tkinter._ImageSpec = ..., + class_: str = "", + compound: _TtkCompound = "", + cursor: tkinter._Cursor = "", + direction: Literal["above", "below", "left", "right", "flush"] = "below", + image: tkinter._ImageSpec = "", menu: tkinter.Menu = ..., name: str = ..., padding=..., # undocumented - state: str = ..., - style: str = ..., + state: str = "normal", + style: str = "", takefocus: tkinter._TakeFocusValue = ..., - text: float | str = ..., + text: float | str = "", textvariable: tkinter.Variable = ..., - underline: int = ..., - width: int | Literal[""] = ..., + underline: int = -1, + width: int | Literal[""] = "", ) -> None: ... @overload def configure( @@ -522,14 +524,14 @@ class Notebook(Widget): self, master: tkinter.Misc | None = None, *, - class_: str = ..., - cursor: tkinter._Cursor = ..., - height: int = ..., + class_: str = "", + cursor: tkinter._Cursor = "", + height: int = 0, name: str = ..., padding: _Padding = ..., - style: str = ..., + style: str = "", takefocus: tkinter._TakeFocusValue = ..., - width: int = ..., + width: int = 0, ) -> None: ... @overload def configure( @@ -573,15 +575,15 @@ class Panedwindow(Widget, tkinter.PanedWindow): self, master: tkinter.Misc | None = None, *, - class_: str = ..., - cursor: tkinter._Cursor = ..., + class_: str = "", + cursor: tkinter._Cursor = "", # width and height for tkinter.ttk.Panedwindow are int but for tkinter.PanedWindow they are screen units - height: int = ..., + height: int = 0, name: str = ..., - orient: Literal["vertical", "horizontal"] = ..., # can't be changed with configure() - style: str = ..., - takefocus: tkinter._TakeFocusValue = ..., - width: int = ..., + orient: Literal["vertical", "horizontal"] = "vertical", # can't be changed with configure() + style: str = "", + takefocus: tkinter._TakeFocusValue = "", + width: int = 0, ) -> None: ... def add(self, child: tkinter.Widget, *, weight: int = ..., **kw) -> None: ... @overload # type: ignore[override] @@ -623,17 +625,17 @@ class Progressbar(Widget): self, master: tkinter.Misc | None = None, *, - class_: str = ..., - cursor: tkinter._Cursor = ..., - length: tkinter._ScreenUnits = ..., - maximum: float = ..., - mode: Literal["determinate", "indeterminate"] = ..., + class_: str = "", + cursor: tkinter._Cursor = "", + length: tkinter._ScreenUnits = 100, + maximum: float = 100, + mode: Literal["determinate", "indeterminate"] = "determinate", name: str = ..., - orient: Literal["horizontal", "vertical"] = ..., - phase: int = ..., # docs say read-only but assigning int to this works - style: str = ..., - takefocus: tkinter._TakeFocusValue = ..., - value: float = ..., + orient: Literal["horizontal", "vertical"] = "horizontal", + phase: int = 0, # docs say read-only but assigning int to this works + style: str = "", + takefocus: tkinter._TakeFocusValue = "", + value: float = 0.0, variable: tkinter.IntVar | tkinter.DoubleVar = ..., ) -> None: ... @overload @@ -664,22 +666,22 @@ class Radiobutton(Widget): self, master: tkinter.Misc | None = None, *, - class_: str = ..., - command: tkinter._ButtonCommand = ..., - compound: _TtkCompound = ..., - cursor: tkinter._Cursor = ..., - image: tkinter._ImageSpec = ..., + class_: str = "", + command: tkinter._ButtonCommand = "", + compound: _TtkCompound = "", + cursor: tkinter._Cursor = "", + image: tkinter._ImageSpec = "", name: str = ..., padding=..., # undocumented - state: str = ..., - style: str = ..., + state: str = "normal", + style: str = "", takefocus: tkinter._TakeFocusValue = ..., - text: float | str = ..., + text: float | str = "", textvariable: tkinter.Variable = ..., - underline: int = ..., - value: Any = ..., + underline: int = -1, + value: Any = "1", variable: tkinter.Variable | Literal[""] = ..., - width: int | Literal[""] = ..., + width: int | Literal[""] = "", ) -> None: ... @overload def configure( @@ -712,18 +714,18 @@ class Scale(Widget, tkinter.Scale): # type: ignore[misc] self, master: tkinter.Misc | None = None, *, - class_: str = ..., - command: str | Callable[[str], object] = ..., - cursor: tkinter._Cursor = ..., - from_: float = ..., - length: tkinter._ScreenUnits = ..., + class_: str = "", + command: str | Callable[[str], object] = "", + cursor: tkinter._Cursor = "", + from_: float = 0, + length: tkinter._ScreenUnits = 100, name: str = ..., - orient: Literal["horizontal", "vertical"] = ..., + orient: Literal["horizontal", "vertical"] = "horizontal", state: str = ..., # undocumented - style: str = ..., + style: str = "", takefocus: tkinter._TakeFocusValue = ..., - to: float = ..., - value: float = ..., + to: float = 1.0, + value: float = 0, variable: tkinter.IntVar | tkinter.DoubleVar = ..., ) -> None: ... @overload # type: ignore[override] @@ -773,13 +775,13 @@ class Scrollbar(Widget, tkinter.Scrollbar): # type: ignore[misc] self, master: tkinter.Misc | None = None, *, - class_: str = ..., - command: Callable[..., tuple[float, float] | None] | str = ..., - cursor: tkinter._Cursor = ..., + class_: str = "", + command: Callable[..., tuple[float, float] | None] | str = "", + cursor: tkinter._Cursor = "", name: str = ..., - orient: Literal["horizontal", "vertical"] = ..., - style: str = ..., - takefocus: tkinter._TakeFocusValue = ..., + orient: Literal["horizontal", "vertical"] = "vertical", + style: str = "", + takefocus: tkinter._TakeFocusValue = "", ) -> None: ... @overload # type: ignore[override] def configure( @@ -814,12 +816,12 @@ class Separator(Widget): self, master: tkinter.Misc | None = None, *, - class_: str = ..., - cursor: tkinter._Cursor = ..., + class_: str = "", + cursor: tkinter._Cursor = "", name: str = ..., - orient: Literal["horizontal", "vertical"] = ..., - style: str = ..., - takefocus: tkinter._TakeFocusValue = ..., + orient: Literal["horizontal", "vertical"] = "horizontal", + style: str = "", + takefocus: tkinter._TakeFocusValue = "", ) -> None: ... @overload def configure( @@ -840,11 +842,11 @@ class Sizegrip(Widget): self, master: tkinter.Misc | None = None, *, - class_: str = ..., + class_: str = "", cursor: tkinter._Cursor = ..., name: str = ..., - style: str = ..., - takefocus: tkinter._TakeFocusValue = ..., + style: str = "", + takefocus: tkinter._TakeFocusValue = "", ) -> None: ... @overload def configure( @@ -865,30 +867,30 @@ class Spinbox(Entry): master: tkinter.Misc | None = None, *, background: str = ..., # undocumented - class_: str = ..., - command: Callable[[], object] | str | list[str] | tuple[str, ...] = ..., - cursor: tkinter._Cursor = ..., + class_: str = "", + command: Callable[[], object] | str | list[str] | tuple[str, ...] = "", + cursor: tkinter._Cursor = "", exportselection: bool = ..., # undocumented font: _FontDescription = ..., # undocumented foreground: str = ..., # undocumented - format: str = ..., - from_: float = ..., - increment: float = ..., + format: str = "", + from_: float = 0, + increment: float = 1, invalidcommand: tkinter._EntryValidateCommand = ..., # undocumented justify: Literal["left", "center", "right"] = ..., # undocumented name: str = ..., show=..., # undocumented - state: str = ..., - style: str = ..., + state: str = "normal", + style: str = "", takefocus: tkinter._TakeFocusValue = ..., textvariable: tkinter.Variable = ..., # undocumented - to: float = ..., - validate: Literal["none", "focus", "focusin", "focusout", "key", "all"] = ..., - validatecommand: tkinter._EntryValidateCommand = ..., + to: float = 0, + validate: Literal["none", "focus", "focusin", "focusout", "key", "all"] = "none", + validatecommand: tkinter._EntryValidateCommand = "", values: list[str] | tuple[str, ...] = ..., width: int = ..., # undocumented - wrap: bool = ..., - xscrollcommand: tkinter._XYScrollCommand = ..., + wrap: bool = False, + xscrollcommand: tkinter._XYScrollCommand = "", ) -> None: ... @overload # type: ignore[override] def configure( @@ -957,23 +959,23 @@ class Treeview(Widget, tkinter.XView, tkinter.YView): self, master: tkinter.Misc | None = None, *, - class_: str = ..., - columns: str | list[str] | list[int] | list[str | int] | tuple[str | int, ...] = ..., - cursor: tkinter._Cursor = ..., - displaycolumns: str | int | list[str] | tuple[str, ...] | list[int] | tuple[int, ...] = ..., - height: int = ..., + class_: str = "", + columns: str | list[str] | list[int] | list[str | int] | tuple[str | int, ...] = "", + cursor: tkinter._Cursor = "", + displaycolumns: str | int | list[str] | tuple[str, ...] | list[int] | tuple[int, ...] = ("#all",), + height: int = 10, name: str = ..., padding: _Padding = ..., - selectmode: Literal["extended", "browse", "none"] = ..., + selectmode: Literal["extended", "browse", "none"] = "extended", # list/tuple of Literal don't actually work in mypy # # 'tree headings' is same as ['tree', 'headings'], and I wouldn't be # surprised if someone is using it. - show: Literal["tree", "headings", "tree headings", ""] | list[str] | tuple[str, ...] = ..., - style: str = ..., + show: Literal["tree", "headings", "tree headings", ""] | list[str] | tuple[str, ...] = ("tree", "headings"), + style: str = "", takefocus: tkinter._TakeFocusValue = ..., - xscrollcommand: tkinter._XYScrollCommand = ..., - yscrollcommand: tkinter._XYScrollCommand = ..., + xscrollcommand: tkinter._XYScrollCommand = "", + yscrollcommand: tkinter._XYScrollCommand = "", ) -> None: ... @overload def configure( @@ -1158,9 +1160,10 @@ class Treeview(Widget, tkinter.XView, tkinter.YView): def tag_has(self, tagname: str, item: str | int) -> bool: ... class LabeledScale(Frame): - label: Incomplete - scale: Incomplete - # TODO: don't any-type **kw. That goes to Frame.__init__. + label: Label + scale: Scale + # This should be kept in sync with tkinter.ttk.Frame.__init__() + # (all the keyword-only args except compound are from there) def __init__( self, master: tkinter.Misc | None = None, @@ -1168,8 +1171,18 @@ class LabeledScale(Frame): from_: float = 0, to: float = 10, *, - compound: Literal["top", "bottom"] = ..., - **kw, + border: tkinter._ScreenUnits = ..., + borderwidth: tkinter._ScreenUnits = ..., + class_: str = "", + compound: Literal["top", "bottom"] = "top", + cursor: tkinter._Cursor = "", + height: tkinter._ScreenUnits = 0, + name: str = ..., + padding: _Padding = ..., + relief: tkinter._Relief = ..., + style: str = "", + takefocus: tkinter._TakeFocusValue = "", + width: tkinter._ScreenUnits = 0, ) -> None: ... # destroy is overridden, signature does not change value: Any @@ -1177,15 +1190,15 @@ class LabeledScale(Frame): class OptionMenu(Menubutton): def __init__( self, - master, - variable, + master: tkinter.Misc | None, + variable: tkinter.StringVar, default: str | None = None, *values: str, # rest of these are keyword-only because *args syntax used above - style: str = ..., - direction: Literal["above", "below", "left", "right", "flush"] = ..., - command: Callable[[tkinter.StringVar], object] | None = ..., + style: str = "", + direction: Literal["above", "below", "left", "right", "flush"] = "below", + command: Callable[[tkinter.StringVar], object] | None = None, ) -> None: ... # configure, config, cget, destroy are inherited from Menubutton # destroy and __setitem__ are overridden, signature does not change - def set_menu(self, default: Incomplete | None = None, *values) -> None: ... + def set_menu(self, default: str | None = None, *values: str) -> None: ... diff --git a/mypy/typeshed/stdlib/typing.pyi b/mypy/typeshed/stdlib/typing.pyi index 9fef9d3922f5..5d01be539016 100644 --- a/mypy/typeshed/stdlib/typing.pyi +++ b/mypy/typeshed/stdlib/typing.pyi @@ -273,6 +273,7 @@ if sys.version_info >= (3, 10): def __or__(self, right: Any) -> _SpecialForm: ... def __ror__(self, left: Any) -> _SpecialForm: ... + Concatenate: _SpecialForm TypeAlias: _SpecialForm TypeGuard: _SpecialForm @@ -864,6 +865,7 @@ class NamedTuple(tuple[Any, ...]): # So we only add it to the stub on 3.12+. if sys.version_info >= (3, 12): __orig_bases__: ClassVar[tuple[Any, ...]] + @overload def __init__(self, __typename: str, __fields: Iterable[tuple[str, Any]]) -> None: ... @overload @@ -885,6 +887,7 @@ class _TypedDict(Mapping[str, object], metaclass=ABCMeta): # so we only add it to the stub on 3.12+ if sys.version_info >= (3, 12): __orig_bases__: ClassVar[tuple[Any, ...]] + def copy(self) -> typing_extensions.Self: ... # Using Never so that only calls using mypy plugin hook that specialize the signature # can go through. diff --git a/mypy/typeshed/stdlib/unicodedata.pyi b/mypy/typeshed/stdlib/unicodedata.pyi index 35ab6d609a19..5c6749c8a1ae 100644 --- a/mypy/typeshed/stdlib/unicodedata.pyi +++ b/mypy/typeshed/stdlib/unicodedata.pyi @@ -11,6 +11,8 @@ if sys.version_info < (3, 10): _T = TypeVar("_T") +_NormalizationForm: TypeAlias = Literal["NFC", "NFD", "NFKC", "NFKD"] + def bidirectional(__chr: str) -> str: ... def category(__chr: str) -> str: ... def combining(__chr: str) -> int: ... @@ -27,14 +29,14 @@ def digit(__chr: str, __default: _T) -> int | _T: ... _EastAsianWidth: TypeAlias = Literal["F", "H", "W", "Na", "A", "N"] def east_asian_width(__chr: str) -> _EastAsianWidth: ... -def is_normalized(__form: str, __unistr: str) -> bool: ... +def is_normalized(__form: _NormalizationForm, __unistr: str) -> bool: ... def lookup(__name: str | ReadOnlyBuffer) -> str: ... def mirrored(__chr: str) -> int: ... @overload def name(__chr: str) -> str: ... @overload def name(__chr: str, __default: _T) -> str | _T: ... -def normalize(__form: str, __unistr: str) -> str: ... +def normalize(__form: _NormalizationForm, __unistr: str) -> str: ... @overload def numeric(__chr: str) -> float: ... @overload @@ -57,14 +59,14 @@ class UCD: @overload def digit(self, __chr: str, __default: _T) -> int | _T: ... def east_asian_width(self, __chr: str) -> _EastAsianWidth: ... - def is_normalized(self, __form: str, __unistr: str) -> bool: ... + def is_normalized(self, __form: _NormalizationForm, __unistr: str) -> bool: ... def lookup(self, __name: str | ReadOnlyBuffer) -> str: ... def mirrored(self, __chr: str) -> int: ... @overload def name(self, __chr: str) -> str: ... @overload def name(self, __chr: str, __default: _T) -> str | _T: ... - def normalize(self, __form: str, __unistr: str) -> str: ... + def normalize(self, __form: _NormalizationForm, __unistr: str) -> str: ... @overload def numeric(self, __chr: str) -> float: ... @overload diff --git a/mypy/typeshed/stdlib/unittest/result.pyi b/mypy/typeshed/stdlib/unittest/result.pyi index dfc505936f59..436fabf20c65 100644 --- a/mypy/typeshed/stdlib/unittest/result.pyi +++ b/mypy/typeshed/stdlib/unittest/result.pyi @@ -27,6 +27,7 @@ class TestResult: tb_locals: bool if sys.version_info >= (3, 12): collectedDurations: _DurationsType + def __init__(self, stream: TextIO | None = None, descriptions: bool | None = None, verbosity: int | None = None) -> None: ... def printErrors(self) -> None: ... def wasSuccessful(self) -> bool: ... From 2e5174c82317068645ec888c36902bd19ffcd49d Mon Sep 17 00:00:00 2001 From: Marc Mueller <30130371+cdce8p@users.noreply.github.com> Date: Fri, 16 Feb 2024 15:01:15 +0100 Subject: [PATCH 14/54] Add basic support for recursive TypeVar defaults (PEP 696) (#16878) Ref: https://github.com/python/mypy/issues/14851 --- mypy/applytype.py | 13 +++- mypy/expandtype.py | 9 +++ mypy/semanal.py | 9 +++ mypy/tvar_scope.py | 22 ++++++ mypy/typetraverser.py | 6 +- test-data/unit/check-typevar-defaults.test | 78 ++++++++++++++++++++++ 6 files changed, 133 insertions(+), 4 deletions(-) diff --git a/mypy/applytype.py b/mypy/applytype.py index b00372855d9c..e14906fa2772 100644 --- a/mypy/applytype.py +++ b/mypy/applytype.py @@ -147,7 +147,18 @@ def apply_generic_arguments( # TODO: move apply_poly() logic from checkexpr.py here when new inference # becomes universally used (i.e. in all passes + in unification). # With this new logic we can actually *add* some new free variables. - remaining_tvars = [tv for tv in tvars if tv.id not in id_to_type] + remaining_tvars: list[TypeVarLikeType] = [] + for tv in tvars: + if tv.id in id_to_type: + continue + if not tv.has_default(): + remaining_tvars.append(tv) + continue + # TypeVarLike isn't in id_to_type mapping. + # Only expand the TypeVar default here. + typ = expand_type(tv, id_to_type) + assert isinstance(typ, TypeVarLikeType) + remaining_tvars.append(typ) return callable.copy_modified( ret_type=expand_type(callable.ret_type, id_to_type), diff --git a/mypy/expandtype.py b/mypy/expandtype.py index d2d294fb77f3..3bf45854b2a0 100644 --- a/mypy/expandtype.py +++ b/mypy/expandtype.py @@ -179,6 +179,7 @@ class ExpandTypeVisitor(TrivialSyntheticTypeTranslator): def __init__(self, variables: Mapping[TypeVarId, Type]) -> None: self.variables = variables + self.recursive_tvar_guard: dict[TypeVarId, Type | None] = {} def visit_unbound_type(self, t: UnboundType) -> Type: return t @@ -226,6 +227,14 @@ def visit_type_var(self, t: TypeVarType) -> Type: # TODO: do we really need to do this? # If I try to remove this special-casing ~40 tests fail on reveal_type(). return repl.copy_modified(last_known_value=None) + if isinstance(repl, TypeVarType) and repl.has_default(): + if (tvar_id := repl.id) in self.recursive_tvar_guard: + return self.recursive_tvar_guard[tvar_id] or repl + self.recursive_tvar_guard[tvar_id] = None + repl = repl.accept(self) + if isinstance(repl, TypeVarType): + repl.default = repl.default.accept(self) + self.recursive_tvar_guard[tvar_id] = repl return repl def visit_param_spec(self, t: ParamSpecType) -> Type: diff --git a/mypy/semanal.py b/mypy/semanal.py index 4bf9f0c3eabb..aeceb644fe52 100644 --- a/mypy/semanal.py +++ b/mypy/semanal.py @@ -1954,6 +1954,15 @@ class Foo(Bar, Generic[T]): ... del base_type_exprs[i] tvar_defs: list[TypeVarLikeType] = [] for name, tvar_expr in declared_tvars: + tvar_expr_default = tvar_expr.default + if isinstance(tvar_expr_default, UnboundType): + # TODO: - detect out of order and self-referencing TypeVars + # - nested default types, e.g. list[T1] + n = self.lookup_qualified( + tvar_expr_default.name, tvar_expr_default, suppress_errors=True + ) + if n is not None and (default := self.tvar_scope.get_binding(n)) is not None: + tvar_expr.default = default tvar_def = self.tvar_scope.bind_new(name, tvar_expr) tvar_defs.append(tvar_def) return base_type_exprs, tvar_defs, is_protocol diff --git a/mypy/tvar_scope.py b/mypy/tvar_scope.py index c7a653a1552d..4dc663df0399 100644 --- a/mypy/tvar_scope.py +++ b/mypy/tvar_scope.py @@ -15,6 +15,26 @@ TypeVarTupleType, TypeVarType, ) +from mypy.typetraverser import TypeTraverserVisitor + + +class TypeVarLikeNamespaceSetter(TypeTraverserVisitor): + """Set namespace for all TypeVarLikeTypes types.""" + + def __init__(self, namespace: str) -> None: + self.namespace = namespace + + def visit_type_var(self, t: TypeVarType) -> None: + t.id.namespace = self.namespace + super().visit_type_var(t) + + def visit_param_spec(self, t: ParamSpecType) -> None: + t.id.namespace = self.namespace + return super().visit_param_spec(t) + + def visit_type_var_tuple(self, t: TypeVarTupleType) -> None: + t.id.namespace = self.namespace + super().visit_type_var_tuple(t) class TypeVarLikeScope: @@ -88,6 +108,8 @@ def bind_new(self, name: str, tvar_expr: TypeVarLikeExpr) -> TypeVarLikeType: i = self.func_id # TODO: Consider also using namespaces for functions namespace = "" + tvar_expr.default.accept(TypeVarLikeNamespaceSetter(namespace)) + if isinstance(tvar_expr, TypeVarExpr): tvar_def: TypeVarLikeType = TypeVarType( name=name, diff --git a/mypy/typetraverser.py b/mypy/typetraverser.py index d9ab54871f4a..1ff5f6685eb8 100644 --- a/mypy/typetraverser.py +++ b/mypy/typetraverser.py @@ -61,16 +61,16 @@ def visit_type_var(self, t: TypeVarType) -> None: # Note that type variable values and upper bound aren't treated as # components, since they are components of the type variable # definition. We want to traverse everything just once. - pass + t.default.accept(self) def visit_param_spec(self, t: ParamSpecType) -> None: - pass + t.default.accept(self) def visit_parameters(self, t: Parameters) -> None: self.traverse_types(t.arg_types) def visit_type_var_tuple(self, t: TypeVarTupleType) -> None: - pass + t.default.accept(self) def visit_literal_type(self, t: LiteralType) -> None: t.fallback.accept(self) diff --git a/test-data/unit/check-typevar-defaults.test b/test-data/unit/check-typevar-defaults.test index 544bc59494b3..1a08823cb692 100644 --- a/test-data/unit/check-typevar-defaults.test +++ b/test-data/unit/check-typevar-defaults.test @@ -349,6 +349,84 @@ def func_c4( reveal_type(m) # N: Revealed type is "__main__.ClassC4[builtins.int, builtins.float]" [builtins fixtures/tuple.pyi] +[case testTypeVarDefaultsClassRecursive1] +# flags: --disallow-any-generics +from typing import Generic, TypeVar + +T1 = TypeVar("T1", default=str) +T2 = TypeVar("T2", default=T1) +T3 = TypeVar("T3", default=T2) + +class ClassD1(Generic[T1, T2]): ... + +def func_d1( + a: ClassD1, + b: ClassD1[int], + c: ClassD1[int, float] +) -> None: + reveal_type(a) # N: Revealed type is "__main__.ClassD1[builtins.str, builtins.str]" + reveal_type(b) # N: Revealed type is "__main__.ClassD1[builtins.int, builtins.int]" + reveal_type(c) # N: Revealed type is "__main__.ClassD1[builtins.int, builtins.float]" + + k = ClassD1() + reveal_type(k) # N: Revealed type is "__main__.ClassD1[builtins.str, builtins.str]" + l = ClassD1[int]() + reveal_type(l) # N: Revealed type is "__main__.ClassD1[builtins.int, builtins.int]" + m = ClassD1[int, float]() + reveal_type(m) # N: Revealed type is "__main__.ClassD1[builtins.int, builtins.float]" + +class ClassD2(Generic[T1, T2, T3]): ... + +def func_d2( + a: ClassD2, + b: ClassD2[int], + c: ClassD2[int, float], + d: ClassD2[int, float, str], +) -> None: + reveal_type(a) # N: Revealed type is "__main__.ClassD2[builtins.str, builtins.str, builtins.str]" + reveal_type(b) # N: Revealed type is "__main__.ClassD2[builtins.int, builtins.int, builtins.int]" + reveal_type(c) # N: Revealed type is "__main__.ClassD2[builtins.int, builtins.float, builtins.float]" + reveal_type(d) # N: Revealed type is "__main__.ClassD2[builtins.int, builtins.float, builtins.str]" + + k = ClassD2() + reveal_type(k) # N: Revealed type is "__main__.ClassD2[builtins.str, builtins.str, builtins.str]" + l = ClassD2[int]() + reveal_type(l) # N: Revealed type is "__main__.ClassD2[builtins.int, builtins.int, builtins.int]" + m = ClassD2[int, float]() + reveal_type(m) # N: Revealed type is "__main__.ClassD2[builtins.int, builtins.float, builtins.float]" + n = ClassD2[int, float, str]() + reveal_type(n) # N: Revealed type is "__main__.ClassD2[builtins.int, builtins.float, builtins.str]" + +[case testTypeVarDefaultsClassRecursiveMultipleFiles] +# flags: --disallow-any-generics +from typing import Generic, TypeVar +from file2 import T as T2 + +T = TypeVar('T', default=T2) + +class ClassG1(Generic[T2, T]): + pass + +def func( + a: ClassG1, + b: ClassG1[str], + c: ClassG1[str, float], +) -> None: + reveal_type(a) # N: Revealed type is "__main__.ClassG1[builtins.int, builtins.int]" + reveal_type(b) # N: Revealed type is "__main__.ClassG1[builtins.str, builtins.str]" + reveal_type(c) # N: Revealed type is "__main__.ClassG1[builtins.str, builtins.float]" + + k = ClassG1() + reveal_type(k) # N: Revealed type is "__main__.ClassG1[builtins.int, builtins.int]" + l = ClassG1[str]() + reveal_type(l) # N: Revealed type is "__main__.ClassG1[builtins.str, builtins.str]" + m = ClassG1[str, float]() + reveal_type(m) # N: Revealed type is "__main__.ClassG1[builtins.str, builtins.float]" + +[file file2.py] +from typing import TypeVar +T = TypeVar('T', default=int) + [case testTypeVarDefaultsTypeAlias1] # flags: --disallow-any-generics from typing import Any, Dict, List, Tuple, TypeVar, Union From bfbac5efbad32305b2948b82f95c9a8c34d44d34 Mon Sep 17 00:00:00 2001 From: Ali Hamdan Date: Fri, 16 Feb 2024 23:34:44 +0100 Subject: [PATCH 15/54] stubgen: Fix generated dataclass `__init__` signature (#16906) Fixes #16811 stubgen was swallowing default values for `__init__` methods generated by the dataclass plugin making their signature incorrect. This is because the plugin does not include the argument's initializer in the generated signature. I changed it to include a dummy ellipsis so that stubgen can generate correct code. I also fixed arguments added by the dataclass plugin with the invalid names `*` and `**` to have the valid and unique names `*generated_args` and `**generated_kwargs` (with extra underscores to make them unique if necessary). This removes the need for the hack to special case them in stubgen and is less confusing for someone looking at them in a stub file. --- mypy/plugins/dataclasses.py | 17 +++++++--- mypy/stubgen.py | 11 ------- test-data/unit/check-dataclasses.test | 6 ++++ test-data/unit/stubgen.test | 47 ++++++++++++++++++--------- 4 files changed, 50 insertions(+), 31 deletions(-) diff --git a/mypy/plugins/dataclasses.py b/mypy/plugins/dataclasses.py index 685d1b342055..dead512a2202 100644 --- a/mypy/plugins/dataclasses.py +++ b/mypy/plugins/dataclasses.py @@ -24,6 +24,7 @@ Context, DataclassTransformSpec, Decorator, + EllipsisExpr, Expression, FuncDef, FuncItem, @@ -149,13 +150,13 @@ def to_argument( return Argument( variable=self.to_var(current_info), type_annotation=self.expand_type(current_info), - initializer=None, + initializer=EllipsisExpr() if self.has_default else None, # Only used by stubgen kind=arg_kind, ) def expand_type(self, current_info: TypeInfo) -> Type | None: if self.type is not None and self.info.self_type is not None: - # In general, it is not safe to call `expand_type()` during semantic analyzis, + # In general, it is not safe to call `expand_type()` during semantic analysis, # however this plugin is called very late, so all types should be fully ready. # Also, it is tricky to avoid eager expansion of Self types here (e.g. because # we serialize attributes). @@ -269,11 +270,17 @@ def transform(self) -> bool: if arg.kind == ARG_POS: arg.kind = ARG_OPT - nameless_var = Var("") + existing_args_names = {arg.variable.name for arg in args} + gen_args_name = "generated_args" + while gen_args_name in existing_args_names: + gen_args_name += "_" + gen_kwargs_name = "generated_kwargs" + while gen_kwargs_name in existing_args_names: + gen_kwargs_name += "_" args = [ - Argument(nameless_var, AnyType(TypeOfAny.explicit), None, ARG_STAR), + Argument(Var(gen_args_name), AnyType(TypeOfAny.explicit), None, ARG_STAR), *args, - Argument(nameless_var, AnyType(TypeOfAny.explicit), None, ARG_STAR2), + Argument(Var(gen_kwargs_name), AnyType(TypeOfAny.explicit), None, ARG_STAR2), ] add_method_to_class( diff --git a/mypy/stubgen.py b/mypy/stubgen.py index 36e8bd2acfb4..279f0569174a 100755 --- a/mypy/stubgen.py +++ b/mypy/stubgen.py @@ -537,17 +537,6 @@ def _get_func_args(self, o: FuncDef, ctx: FunctionContext) -> list[ArgSig]: if new_args is not None: args = new_args - is_dataclass_generated = ( - self.analyzed and self.processing_dataclass and o.info.names[o.name].plugin_generated - ) - if o.name == "__init__" and is_dataclass_generated and "**" in [a.name for a in args]: - # The dataclass plugin generates invalid nameless "*" and "**" arguments - new_name = "".join(a.name.strip("*") for a in args) - for arg in args: - if arg.name == "*": - arg.name = f"*{new_name}_" # this name is guaranteed to be unique - elif arg.name == "**": - arg.name = f"**{new_name}__" # same here return args def _get_func_return(self, o: FuncDef, ctx: FunctionContext) -> str | None: diff --git a/test-data/unit/check-dataclasses.test b/test-data/unit/check-dataclasses.test index b57fe8f548c4..a055507cdd78 100644 --- a/test-data/unit/check-dataclasses.test +++ b/test-data/unit/check-dataclasses.test @@ -1610,10 +1610,16 @@ B: Any @dataclass class A(B): a: int +@dataclass +class C(B): + generated_args: int + generated_kwargs: int A(a=1, b=2) A(1) A(a="foo") # E: Argument "a" to "A" has incompatible type "str"; expected "int" +C(generated_args="foo", generated_kwargs="bar") # E: Argument "generated_args" to "C" has incompatible type "str"; expected "int" \ + # E: Argument "generated_kwargs" to "C" has incompatible type "str"; expected "int" [builtins fixtures/dataclasses.pyi] [case testDataclassesCallableFrozen] diff --git a/test-data/unit/stubgen.test b/test-data/unit/stubgen.test index c56f6b40b74d..3503fd4ad808 100644 --- a/test-data/unit/stubgen.test +++ b/test-data/unit/stubgen.test @@ -4083,20 +4083,21 @@ class W: ... class V: ... [case testDataclass_semanal] -from dataclasses import dataclass, InitVar +from dataclasses import InitVar, dataclass, field from typing import ClassVar @dataclass class X: a: int - b: str = "hello" - c: ClassVar - d: ClassVar = 200 + b: InitVar[str] + c: str = "hello" + d: ClassVar + e: ClassVar = 200 f: list[int] = field(init=False, default_factory=list) g: int = field(default=2, kw_only=True) h: int = 1 - i: InitVar[str] - j: InitVar = 100 + i: InitVar = 100 + j: list[int] = field(default_factory=list) non_field = None @dataclass(init=False, repr=False, frozen=True) @@ -4109,23 +4110,24 @@ from typing import ClassVar @dataclass class X: a: int - b: str = ... - c: ClassVar - d: ClassVar = ... + b: InitVar[str] + c: str = ... + d: ClassVar + e: ClassVar = ... f: list[int] = ... g: int = ... h: int = ... - i: InitVar[str] - j: InitVar = ... + i: InitVar = ... + j: list[int] = ... non_field = ... - def __init__(self, a, b, f, g, h, i, j) -> None: ... + def __init__(self, a, b, c=..., *, g=..., h=..., i=..., j=...) -> None: ... @dataclass(init=False, repr=False, frozen=True) class Y: ... [case testDataclassWithKwOnlyField_semanal] # flags: --python-version=3.10 -from dataclasses import dataclass, InitVar, KW_ONLY +from dataclasses import dataclass, field, InitVar, KW_ONLY from typing import ClassVar @dataclass @@ -4162,7 +4164,7 @@ class X: i: InitVar[str] j: InitVar = ... non_field = ... - def __init__(self, a, b, f, g, *, h, i, j) -> None: ... + def __init__(self, a, b=..., *, g=..., h=..., i, j=...) -> None: ... @dataclass(init=False, repr=False, frozen=True) class Y: ... @@ -4193,6 +4195,13 @@ import missing class X(missing.Base): a: int +@dataclass +class Y(missing.Base): + generated_args: str + generated_args_: str + generated_kwargs: float + generated_kwargs_: float + [out] import missing from dataclasses import dataclass @@ -4200,7 +4209,15 @@ from dataclasses import dataclass @dataclass class X(missing.Base): a: int - def __init__(self, *selfa_, a, **selfa__) -> None: ... + def __init__(self, *generated_args, a, **generated_kwargs) -> None: ... + +@dataclass +class Y(missing.Base): + generated_args: str + generated_args_: str + generated_kwargs: float + generated_kwargs_: float + def __init__(self, *generated_args__, generated_args, generated_args_, generated_kwargs, generated_kwargs_, **generated_kwargs__) -> None: ... [case testAlwaysUsePEP604Union] import typing From 17271e57cfce5c441c3e481d20b28ca7484db231 Mon Sep 17 00:00:00 2001 From: Edward Paget Date: Sat, 17 Feb 2024 17:32:11 -0600 Subject: [PATCH 16/54] Fix narrowing on match with function subject (#16503) Fixes #12998 mypy can't narrow match statements with functions subjects because the callexpr node is not a literal node. This adds a 'dummy' literal node that the match statement visitor can use to do the type narrowing. The python grammar describes the the match subject as a named expression so this uses that nameexpr node as it's literal. --------- Co-authored-by: hauntsaninja --- mypy/checker.py | 19 ++++++++++++++++--- test-data/unit/check-python310.test | 15 +++++++++++++++ 2 files changed, 31 insertions(+), 3 deletions(-) diff --git a/mypy/checker.py b/mypy/checker.py index 391f28e93b1d..56be3db3f9e7 100644 --- a/mypy/checker.py +++ b/mypy/checker.py @@ -5053,6 +5053,19 @@ def visit_continue_stmt(self, s: ContinueStmt) -> None: return def visit_match_stmt(self, s: MatchStmt) -> None: + named_subject: Expression + if isinstance(s.subject, CallExpr): + # Create a dummy subject expression to handle cases where a match statement's subject + # is not a literal value. This lets us correctly narrow types and check exhaustivity + # This is hack! + id = s.subject.callee.fullname if isinstance(s.subject.callee, RefExpr) else "" + name = "dummy-match-" + id + v = Var(name) + named_subject = NameExpr(name) + named_subject.node = v + else: + named_subject = s.subject + with self.binder.frame_context(can_skip=False, fall_through=0): subject_type = get_proper_type(self.expr_checker.accept(s.subject)) @@ -5071,7 +5084,7 @@ def visit_match_stmt(self, s: MatchStmt) -> None: # The second pass narrows down the types and type checks bodies. for p, g, b in zip(s.patterns, s.guards, s.bodies): current_subject_type = self.expr_checker.narrow_type_from_binder( - s.subject, subject_type + named_subject, subject_type ) pattern_type = self.pattern_checker.accept(p, current_subject_type) with self.binder.frame_context(can_skip=True, fall_through=2): @@ -5082,7 +5095,7 @@ def visit_match_stmt(self, s: MatchStmt) -> None: else_map: TypeMap = {} else: pattern_map, else_map = conditional_types_to_typemaps( - s.subject, pattern_type.type, pattern_type.rest_type + named_subject, pattern_type.type, pattern_type.rest_type ) self.remove_capture_conflicts(pattern_type.captures, inferred_types) self.push_type_map(pattern_map) @@ -5110,7 +5123,7 @@ def visit_match_stmt(self, s: MatchStmt) -> None: and expr.fullname == case_target.fullname ): continue - type_map[s.subject] = type_map[expr] + type_map[named_subject] = type_map[expr] self.push_type_map(guard_map) self.accept(b) diff --git a/test-data/unit/check-python310.test b/test-data/unit/check-python310.test index cbb26a130738..b0e27fe1e3a0 100644 --- a/test-data/unit/check-python310.test +++ b/test-data/unit/check-python310.test @@ -1139,6 +1139,21 @@ match m: reveal_type(a) # N: Revealed type is "builtins.str" +[case testMatchCapturePatternFromFunctionReturningUnion] +def func1(arg: bool) -> str | int: ... +def func2(arg: bool) -> bytes | int: ... + +def main() -> None: + match func1(True): + case str(a): + match func2(True): + case c: + reveal_type(a) # N: Revealed type is "builtins.str" + reveal_type(c) # N: Revealed type is "Union[builtins.bytes, builtins.int]" + reveal_type(a) # N: Revealed type is "builtins.str" + case a: + reveal_type(a) # N: Revealed type is "builtins.int" + -- Guards -- [case testMatchSimplePatternGuard] From eb84794bd02b20e051103f91b6d1dcb01c0e342c Mon Sep 17 00:00:00 2001 From: Alex Waygood Date: Sun, 18 Feb 2024 13:33:59 +0000 Subject: [PATCH 17/54] FIx stubtest's tests to work with the latest version of `typing_extensions` (#16928) Stubtest's tests will start failing when `typing_extensions==4.10.0` comes out, due to some new `ClassVar`s on `typing_extensions.TypedDict`. This PR fixes that. Fixes https://github.com/python/typing_extensions/issues/339. Note: there's no need to cherry-pick this to the `release-1.9.0` branch, since the daily workflow `typing_extensions` uses runs mypy's tests using the mypy `master` branch. --- test-data/unit/lib-stub/typing_extensions.pyi | 2 ++ 1 file changed, 2 insertions(+) diff --git a/test-data/unit/lib-stub/typing_extensions.pyi b/test-data/unit/lib-stub/typing_extensions.pyi index 7aca6fad1b42..68dd985cfe2a 100644 --- a/test-data/unit/lib-stub/typing_extensions.pyi +++ b/test-data/unit/lib-stub/typing_extensions.pyi @@ -61,6 +61,8 @@ class _TypedDict(Mapping[str, object]): __optional_keys__: frozenset[str] __readonly_keys__: frozenset[str] __mutable_keys__: frozenset[str] + __closed__: bool + __extra_items__: Any __total__: bool def TypedDict(typename: str, fields: Dict[str, Type[_T]], *, total: Any = ...) -> Type[dict]: ... From 46ebacae0ca5b464a7d422ac1e3370cae32c135a Mon Sep 17 00:00:00 2001 From: Ali Hamdan Date: Sun, 18 Feb 2024 22:32:19 +0100 Subject: [PATCH 18/54] stubgen: Replace obsolete typing aliases with builtin containers (#16780) Addresses part of #16737 This only replaces typing symbols that have equivalents in the `builtins` module. Replacing other symbols, like those from the `collections.abc` module, are a bit more complicated so I suggest we handle them separately. I also changed the default `TypedDict` module from `typing_extensions` to `typing` as typeshed dropped support for Python 3.7. --- mypy/stubgen.py | 51 ++++++---- mypy/stubutil.py | 33 ++++++- .../pybind11_fixtures/__init__.pyi | 6 +- .../pybind11_fixtures/demo.pyi | 4 +- .../pybind11_fixtures/__init__.pyi | 6 +- .../pybind11_fixtures/demo.pyi | 4 +- test-data/unit/stubgen.test | 94 +++++++++++++++---- 7 files changed, 148 insertions(+), 50 deletions(-) diff --git a/mypy/stubgen.py b/mypy/stubgen.py index 279f0569174a..7721366f5c0c 100755 --- a/mypy/stubgen.py +++ b/mypy/stubgen.py @@ -47,7 +47,7 @@ import os.path import sys import traceback -from typing import Final, Iterable +from typing import Final, Iterable, Iterator import mypy.build import mypy.mixedtraverser @@ -114,6 +114,7 @@ from mypy.stubdoc import ArgSig, FunctionSig from mypy.stubgenc import InspectionStubGenerator, generate_stub_for_c_module from mypy.stubutil import ( + TYPING_BUILTIN_REPLACEMENTS, BaseStubGenerator, CantImport, ClassInfo, @@ -289,20 +290,19 @@ def visit_call_expr(self, node: CallExpr) -> str: raise ValueError(f"Unknown argument kind {kind} in call") return f"{callee}({', '.join(args)})" + def _visit_ref_expr(self, node: NameExpr | MemberExpr) -> str: + fullname = self.stubgen.get_fullname(node) + if fullname in TYPING_BUILTIN_REPLACEMENTS: + return self.stubgen.add_name(TYPING_BUILTIN_REPLACEMENTS[fullname], require=False) + qualname = get_qualified_name(node) + self.stubgen.import_tracker.require_name(qualname) + return qualname + def visit_name_expr(self, node: NameExpr) -> str: - self.stubgen.import_tracker.require_name(node.name) - return node.name + return self._visit_ref_expr(node) def visit_member_expr(self, o: MemberExpr) -> str: - node: Expression = o - trailer = "" - while isinstance(node, MemberExpr): - trailer = "." + node.name + trailer - node = node.expr - if not isinstance(node, NameExpr): - return ERROR_MARKER - self.stubgen.import_tracker.require_name(node.name) - return node.name + trailer + return self._visit_ref_expr(o) def visit_str_expr(self, node: StrExpr) -> str: return repr(node.value) @@ -351,11 +351,17 @@ def find_defined_names(file: MypyFile) -> set[str]: return finder.names +def get_assigned_names(lvalues: Iterable[Expression]) -> Iterator[str]: + for lvalue in lvalues: + if isinstance(lvalue, NameExpr): + yield lvalue.name + elif isinstance(lvalue, TupleExpr): + yield from get_assigned_names(lvalue.items) + + class DefinitionFinder(mypy.traverser.TraverserVisitor): """Find names of things defined at the top level of a module.""" - # TODO: Assignment statements etc. - def __init__(self) -> None: # Short names of things defined at the top level. self.names: set[str] = set() @@ -368,6 +374,10 @@ def visit_func_def(self, o: FuncDef) -> None: # Don't recurse, as we only keep track of top-level definitions. self.names.add(o.name) + def visit_assignment_stmt(self, o: AssignmentStmt) -> None: + for name in get_assigned_names(o.lvalues): + self.names.add(name) + def find_referenced_names(file: MypyFile) -> set[str]: finder = ReferenceFinder() @@ -1023,10 +1033,15 @@ def is_alias_expression(self, expr: Expression, top_level: bool = True) -> bool: and isinstance(expr.node, (FuncDef, Decorator, MypyFile)) or isinstance(expr.node, TypeInfo) ) and not self.is_private_member(expr.node.fullname) - elif ( - isinstance(expr, IndexExpr) - and isinstance(expr.base, NameExpr) - and not self.is_private_name(expr.base.name) + elif isinstance(expr, IndexExpr) and ( + (isinstance(expr.base, NameExpr) and not self.is_private_name(expr.base.name)) + or ( # Also some known aliases that could be member expression + isinstance(expr.base, MemberExpr) + and not self.is_private_member(get_qualified_name(expr.base)) + and self.get_fullname(expr.base).startswith( + ("builtins.", "typing.", "typing_extensions.", "collections.abc.") + ) + ) ): if isinstance(expr.index, TupleExpr): indices = expr.index.items diff --git a/mypy/stubutil.py b/mypy/stubutil.py index 69af643efab2..410672f89d09 100644 --- a/mypy/stubutil.py +++ b/mypy/stubutil.py @@ -22,6 +22,26 @@ # Modules that may fail when imported, or that may have side effects (fully qualified). NOT_IMPORTABLE_MODULES = () +# Typing constructs to be replaced by their builtin equivalents. +TYPING_BUILTIN_REPLACEMENTS: Final = { + # From typing + "typing.Text": "builtins.str", + "typing.Tuple": "builtins.tuple", + "typing.List": "builtins.list", + "typing.Dict": "builtins.dict", + "typing.Set": "builtins.set", + "typing.FrozenSet": "builtins.frozenset", + "typing.Type": "builtins.type", + # From typing_extensions + "typing_extensions.Text": "builtins.str", + "typing_extensions.Tuple": "builtins.tuple", + "typing_extensions.List": "builtins.list", + "typing_extensions.Dict": "builtins.dict", + "typing_extensions.Set": "builtins.set", + "typing_extensions.FrozenSet": "builtins.frozenset", + "typing_extensions.Type": "builtins.type", +} + class CantImport(Exception): def __init__(self, module: str, message: str) -> None: @@ -229,6 +249,8 @@ def visit_unbound_type(self, t: UnboundType) -> str: return " | ".join([item.accept(self) for item in t.args]) if fullname == "typing.Optional": return f"{t.args[0].accept(self)} | None" + if fullname in TYPING_BUILTIN_REPLACEMENTS: + s = self.stubgen.add_name(TYPING_BUILTIN_REPLACEMENTS[fullname], require=True) if self.known_modules is not None and "." in s: # see if this object is from any of the modules that we're currently processing. # reverse sort so that subpackages come before parents: e.g. "foo.bar" before "foo". @@ -476,7 +498,7 @@ def reexport(self, name: str) -> None: def import_lines(self) -> list[str]: """The list of required import lines (as strings with python code). - In order for a module be included in this output, an indentifier must be both + In order for a module be included in this output, an identifier must be both 'required' via require_name() and 'imported' via add_import_from() or add_import() """ @@ -585,9 +607,9 @@ def __init__( # a corresponding import statement. self.known_imports = { "_typeshed": ["Incomplete"], - "typing": ["Any", "TypeVar", "NamedTuple"], + "typing": ["Any", "TypeVar", "NamedTuple", "TypedDict"], "collections.abc": ["Generator"], - "typing_extensions": ["TypedDict", "ParamSpec", "TypeVarTuple"], + "typing_extensions": ["ParamSpec", "TypeVarTuple"], } def get_sig_generators(self) -> list[SignatureGenerator]: @@ -613,7 +635,10 @@ def add_name(self, fullname: str, require: bool = True) -> str: """ module, name = fullname.rsplit(".", 1) alias = "_" + name if name in self.defined_names else None - self.import_tracker.add_import_from(module, [(name, alias)], require=require) + while alias in self.defined_names: + alias = "_" + alias + if module != "builtins" or alias: # don't import from builtins unless needed + self.import_tracker.add_import_from(module, [(name, alias)], require=require) return alias or name def add_import_line(self, line: str) -> None: diff --git a/test-data/pybind11_fixtures/expected_stubs_no_docs/pybind11_fixtures/__init__.pyi b/test-data/pybind11_fixtures/expected_stubs_no_docs/pybind11_fixtures/__init__.pyi index bb939aa5a5e7..90afb46d6d94 100644 --- a/test-data/pybind11_fixtures/expected_stubs_no_docs/pybind11_fixtures/__init__.pyi +++ b/test-data/pybind11_fixtures/expected_stubs_no_docs/pybind11_fixtures/__init__.pyi @@ -1,6 +1,6 @@ import os from . import demo as demo -from typing import List, Tuple, overload +from typing import overload class StaticMethods: def __init__(self, *args, **kwargs) -> None: ... @@ -22,6 +22,6 @@ class TestStruct: def func_incomplete_signature(*args, **kwargs): ... def func_returning_optional() -> int | None: ... -def func_returning_pair() -> Tuple[int, float]: ... +def func_returning_pair() -> tuple[int, float]: ... def func_returning_path() -> os.PathLike: ... -def func_returning_vector() -> List[float]: ... +def func_returning_vector() -> list[float]: ... diff --git a/test-data/pybind11_fixtures/expected_stubs_no_docs/pybind11_fixtures/demo.pyi b/test-data/pybind11_fixtures/expected_stubs_no_docs/pybind11_fixtures/demo.pyi index 6f164a03edcc..87b8ec0e4ad6 100644 --- a/test-data/pybind11_fixtures/expected_stubs_no_docs/pybind11_fixtures/demo.pyi +++ b/test-data/pybind11_fixtures/expected_stubs_no_docs/pybind11_fixtures/demo.pyi @@ -1,4 +1,4 @@ -from typing import ClassVar, List, overload +from typing import ClassVar, overload PI: float __version__: str @@ -47,7 +47,7 @@ class Point: def __init__(self) -> None: ... @overload def __init__(self, x: float, y: float) -> None: ... - def as_list(self) -> List[float]: ... + def as_list(self) -> list[float]: ... @overload def distance_to(self, x: float, y: float) -> float: ... @overload diff --git a/test-data/pybind11_fixtures/expected_stubs_with_docs/pybind11_fixtures/__init__.pyi b/test-data/pybind11_fixtures/expected_stubs_with_docs/pybind11_fixtures/__init__.pyi index 622e5881a147..db04bccab028 100644 --- a/test-data/pybind11_fixtures/expected_stubs_with_docs/pybind11_fixtures/__init__.pyi +++ b/test-data/pybind11_fixtures/expected_stubs_with_docs/pybind11_fixtures/__init__.pyi @@ -1,6 +1,6 @@ import os from . import demo as demo -from typing import List, Tuple, overload +from typing import overload class StaticMethods: def __init__(self, *args, **kwargs) -> None: @@ -44,9 +44,9 @@ def func_incomplete_signature(*args, **kwargs): """func_incomplete_signature() -> dummy_sub_namespace::HasNoBinding""" def func_returning_optional() -> int | None: """func_returning_optional() -> Optional[int]""" -def func_returning_pair() -> Tuple[int, float]: +def func_returning_pair() -> tuple[int, float]: """func_returning_pair() -> Tuple[int, float]""" def func_returning_path() -> os.PathLike: """func_returning_path() -> os.PathLike""" -def func_returning_vector() -> List[float]: +def func_returning_vector() -> list[float]: """func_returning_vector() -> List[float]""" diff --git a/test-data/pybind11_fixtures/expected_stubs_with_docs/pybind11_fixtures/demo.pyi b/test-data/pybind11_fixtures/expected_stubs_with_docs/pybind11_fixtures/demo.pyi index 1527225ed009..1be0bc905a43 100644 --- a/test-data/pybind11_fixtures/expected_stubs_with_docs/pybind11_fixtures/demo.pyi +++ b/test-data/pybind11_fixtures/expected_stubs_with_docs/pybind11_fixtures/demo.pyi @@ -1,4 +1,4 @@ -from typing import ClassVar, List, overload +from typing import ClassVar, overload PI: float __version__: str @@ -73,7 +73,7 @@ class Point: 2. __init__(self: pybind11_fixtures.demo.Point, x: float, y: float) -> None """ - def as_list(self) -> List[float]: + def as_list(self) -> list[float]: """as_list(self: pybind11_fixtures.demo.Point) -> List[float]""" @overload def distance_to(self, x: float, y: float) -> float: diff --git a/test-data/unit/stubgen.test b/test-data/unit/stubgen.test index 3503fd4ad808..53baa2c0ca06 100644 --- a/test-data/unit/stubgen.test +++ b/test-data/unit/stubgen.test @@ -1376,9 +1376,8 @@ x: List[collections.defaultdict] [out] import collections -from typing import List -x: List[collections.defaultdict] +x: list[collections.defaultdict] [case testAnnotationFwRefs] @@ -2216,9 +2215,9 @@ funcs: Dict[Any, Any] f = funcs[a.f] [out] from _typeshed import Incomplete -from typing import Any, Dict +from typing import Any -funcs: Dict[Any, Any] +funcs: dict[Any, Any] f: Incomplete [case testAbstractMethodNameExpr] @@ -3290,18 +3289,18 @@ def f(*args: Union[int, Tuple[int, int]]) -> int: [out] -from typing import Tuple, overload +from typing import overload class A: @overload def f(self, x: int, y: int) -> int: ... @overload - def f(self, x: Tuple[int, int]) -> int: ... + def f(self, x: tuple[int, int]) -> int: ... @overload def f(x: int, y: int) -> int: ... @overload -def f(x: Tuple[int, int]) -> int: ... +def f(x: tuple[int, int]) -> int: ... [case testOverload_fromTypingExtensionsImport] from typing import Tuple, Union @@ -3332,19 +3331,18 @@ def f(*args: Union[int, Tuple[int, int]]) -> int: [out] -from typing import Tuple from typing_extensions import overload class A: @overload def f(self, x: int, y: int) -> int: ... @overload - def f(self, x: Tuple[int, int]) -> int: ... + def f(self, x: tuple[int, int]) -> int: ... @overload def f(x: int, y: int) -> int: ... @overload -def f(x: Tuple[int, int]) -> int: ... +def f(x: tuple[int, int]) -> int: ... [case testOverload_importTyping] import typing @@ -3407,22 +3405,22 @@ class A: @typing.overload def f(self, x: int, y: int) -> int: ... @typing.overload - def f(self, x: typing.Tuple[int, int]) -> int: ... + def f(self, x: tuple[int, int]) -> int: ... @typing.overload @classmethod def g(cls, x: int, y: int) -> int: ... @typing.overload @classmethod - def g(cls, x: typing.Tuple[int, int]) -> int: ... + def g(cls, x: tuple[int, int]) -> int: ... @typing.overload def f(x: int, y: int) -> int: ... @typing.overload -def f(x: typing.Tuple[int, int]) -> int: ... +def f(x: tuple[int, int]) -> int: ... @typing_extensions.overload def g(x: int, y: int) -> int: ... @typing_extensions.overload -def g(x: typing.Tuple[int, int]) -> int: ... +def g(x: tuple[int, int]) -> int: ... [case testOverload_importTypingAs] import typing as t @@ -3485,22 +3483,22 @@ class A: @t.overload def f(self, x: int, y: int) -> int: ... @t.overload - def f(self, x: t.Tuple[int, int]) -> int: ... + def f(self, x: tuple[int, int]) -> int: ... @t.overload @classmethod def g(cls, x: int, y: int) -> int: ... @t.overload @classmethod - def g(cls, x: t.Tuple[int, int]) -> int: ... + def g(cls, x: tuple[int, int]) -> int: ... @t.overload def f(x: int, y: int) -> int: ... @t.overload -def f(x: t.Tuple[int, int]) -> int: ... +def f(x: tuple[int, int]) -> int: ... @te.overload def g(x: int, y: int) -> int: ... @te.overload -def g(x: t.Tuple[int, int]) -> int: ... +def g(x: tuple[int, int]) -> int: ... [case testOverloadFromImportAlias] from typing import overload as t_overload @@ -4249,6 +4247,66 @@ o = int | None def f1(a: int | tuple[int, int | None] | None) -> int: ... def f2(a: int | x.Union[int, int] | float | None) -> int: ... +[case testTypingBuiltinReplacements] +import typing +import typing as t +from typing import Tuple +import typing_extensions +import typing_extensions as te +from typing_extensions import List, Type + +# builtins are not builtins +tuple = int +[list,] = float +dict, set, frozenset = str, float, int + +x: Tuple[t.Text, t.FrozenSet[typing.Type[float]]] +y: typing.List[int] +z: t.Dict[str, float] +v: typing.Set[int] +w: List[typing_extensions.Dict[te.FrozenSet[Type[int]], te.Tuple[te.Set[te.Text], ...]]] + +x_alias = Tuple[str, ...] +y_alias = typing.List[int] +z_alias = t.Dict[str, float] +v_alias = typing.Set[int] +w_alias = List[typing_extensions.Dict[str, te.Tuple[int, ...]]] + +[out] +from _typeshed import Incomplete +from builtins import dict as _dict, frozenset as _frozenset, list as _list, set as _set, tuple as _tuple + +tuple = int +list: Incomplete +dict: Incomplete +set: Incomplete +frozenset: Incomplete +x: _tuple[str, _frozenset[type[float]]] +y: _list[int] +z: _dict[str, float] +v: _set[int] +w: _list[_dict[_frozenset[type[int]], _tuple[_set[str], ...]]] +x_alias = _tuple[str, ...] +y_alias = _list[int] +z_alias = _dict[str, float] +v_alias = _set[int] +w_alias = _list[_dict[str, _tuple[int, ...]]] + +[case testHandlingNameCollisions] +# flags: --include-private +from typing import Tuple +tuple = int +_tuple = range +__tuple = map +x: Tuple[int, str] +[out] +from builtins import tuple as ___tuple + +tuple = int +_tuple = range +__tuple = map +x: ___tuple[int, str] + [case testPEP570PosOnlyParams] def f(x=0, /): ... def f1(x: int, /): ... From 790e8a73d8671a41cae419b4ea07579bfb2bc292 Mon Sep 17 00:00:00 2001 From: Marc Mueller <30130371+cdce8p@users.noreply.github.com> Date: Tue, 20 Feb 2024 01:02:49 +0100 Subject: [PATCH 19/54] Error handling for recursive TypeVar defaults (PEP 696) (#16925) This PR adds some additional error handling for recursive TypeVar defaults. Open issue for future PRs: - Expanding nested recursive defaults, e.g. `T2 = list[T1 = str]` - Scope binding, especially for TypeAliasTypes Ref: https://github.com/python/mypy/issues/14851 --- mypy/messages.py | 9 ++ mypy/semanal.py | 47 ++++++-- mypy/typeanal.py | 36 +++++- mypy/types.py | 9 ++ test-data/unit/check-typevar-defaults.test | 134 ++++++++++++++++++++- 5 files changed, 223 insertions(+), 12 deletions(-) diff --git a/mypy/messages.py b/mypy/messages.py index c107e874f4fc..db6c91ba9008 100644 --- a/mypy/messages.py +++ b/mypy/messages.py @@ -2059,6 +2059,15 @@ def impossible_intersection( template.format(formatted_base_class_list, reason), context, code=codes.UNREACHABLE ) + def tvar_without_default_type( + self, tvar_name: str, last_tvar_name_with_default: str, context: Context + ) -> None: + self.fail( + f'"{tvar_name}" cannot appear after "{last_tvar_name_with_default}" ' + "in type parameter list because it has no default type", + context, + ) + def report_protocol_problems( self, subtype: Instance | TupleType | TypedDictType | TypeType | CallableType, diff --git a/mypy/semanal.py b/mypy/semanal.py index aeceb644fe52..38d5ddec0818 100644 --- a/mypy/semanal.py +++ b/mypy/semanal.py @@ -226,6 +226,7 @@ SELF_TYPE_NAMES, FindTypeVarVisitor, TypeAnalyser, + TypeVarDefaultTranslator, TypeVarLikeList, analyze_type_alias, check_for_explicit_any, @@ -252,6 +253,7 @@ TPDICT_NAMES, TYPE_ALIAS_NAMES, TYPE_CHECK_ONLY_NAMES, + TYPE_VAR_LIKE_NAMES, TYPED_NAMEDTUPLE_NAMES, AnyType, CallableType, @@ -1953,17 +1955,19 @@ class Foo(Bar, Generic[T]): ... defn.removed_base_type_exprs.append(defn.base_type_exprs[i]) del base_type_exprs[i] tvar_defs: list[TypeVarLikeType] = [] + last_tvar_name_with_default: str | None = None for name, tvar_expr in declared_tvars: - tvar_expr_default = tvar_expr.default - if isinstance(tvar_expr_default, UnboundType): - # TODO: - detect out of order and self-referencing TypeVars - # - nested default types, e.g. list[T1] - n = self.lookup_qualified( - tvar_expr_default.name, tvar_expr_default, suppress_errors=True - ) - if n is not None and (default := self.tvar_scope.get_binding(n)) is not None: - tvar_expr.default = default + tvar_expr.default = tvar_expr.default.accept( + TypeVarDefaultTranslator(self, tvar_expr.name, context) + ) tvar_def = self.tvar_scope.bind_new(name, tvar_expr) + if last_tvar_name_with_default is not None and not tvar_def.has_default(): + self.msg.tvar_without_default_type( + tvar_def.name, last_tvar_name_with_default, context + ) + tvar_def.default = AnyType(TypeOfAny.from_error) + elif tvar_def.has_default(): + last_tvar_name_with_default = tvar_def.name tvar_defs.append(tvar_def) return base_type_exprs, tvar_defs, is_protocol @@ -2855,6 +2859,10 @@ def visit_assignment_stmt(self, s: AssignmentStmt) -> None: with self.allow_unbound_tvars_set(): s.rvalue.accept(self) self.basic_type_applications = old_basic_type_applications + elif self.can_possibly_be_typevarlike_declaration(s): + # Allow unbound tvars inside TypeVarLike defaults to be evaluated later + with self.allow_unbound_tvars_set(): + s.rvalue.accept(self) else: s.rvalue.accept(self) @@ -3031,6 +3039,16 @@ def can_possibly_be_type_form(self, s: AssignmentStmt) -> bool: # Something that looks like Foo = Bar[Baz, ...] return True + def can_possibly_be_typevarlike_declaration(self, s: AssignmentStmt) -> bool: + """Check if r.h.s. can be a TypeVarLike declaration.""" + if len(s.lvalues) != 1 or not isinstance(s.lvalues[0], NameExpr): + return False + if not isinstance(s.rvalue, CallExpr) or not isinstance(s.rvalue.callee, NameExpr): + return False + ref = s.rvalue.callee + ref.accept(self) + return ref.fullname in TYPE_VAR_LIKE_NAMES + def is_type_ref(self, rv: Expression, bare: bool = False) -> bool: """Does this expression refer to a type? @@ -3515,9 +3533,20 @@ def analyze_alias( found_type_vars = self.find_type_var_likes(typ) tvar_defs: list[TypeVarLikeType] = [] namespace = self.qualified_name(name) + last_tvar_name_with_default: str | None = None with self.tvar_scope_frame(self.tvar_scope.class_frame(namespace)): for name, tvar_expr in found_type_vars: + tvar_expr.default = tvar_expr.default.accept( + TypeVarDefaultTranslator(self, tvar_expr.name, typ) + ) tvar_def = self.tvar_scope.bind_new(name, tvar_expr) + if last_tvar_name_with_default is not None and not tvar_def.has_default(): + self.msg.tvar_without_default_type( + tvar_def.name, last_tvar_name_with_default, typ + ) + tvar_def.default = AnyType(TypeOfAny.from_error) + elif tvar_def.has_default(): + last_tvar_name_with_default = tvar_def.name tvar_defs.append(tvar_def) analyzed, depends_on = analyze_type_alias( diff --git a/mypy/typeanal.py b/mypy/typeanal.py index 530793730f35..9cc0114df333 100644 --- a/mypy/typeanal.py +++ b/mypy/typeanal.py @@ -38,7 +38,12 @@ ) from mypy.options import Options from mypy.plugin import AnalyzeTypeContext, Plugin, TypeAnalyzerPluginInterface -from mypy.semanal_shared import SemanticAnalyzerCoreInterface, paramspec_args, paramspec_kwargs +from mypy.semanal_shared import ( + SemanticAnalyzerCoreInterface, + SemanticAnalyzerInterface, + paramspec_args, + paramspec_kwargs, +) from mypy.state import state from mypy.tvar_scope import TypeVarLikeScope from mypy.types import ( @@ -2508,3 +2513,32 @@ def process_types(self, types: list[Type] | tuple[Type, ...]) -> None: else: for t in types: t.accept(self) + + +class TypeVarDefaultTranslator(TrivialSyntheticTypeTranslator): + """Type translate visitor that replaces UnboundTypes with in-scope TypeVars.""" + + def __init__( + self, api: SemanticAnalyzerInterface, tvar_expr_name: str, context: Context + ) -> None: + self.api = api + self.tvar_expr_name = tvar_expr_name + self.context = context + + def visit_unbound_type(self, t: UnboundType) -> Type: + sym = self.api.lookup_qualified(t.name, t, suppress_errors=True) + if sym is not None: + if type_var := self.api.tvar_scope.get_binding(sym): + return type_var + if isinstance(sym.node, TypeVarLikeExpr): + self.api.fail( + f'Type parameter "{self.tvar_expr_name}" has a default type ' + "that refers to one or more type variables that are out of scope", + self.context, + ) + return AnyType(TypeOfAny.from_error) + return super().visit_unbound_type(t) + + def visit_type_alias_type(self, t: TypeAliasType) -> Type: + # TypeAliasTypes are analyzed separately already, just return it + return t diff --git a/mypy/types.py b/mypy/types.py index b1119c9447e2..f76e35784d8f 100644 --- a/mypy/types.py +++ b/mypy/types.py @@ -85,6 +85,15 @@ TypeVisitor as TypeVisitor, ) +TYPE_VAR_LIKE_NAMES: Final = ( + "typing.TypeVar", + "typing_extensions.TypeVar", + "typing.ParamSpec", + "typing_extensions.ParamSpec", + "typing.TypeVarTuple", + "typing_extensions.TypeVarTuple", +) + TYPED_NAMEDTUPLE_NAMES: Final = ("typing.NamedTuple", "typing_extensions.NamedTuple") # Supported names of TypedDict type constructors. diff --git a/test-data/unit/check-typevar-defaults.test b/test-data/unit/check-typevar-defaults.test index 1a08823cb692..9ca67376da26 100644 --- a/test-data/unit/check-typevar-defaults.test +++ b/test-data/unit/check-typevar-defaults.test @@ -82,6 +82,74 @@ T3 = TypeVar("T3", int, str, default=bytes) # E: TypeVar default must be one of T4 = TypeVar("T4", int, str, default=Union[int, str]) # E: TypeVar default must be one of the constraint types T5 = TypeVar("T5", float, str, default=int) # E: TypeVar default must be one of the constraint types +[case testTypeVarDefaultsInvalid3] +from typing import Dict, Generic, TypeVar + +T1 = TypeVar("T1") +T2 = TypeVar("T2", default=T3) # E: Name "T3" is used before definition +T3 = TypeVar("T3", default=str) +T4 = TypeVar("T4", default=T3) + +class ClassError1(Generic[T3, T1]): ... # E: "T1" cannot appear after "T3" in type parameter list because it has no default type + +def func_error1( + a: ClassError1, + b: ClassError1[int], + c: ClassError1[int, float], +) -> None: + reveal_type(a) # N: Revealed type is "__main__.ClassError1[builtins.str, Any]" + reveal_type(b) # N: Revealed type is "__main__.ClassError1[builtins.int, Any]" + reveal_type(c) # N: Revealed type is "__main__.ClassError1[builtins.int, builtins.float]" + + k = ClassError1() + reveal_type(k) # N: Revealed type is "__main__.ClassError1[builtins.str, Any]" + l = ClassError1[int]() + reveal_type(l) # N: Revealed type is "__main__.ClassError1[builtins.int, Any]" + m = ClassError1[int, float]() + reveal_type(m) # N: Revealed type is "__main__.ClassError1[builtins.int, builtins.float]" + +class ClassError2(Generic[T4, T3]): ... # E: Type parameter "T4" has a default type that refers to one or more type variables that are out of scope + +def func_error2( + a: ClassError2, + b: ClassError2[int], + c: ClassError2[int, float], +) -> None: + reveal_type(a) # N: Revealed type is "__main__.ClassError2[Any, builtins.str]" + reveal_type(b) # N: Revealed type is "__main__.ClassError2[builtins.int, builtins.str]" + reveal_type(c) # N: Revealed type is "__main__.ClassError2[builtins.int, builtins.float]" + + k = ClassError2() + reveal_type(k) # N: Revealed type is "__main__.ClassError2[Any, builtins.str]" + l = ClassError2[int]() + reveal_type(l) # N: Revealed type is "__main__.ClassError2[builtins.int, builtins.str]" + m = ClassError2[int, float]() + reveal_type(m) # N: Revealed type is "__main__.ClassError2[builtins.int, builtins.float]" + +TERR1 = Dict[T3, T1] # E: "T1" cannot appear after "T3" in type parameter list because it has no default type + +def func_error_alias1( + a: TERR1, + b: TERR1[int], + c: TERR1[int, float], +) -> None: + reveal_type(a) # N: Revealed type is "builtins.dict[builtins.str, Any]" + reveal_type(b) # N: Revealed type is "builtins.dict[builtins.int, Any]" + reveal_type(c) # N: Revealed type is "builtins.dict[builtins.int, builtins.float]" + +TERR2 = Dict[T4, T3] # TODO should be an error \ + # Type parameter "T4" has a default type that refers to one or more type variables that are out of scope + +def func_error_alias2( + a: TERR2, + b: TERR2[int], + c: TERR2[int, float], +) -> None: + reveal_type(a) # N: Revealed type is "builtins.dict[Any, builtins.str]" + reveal_type(b) # N: Revealed type is "builtins.dict[builtins.int, builtins.str]" + reveal_type(c) # N: Revealed type is "builtins.dict[builtins.int, builtins.float]" +[builtins fixtures/dict.pyi] + [case testTypeVarDefaultsFunctions] from typing import TypeVar, ParamSpec, List, Union, Callable, Tuple from typing_extensions import TypeVarTuple, Unpack @@ -351,11 +419,12 @@ def func_c4( [case testTypeVarDefaultsClassRecursive1] # flags: --disallow-any-generics -from typing import Generic, TypeVar +from typing import Generic, TypeVar, List T1 = TypeVar("T1", default=str) T2 = TypeVar("T2", default=T1) T3 = TypeVar("T3", default=T2) +T4 = TypeVar("T4", default=List[T1]) class ClassD1(Generic[T1, T2]): ... @@ -397,12 +466,30 @@ def func_d2( n = ClassD2[int, float, str]() reveal_type(n) # N: Revealed type is "__main__.ClassD2[builtins.int, builtins.float, builtins.str]" +class ClassD3(Generic[T1, T4]): ... + +def func_d3( + a: ClassD3, + b: ClassD3[int], + c: ClassD3[int, float], +) -> None: + reveal_type(a) # N: Revealed type is "__main__.ClassD3[builtins.str, builtins.list[builtins.str]]" + reveal_type(b) # N: Revealed type is "__main__.ClassD3[builtins.int, builtins.list[builtins.int]]" + reveal_type(c) # N: Revealed type is "__main__.ClassD3[builtins.int, builtins.float]" + + # k = ClassD3() + # reveal_type(k) # Revealed type is "__main__.ClassD3[builtins.str, builtins.list[builtins.str]]" # TODO + l = ClassD3[int]() + reveal_type(l) # N: Revealed type is "__main__.ClassD3[builtins.int, builtins.list[builtins.int]]" + m = ClassD3[int, float]() + reveal_type(m) # N: Revealed type is "__main__.ClassD3[builtins.int, builtins.float]" + [case testTypeVarDefaultsClassRecursiveMultipleFiles] # flags: --disallow-any-generics from typing import Generic, TypeVar from file2 import T as T2 -T = TypeVar('T', default=T2) +T = TypeVar("T", default=T2) class ClassG1(Generic[T2, T]): pass @@ -587,3 +674,46 @@ def func_c4( # reveal_type(b) # Revealed type is "Tuple[builtins.int, builtins.str]" # TODO reveal_type(c) # N: Revealed type is "Tuple[builtins.int, builtins.float]" [builtins fixtures/tuple.pyi] + +[case testTypeVarDefaultsTypeAliasRecursive1] +# flags: --disallow-any-generics +from typing import Dict, List, TypeVar + +T1 = TypeVar("T1") +T2 = TypeVar("T2", default=T1) + +TD1 = Dict[T1, T2] + +def func_d1( + a: TD1, # E: Missing type parameters for generic type "TD1" + b: TD1[int], + c: TD1[int, float], +) -> None: + reveal_type(a) # N: Revealed type is "builtins.dict[Any, Any]" + reveal_type(b) # N: Revealed type is "builtins.dict[builtins.int, builtins.int]" + reveal_type(c) # N: Revealed type is "builtins.dict[builtins.int, builtins.float]" +[builtins fixtures/dict.pyi] + +[case testTypeVarDefaultsTypeAliasRecursive2] +from typing import Any, Dict, Generic, TypeVar + +T1 = TypeVar("T1", default=str) +T2 = TypeVar("T2", default=T1) +Alias1 = Dict[T1, T2] +T3 = TypeVar("T3") +class A(Generic[T3]): ... + +T4 = TypeVar("T4", default=A[Alias1]) +class B(Generic[T4]): ... + +def func_d3( + a: B, + b: B[A[Alias1[int]]], + c: B[A[Alias1[int, float]]], + d: B[int], +) -> None: + reveal_type(a) # N: Revealed type is "__main__.B[__main__.A[builtins.dict[builtins.str, builtins.str]]]" + reveal_type(b) # N: Revealed type is "__main__.B[__main__.A[builtins.dict[builtins.int, builtins.int]]]" + reveal_type(c) # N: Revealed type is "__main__.B[__main__.A[builtins.dict[builtins.int, builtins.float]]]" + reveal_type(d) # N: Revealed type is "__main__.B[builtins.int]" +[builtins fixtures/dict.pyi] From 2037e4a068df6e1dcc8f76c37f53e04d62d64e80 Mon Sep 17 00:00:00 2001 From: Shantanu <12621235+hauntsaninja@users.noreply.github.com> Date: Sun, 25 Feb 2024 14:44:49 -0800 Subject: [PATCH 20/54] Workaround parenthesised context manager issue (#16949) Fixes #16945 --- mypy/checker.py | 18 ++++++------------ 1 file changed, 6 insertions(+), 12 deletions(-) diff --git a/mypy/checker.py b/mypy/checker.py index 56be3db3f9e7..9f987cb5ccdf 100644 --- a/mypy/checker.py +++ b/mypy/checker.py @@ -4,7 +4,7 @@ import itertools from collections import defaultdict -from contextlib import contextmanager, nullcontext +from contextlib import ExitStack, contextmanager from typing import ( AbstractSet, Callable, @@ -526,17 +526,11 @@ def check_second_pass( # print("XXX in pass %d, class %s, function %s" % # (self.pass_num, type_name, node.fullname or node.name)) done.add(node) - with ( - self.tscope.class_scope(active_typeinfo) - if active_typeinfo - else nullcontext() - ): - with ( - self.scope.push_class(active_typeinfo) - if active_typeinfo - else nullcontext() - ): - self.check_partial(node) + with ExitStack() as stack: + if active_typeinfo: + stack.enter_context(self.tscope.class_scope(active_typeinfo)) + stack.enter_context(self.scope.push_class(active_typeinfo)) + self.check_partial(node) return True def check_partial(self, node: DeferredNodeType | FineGrainedDeferredNodeType) -> None: From a91151c46fb0407c9220db9630826634793b9697 Mon Sep 17 00:00:00 2001 From: hesam <97763520+hesam-ghamary@users.noreply.github.com> Date: Mon, 26 Feb 2024 18:28:41 +0330 Subject: [PATCH 21/54] Fix duplicate word in protocols.rst (#16950) --- docs/source/protocols.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/source/protocols.rst b/docs/source/protocols.rst index 3336d77cb397..067f4d9dcfac 100644 --- a/docs/source/protocols.rst +++ b/docs/source/protocols.rst @@ -9,7 +9,7 @@ compatible as types: nominal subtyping and structural subtyping. *Nominal* subtyping is strictly based on the class hierarchy. If class ``Dog`` inherits class ``Animal``, it's a subtype of ``Animal``. Instances of ``Dog`` can be used when ``Animal`` instances are expected. This form of subtyping -subtyping is what Python's type system predominantly uses: it's easy to +is what Python's type system predominantly uses: it's easy to understand and produces clear and concise error messages, and matches how the native :py:func:`isinstance ` check works -- based on class hierarchy. From 5a8cd80857fd7a1771d5f714c3e3ad69af4070c8 Mon Sep 17 00:00:00 2001 From: Srinivas Lade Date: Wed, 28 Feb 2024 11:16:23 -0500 Subject: [PATCH 22/54] [mypyc] Optimize TYPE_CHECKING to False at Runtime (#16263) Fixes [mypyc/mypyc#902](https://github.com/mypyc/mypyc/issues/902) This PR finds references of `typing.TYPE_CHECKING` or `typing_extensions.TYPE_CHECKING` and optimizes them to `False` in mypyc. --- mypyc/irbuild/expression.py | 6 ++++++ mypyc/test-data/irbuild-basic.test | 30 ++++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/mypyc/irbuild/expression.py b/mypyc/irbuild/expression.py index 8d205b432d2d..5cdd9a432a12 100644 --- a/mypyc/irbuild/expression.py +++ b/mypyc/irbuild/expression.py @@ -126,6 +126,8 @@ def transform_name_expr(builder: IRBuilder, expr: NameExpr) -> Value: return builder.true() if fullname == "builtins.False": return builder.false() + if fullname in ("typing.TYPE_CHECKING", "typing_extensions.TYPE_CHECKING"): + return builder.false() math_literal = transform_math_literal(builder, fullname) if math_literal is not None: @@ -185,6 +187,10 @@ def transform_name_expr(builder: IRBuilder, expr: NameExpr) -> Value: def transform_member_expr(builder: IRBuilder, expr: MemberExpr) -> Value: + # Special Cases + if expr.fullname in ("typing.TYPE_CHECKING", "typing_extensions.TYPE_CHECKING"): + return builder.false() + # First check if this is maybe a final attribute. final = builder.get_final_ref(expr) if final is not None: diff --git a/mypyc/test-data/irbuild-basic.test b/mypyc/test-data/irbuild-basic.test index bf608abb87ad..d6c47814cb7f 100644 --- a/mypyc/test-data/irbuild-basic.test +++ b/mypyc/test-data/irbuild-basic.test @@ -3688,3 +3688,33 @@ def f(arg): arg :: __main__.A L0: return arg + +[case testTypeCheckingFlag] +from typing import TYPE_CHECKING, List + +def f(arg: List[int]) -> int: + if TYPE_CHECKING: + from collections.abc import Sized + s: Sized = arg + return len(s) + +[out] +def f(arg): + arg :: list + r0 :: bool + r1 :: int + r2 :: bit + s :: object + r3 :: int +L0: + r0 = 0 << 1 + r1 = extend r0: builtins.bool to builtins.int + r2 = r1 != 0 + if r2 goto L1 else goto L2 :: bool +L1: + goto L3 +L2: +L3: + s = arg + r3 = CPyObject_Size(s) + return r3 From 162c74d2af77070c6983e0f97fcb593eda4d29d1 Mon Sep 17 00:00:00 2001 From: Richard Si Date: Wed, 28 Feb 2024 11:52:42 -0500 Subject: [PATCH 23/54] [mypyc] Remangle redefined names produced by async with (#16408) Fixes mypyc/mypyc#1001. --------- Co-authored-by: Jelle Zijlstra --- mypyc/irbuild/builder.py | 7 ++++--- mypyc/test-data/run-async.test | 28 ++++++++++++++++++++++++++++ 2 files changed, 32 insertions(+), 3 deletions(-) diff --git a/mypyc/irbuild/builder.py b/mypyc/irbuild/builder.py index 9d160b08505d..69f3ad9c495f 100644 --- a/mypyc/irbuild/builder.py +++ b/mypyc/irbuild/builder.py @@ -1246,14 +1246,15 @@ def add_var_to_env_class( ) -> AssignmentTarget: # First, define the variable name as an attribute of the environment class, and then # construct a target for that attribute. - self.fn_info.env_class.attributes[var.name] = rtype - attr_target = AssignmentTargetAttr(base.curr_env_reg, var.name) + name = remangle_redefinition_name(var.name) + self.fn_info.env_class.attributes[name] = rtype + attr_target = AssignmentTargetAttr(base.curr_env_reg, name) if reassign: # Read the local definition of the variable, and set the corresponding attribute of # the environment class' variable to be that value. reg = self.read(self.lookup(var), self.fn_info.fitem.line) - self.add(SetAttr(base.curr_env_reg, var.name, reg, self.fn_info.fitem.line)) + self.add(SetAttr(base.curr_env_reg, name, reg, self.fn_info.fitem.line)) # Override the local definition of the variable to instead point at the variable in # the environment class. diff --git a/mypyc/test-data/run-async.test b/mypyc/test-data/run-async.test index 85ad172d61df..8488632e6574 100644 --- a/mypyc/test-data/run-async.test +++ b/mypyc/test-data/run-async.test @@ -143,3 +143,31 @@ async def foo() -> AsyncIterable[int]: yields, val = run_generator(async_iter(foo())) assert yields == (0,1,2), yields assert val == 'lol no', val + +[case testAsyncWithVarReuse] +class ConMan: + async def __aenter__(self) -> int: + return 1 + async def __aexit__(self, *exc: object): + pass + +class ConManB: + async def __aenter__(self) -> int: + return 2 + async def __aexit__(self, *exc: object): + pass + +async def x() -> None: + value = 2 + async with ConMan() as f: + value += f + assert value == 3, value + async with ConManB() as f: + value += f + assert value == 5, value + +[typing fixtures/typing-full.pyi] +[file driver.py] +import asyncio +import native +asyncio.run(native.x()) From 9f1c90a072c1bbbbb8260ad7181fc1f1acb99137 Mon Sep 17 00:00:00 2001 From: Richard Si Date: Wed, 28 Feb 2024 12:06:35 -0500 Subject: [PATCH 24/54] [mypyc] Don't crash on non-inlinable final local reads (#15719) Fixes mypyc/mypyc#852. Fixes mypyc/mypyc#990. --- mypyc/irbuild/builder.py | 4 ++-- mypyc/test-data/irbuild-basic.test | 26 ++++++++++++++++++++++++++ 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/mypyc/irbuild/builder.py b/mypyc/irbuild/builder.py index 69f3ad9c495f..f201a4737f89 100644 --- a/mypyc/irbuild/builder.py +++ b/mypyc/irbuild/builder.py @@ -60,7 +60,7 @@ UnionType, get_proper_type, ) -from mypy.util import split_target +from mypy.util import module_prefix, split_target from mypy.visitor import ExpressionVisitor, StatementVisitor from mypyc.common import BITMAP_BITS, SELF_NAME, TEMP_ATTR_NAME from mypyc.crash import catch_errors @@ -1023,7 +1023,7 @@ def emit_load_final( """ if final_var.final_value is not None: # this is safe even for non-native names return self.load_literal_value(final_var.final_value) - elif native: + elif native and module_prefix(self.graph, fullname): return self.load_final_static(fullname, self.mapper.type_to_rtype(typ), line, name) else: return None diff --git a/mypyc/test-data/irbuild-basic.test b/mypyc/test-data/irbuild-basic.test index d6c47814cb7f..cd952ef2ebfd 100644 --- a/mypyc/test-data/irbuild-basic.test +++ b/mypyc/test-data/irbuild-basic.test @@ -3337,6 +3337,32 @@ def foo(z): L0: return 1 +[case testFinalLocals] +from typing import Final + +def inlined() -> str: + # XXX: the final type must be declared explicitly for Var.final_value to be set. + const: Final[str] = "Oppenheimer" + return const + +def local() -> str: + const: Final[str] = inlined() + return const +[out] +def inlined(): + r0, const, r1 :: str +L0: + r0 = 'Oppenheimer' + const = r0 + r1 = 'Oppenheimer' + return r1 +def local(): + r0, const :: str +L0: + r0 = inlined() + const = r0 + return const + [case testDirectlyCall__bool__] class A: def __bool__(self) -> bool: From f19b5d3a026319687dd81a5c7c976698bbe948a8 Mon Sep 17 00:00:00 2001 From: Richard Si Date: Wed, 28 Feb 2024 13:01:10 -0500 Subject: [PATCH 25/54] [mypyc] Fix compilation of unreachable comprehensions (#15721) Fixes mypyc/mypyc#816. Admittedly hacky. --- mypyc/irbuild/expression.py | 4 ++++ mypyc/irbuild/for_helpers.py | 29 +++++++++++++++++++++++++++++ mypyc/test-data/run-misc.test | 6 ++++-- 3 files changed, 37 insertions(+), 2 deletions(-) diff --git a/mypyc/irbuild/expression.py b/mypyc/irbuild/expression.py index 5cdd9a432a12..81e37953809f 100644 --- a/mypyc/irbuild/expression.py +++ b/mypyc/irbuild/expression.py @@ -80,6 +80,7 @@ from mypyc.irbuild.constant_fold import constant_fold_expr from mypyc.irbuild.for_helpers import ( comprehension_helper, + raise_error_if_contains_unreachable_names, translate_list_comprehension, translate_set_comprehension, ) @@ -1020,6 +1021,9 @@ def transform_set_comprehension(builder: IRBuilder, o: SetComprehension) -> Valu def transform_dictionary_comprehension(builder: IRBuilder, o: DictionaryComprehension) -> Value: + if raise_error_if_contains_unreachable_names(builder, o): + return builder.none() + d = builder.maybe_spill(builder.call_c(dict_new_op, [], o.line)) loop_params = list(zip(o.indices, o.sequences, o.condlists, o.is_async)) diff --git a/mypyc/irbuild/for_helpers.py b/mypyc/irbuild/for_helpers.py index 61dbbe960eb2..5d8315e88f72 100644 --- a/mypyc/irbuild/for_helpers.py +++ b/mypyc/irbuild/for_helpers.py @@ -12,10 +12,12 @@ from mypy.nodes import ( ARG_POS, CallExpr, + DictionaryComprehension, Expression, GeneratorExpr, Lvalue, MemberExpr, + NameExpr, RefExpr, SetExpr, TupleExpr, @@ -28,6 +30,7 @@ IntOp, LoadAddress, LoadMem, + RaiseStandardError, Register, TupleGet, TupleSet, @@ -229,6 +232,9 @@ def set_item(item_index: Value) -> None: def translate_list_comprehension(builder: IRBuilder, gen: GeneratorExpr) -> Value: + if raise_error_if_contains_unreachable_names(builder, gen): + return builder.none() + # Try simplest list comprehension, otherwise fall back to general one val = sequence_from_generator_preallocate_helper( builder, @@ -251,7 +257,30 @@ def gen_inner_stmts() -> None: return builder.read(list_ops) +def raise_error_if_contains_unreachable_names( + builder: IRBuilder, gen: GeneratorExpr | DictionaryComprehension +) -> bool: + """Raise a runtime error and return True if generator contains unreachable names. + + False is returned if the generator can be safely transformed without crashing. + (It may still be unreachable!) + """ + if any(isinstance(s, NameExpr) and s.node is None for s in gen.indices): + error = RaiseStandardError( + RaiseStandardError.RUNTIME_ERROR, + "mypyc internal error: should be unreachable", + gen.line, + ) + builder.add(error) + return True + + return False + + def translate_set_comprehension(builder: IRBuilder, gen: GeneratorExpr) -> Value: + if raise_error_if_contains_unreachable_names(builder, gen): + return builder.none() + set_ops = builder.maybe_spill(builder.new_set_op([], gen.line)) loop_params = list(zip(gen.indices, gen.sequences, gen.condlists, gen.is_async)) diff --git a/mypyc/test-data/run-misc.test b/mypyc/test-data/run-misc.test index f77ba3a1302b..14bb5be979ae 100644 --- a/mypyc/test-data/run-misc.test +++ b/mypyc/test-data/run-misc.test @@ -1097,8 +1097,10 @@ B = sys.platform == 'x' and sys.foobar C = sys.platform == 'x' and f(a, -b, 'y') > [c + e, g(y=2)] C = sys.platform == 'x' and cast(a, b[c]) C = sys.platform == 'x' and (lambda x: y + x) -# TODO: This still doesn't work -# C = sys.platform == 'x' and (x for y in z) +C = sys.platform == 'x' and (x for y in z) +C = sys.platform == 'x' and [x for y in z] +C = sys.platform == 'x' and {x: x for y in z} +C = sys.platform == 'x' and {x for y in z} assert not A assert not B From 02c50bcbc0ee26ec682c7356a1b3b9ecd9c11a3c Mon Sep 17 00:00:00 2001 From: Riccardo Di Maio <35903974+rdimaio@users.noreply.github.com> Date: Thu, 29 Feb 2024 16:18:33 +0100 Subject: [PATCH 26/54] Docs: Update `TypedDict` import statements (#16958) Since Python 3.8, `TypedDict` has been available from the `typing` module. As Python 3.8+ is needed to use mypy (https://github.com/python/mypy/blob/master/setup.py#L12), then it's best for the docs to reflect Python 3.8+ usage. For previous versions, there's already a disclaimer on the page that explains that `typing_extensions` must be used: https://github.com/python/mypy/blob/master/docs/source/typed_dict.rst?plain=1#L102-L110 Co-authored-by: Alex Waygood --- docs/source/common_issues.rst | 4 ++-- docs/source/error_code_list.rst | 8 ++++---- docs/source/generics.rst | 3 +-- docs/source/protocols.rst | 14 +++++--------- docs/source/stubs.rst | 2 +- docs/source/typed_dict.rst | 4 ++-- 6 files changed, 15 insertions(+), 20 deletions(-) diff --git a/docs/source/common_issues.rst b/docs/source/common_issues.rst index 8cc18c863e45..4a1d1b437153 100644 --- a/docs/source/common_issues.rst +++ b/docs/source/common_issues.rst @@ -541,7 +541,7 @@ Consider this example: .. code-block:: python - from typing_extensions import Protocol + from typing import Protocol class P(Protocol): x: float @@ -561,7 +561,7 @@ the protocol definition: .. code-block:: python - from typing_extensions import Protocol + from typing import Protocol class P(Protocol): @property diff --git a/docs/source/error_code_list.rst b/docs/source/error_code_list.rst index 4decd37e6e8a..48b3b689884f 100644 --- a/docs/source/error_code_list.rst +++ b/docs/source/error_code_list.rst @@ -537,7 +537,7 @@ Example: .. code-block:: python - from typing_extensions import TypedDict + from typing import TypedDict class Point(TypedDict): x: int @@ -562,7 +562,7 @@ to have been validated at the point of construction. Example: .. code-block:: python - from typing_extensions import TypedDict + from typing import TypedDict class Point(TypedDict): x: int @@ -868,7 +868,7 @@ the return type affects which lines mypy thinks are reachable after a ``True`` may swallow exceptions. An imprecise return type can result in mysterious errors reported near ``with`` statements. -To fix this, use either ``typing_extensions.Literal[False]`` or +To fix this, use either ``typing.Literal[False]`` or ``None`` as the return type. Returning ``None`` is equivalent to returning ``False`` in this context, since both are treated as false values. @@ -897,7 +897,7 @@ You can use ``Literal[False]`` to fix the error: .. code-block:: python - from typing_extensions import Literal + from typing import Literal class MyContext: ... diff --git a/docs/source/generics.rst b/docs/source/generics.rst index 9ac79f90121d..01ae7534ba93 100644 --- a/docs/source/generics.rst +++ b/docs/source/generics.rst @@ -770,8 +770,7 @@ protocols mostly follow the normal rules for generic classes. Example: .. code-block:: python - from typing import TypeVar - from typing_extensions import Protocol + from typing import Protocol, TypeVar T = TypeVar('T') diff --git a/docs/source/protocols.rst b/docs/source/protocols.rst index 067f4d9dcfac..731562867691 100644 --- a/docs/source/protocols.rst +++ b/docs/source/protocols.rst @@ -68,8 +68,7 @@ class: .. code-block:: python - from typing import Iterable - from typing_extensions import Protocol + from typing import Iterable, Protocol class SupportsClose(Protocol): # Empty method body (explicit '...') @@ -226,8 +225,7 @@ such as trees and linked lists: .. code-block:: python - from typing import TypeVar, Optional - from typing_extensions import Protocol + from typing import TypeVar, Optional, Protocol class TreeLike(Protocol): value: int @@ -255,7 +253,7 @@ rudimentary support for runtime structural checks: .. code-block:: python - from typing_extensions import Protocol, runtime_checkable + from typing import Protocol, runtime_checkable @runtime_checkable class Portable(Protocol): @@ -298,8 +296,7 @@ member: .. code-block:: python - from typing import Optional, Iterable - from typing_extensions import Protocol + from typing import Optional, Iterable, Protocol class Combiner(Protocol): def __call__(self, *vals: bytes, maxlen: Optional[int] = None) -> list[bytes]: ... @@ -323,8 +320,7 @@ a double underscore prefix is used. For example: .. code-block:: python - from typing import Callable, TypeVar - from typing_extensions import Protocol + from typing import Callable, Protocol, TypeVar T = TypeVar('T') diff --git a/docs/source/stubs.rst b/docs/source/stubs.rst index 7c84a9718b3e..c0a3f8b88111 100644 --- a/docs/source/stubs.rst +++ b/docs/source/stubs.rst @@ -114,7 +114,7 @@ For example: .. code-block:: python - from typing_extensions import Protocol + from typing import Protocol class Resource(Protocol): def ok_1(self, foo: list[str] = ...) -> None: ... diff --git a/docs/source/typed_dict.rst b/docs/source/typed_dict.rst index 19a717d7feb7..e5ce2927db4d 100644 --- a/docs/source/typed_dict.rst +++ b/docs/source/typed_dict.rst @@ -25,7 +25,7 @@ dictionary value depends on the key: .. code-block:: python - from typing_extensions import TypedDict + from typing import TypedDict Movie = TypedDict('Movie', {'name': str, 'year': int}) @@ -189,7 +189,7 @@ in Python 3.6 and later: .. code-block:: python - from typing_extensions import TypedDict + from typing import TypedDict # "from typing_extensions" in Python 3.7 and earlier class Movie(TypedDict): name: str From ab0bd8cac3f4183ca0c67ab7f9235c6b515ac2f3 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Thu, 29 Feb 2024 16:47:00 -0800 Subject: [PATCH 27/54] Sync typeshed (#16969) Source commit: https://github.com/python/typeshed/commit/e05098681f326b98c635853a40287ac21f771fa2 --- mypy/typeshed/stdlib/VERSIONS | 1 + mypy/typeshed/stdlib/_ctypes.pyi | 6 +- mypy/typeshed/stdlib/_dummy_thread.pyi | 10 +- mypy/typeshed/stdlib/_lsprof.pyi | 35 ++++ mypy/typeshed/stdlib/_operator.pyi | 12 +- mypy/typeshed/stdlib/_thread.pyi | 10 +- mypy/typeshed/stdlib/abc.pyi | 6 +- mypy/typeshed/stdlib/argparse.pyi | 30 ++- mypy/typeshed/stdlib/asyncio/events.pyi | 16 +- mypy/typeshed/stdlib/asyncio/tasks.pyi | 4 +- mypy/typeshed/stdlib/builtins.pyi | 8 +- mypy/typeshed/stdlib/cProfile.pyi | 8 +- mypy/typeshed/stdlib/datetime.pyi | 18 +- mypy/typeshed/stdlib/difflib.pyi | 4 +- mypy/typeshed/stdlib/distutils/sysconfig.pyi | 11 +- mypy/typeshed/stdlib/email/utils.pyi | 6 +- mypy/typeshed/stdlib/functools.pyi | 11 +- .../stdlib/importlib/metadata/__init__.pyi | 24 ++- .../stdlib/importlib/metadata/_meta.pyi | 23 ++- mypy/typeshed/stdlib/itertools.pyi | 16 +- mypy/typeshed/stdlib/numbers.pyi | 171 ++++++++++++------ mypy/typeshed/stdlib/os/__init__.pyi | 21 ++- mypy/typeshed/stdlib/posix.pyi | 4 +- mypy/typeshed/stdlib/queue.pyi | 8 + mypy/typeshed/stdlib/shlex.pyi | 34 +++- mypy/typeshed/stdlib/shutil.pyi | 14 +- mypy/typeshed/stdlib/sqlite3/dbapi2.pyi | 73 +++++--- mypy/typeshed/stdlib/sysconfig.pyi | 7 +- mypy/typeshed/stdlib/tarfile.pyi | 3 + mypy/typeshed/stdlib/tkinter/__init__.pyi | 6 +- mypy/typeshed/stdlib/types.pyi | 12 +- mypy/typeshed/stdlib/typing_extensions.pyi | 10 +- .../typeshed/stdlib/xml/etree/ElementTree.pyi | 6 +- 33 files changed, 437 insertions(+), 191 deletions(-) create mode 100644 mypy/typeshed/stdlib/_lsprof.pyi diff --git a/mypy/typeshed/stdlib/VERSIONS b/mypy/typeshed/stdlib/VERSIONS index da395f797881..deb940395e1e 100644 --- a/mypy/typeshed/stdlib/VERSIONS +++ b/mypy/typeshed/stdlib/VERSIONS @@ -36,6 +36,7 @@ _heapq: 3.0- _imp: 3.0- _json: 3.0- _locale: 3.0- +_lsprof: 3.0- _markupbase: 3.0- _msi: 3.0- _operator: 3.4- diff --git a/mypy/typeshed/stdlib/_ctypes.pyi b/mypy/typeshed/stdlib/_ctypes.pyi index ec3d86e41687..e0cc87814609 100644 --- a/mypy/typeshed/stdlib/_ctypes.pyi +++ b/mypy/typeshed/stdlib/_ctypes.pyi @@ -64,6 +64,7 @@ class _CData(metaclass=_CDataMeta): # Structure.from_buffer(...) # valid at runtime # Structure(...).from_buffer(...) # invalid at runtime # + @classmethod def from_buffer(cls, source: WriteableBuffer, offset: int = ...) -> Self: ... @classmethod @@ -106,14 +107,15 @@ class _CArgObject: ... def byref(obj: _CData, offset: int = ...) -> _CArgObject: ... -_ECT: TypeAlias = Callable[[type[_CData] | None, CFuncPtr, tuple[_CData, ...]], _CData] +_ECT: TypeAlias = Callable[[_CData | None, CFuncPtr, tuple[_CData, ...]], _CData] _PF: TypeAlias = tuple[int] | tuple[int, str | None] | tuple[int, str | None, Any] class CFuncPtr(_PointerLike, _CData): restype: type[_CData] | Callable[[int], Any] | None argtypes: Sequence[type[_CData]] errcheck: _ECT - _flags_: ClassVar[int] # Abstract attribute that must be defined on subclasses + # Abstract attribute that must be defined on subclasses + _flags_: ClassVar[int] @overload def __init__(self) -> None: ... @overload diff --git a/mypy/typeshed/stdlib/_dummy_thread.pyi b/mypy/typeshed/stdlib/_dummy_thread.pyi index 541096734a91..1182e53c66c3 100644 --- a/mypy/typeshed/stdlib/_dummy_thread.pyi +++ b/mypy/typeshed/stdlib/_dummy_thread.pyi @@ -1,13 +1,19 @@ from collections.abc import Callable from types import TracebackType -from typing import Any, NoReturn +from typing import Any, NoReturn, overload +from typing_extensions import TypeVarTuple, Unpack __all__ = ["error", "start_new_thread", "exit", "get_ident", "allocate_lock", "interrupt_main", "LockType", "RLock"] +_Ts = TypeVarTuple("_Ts") + TIMEOUT_MAX: int error = RuntimeError -def start_new_thread(function: Callable[..., object], args: tuple[Any, ...], kwargs: dict[str, Any] = {}) -> None: ... +@overload +def start_new_thread(function: Callable[[Unpack[_Ts]], object], args: tuple[Unpack[_Ts]]) -> None: ... +@overload +def start_new_thread(function: Callable[..., object], args: tuple[Any, ...], kwargs: dict[str, Any]) -> None: ... def exit() -> NoReturn: ... def get_ident() -> int: ... def allocate_lock() -> LockType: ... diff --git a/mypy/typeshed/stdlib/_lsprof.pyi b/mypy/typeshed/stdlib/_lsprof.pyi new file mode 100644 index 000000000000..8a6934162c92 --- /dev/null +++ b/mypy/typeshed/stdlib/_lsprof.pyi @@ -0,0 +1,35 @@ +import sys +from _typeshed import structseq +from collections.abc import Callable +from types import CodeType +from typing import Any, Final, final + +class Profiler: + def __init__( + self, timer: Callable[[], float] | None = None, timeunit: float = 0.0, subcalls: bool = True, builtins: bool = True + ) -> None: ... + def getstats(self) -> list[profiler_entry]: ... + def enable(self, subcalls: bool = True, builtins: bool = True) -> None: ... + def disable(self) -> None: ... + def clear(self) -> None: ... + +@final +class profiler_entry(structseq[Any], tuple[CodeType | str, int, int, float, float, list[profiler_subentry]]): + if sys.version_info >= (3, 10): + __match_args__: Final = ("code", "callcount", "reccallcount", "totaltime", "inlinetime", "calls") + code: CodeType | str + callcount: int + reccallcount: int + totaltime: float + inlinetime: float + calls: list[profiler_subentry] + +@final +class profiler_subentry(structseq[Any], tuple[CodeType | str, int, int, float, float]): + if sys.version_info >= (3, 10): + __match_args__: Final = ("code", "callcount", "reccallcount", "totaltime", "inlinetime") + code: CodeType | str + callcount: int + reccallcount: int + totaltime: float + inlinetime: float diff --git a/mypy/typeshed/stdlib/_operator.pyi b/mypy/typeshed/stdlib/_operator.pyi index acc4a6fb59ca..9b24e086adff 100644 --- a/mypy/typeshed/stdlib/_operator.pyi +++ b/mypy/typeshed/stdlib/_operator.pyi @@ -95,16 +95,16 @@ def length_hint(__obj: object, __default: int = 0) -> int: ... @final class attrgetter(Generic[_T_co]): @overload - def __new__(cls, attr: str) -> attrgetter[Any]: ... + def __new__(cls, attr: str, /) -> attrgetter[Any]: ... @overload - def __new__(cls, attr: str, __attr2: str) -> attrgetter[tuple[Any, Any]]: ... + def __new__(cls, attr: str, attr2: str, /) -> attrgetter[tuple[Any, Any]]: ... @overload - def __new__(cls, attr: str, __attr2: str, __attr3: str) -> attrgetter[tuple[Any, Any, Any]]: ... + def __new__(cls, attr: str, attr2: str, attr3: str, /) -> attrgetter[tuple[Any, Any, Any]]: ... @overload - def __new__(cls, attr: str, __attr2: str, __attr3: str, __attr4: str) -> attrgetter[tuple[Any, Any, Any, Any]]: ... + def __new__(cls, attr: str, attr2: str, attr3: str, attr4: str, /) -> attrgetter[tuple[Any, Any, Any, Any]]: ... @overload - def __new__(cls, attr: str, *attrs: str) -> attrgetter[tuple[Any, ...]]: ... - def __call__(self, obj: Any) -> _T_co: ... + def __new__(cls, attr: str, /, *attrs: str) -> attrgetter[tuple[Any, ...]]: ... + def __call__(self, obj: Any, /) -> _T_co: ... @final class itemgetter(Generic[_T_co]): diff --git a/mypy/typeshed/stdlib/_thread.pyi b/mypy/typeshed/stdlib/_thread.pyi index ff9bd1a12eb1..e69f9d2359aa 100644 --- a/mypy/typeshed/stdlib/_thread.pyi +++ b/mypy/typeshed/stdlib/_thread.pyi @@ -3,7 +3,10 @@ from _typeshed import structseq from collections.abc import Callable from threading import Thread from types import TracebackType -from typing import Any, Final, NoReturn, final +from typing import Any, Final, NoReturn, final, overload +from typing_extensions import TypeVarTuple, Unpack + +_Ts = TypeVarTuple("_Ts") error = RuntimeError @@ -18,7 +21,10 @@ class LockType: self, type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None ) -> None: ... -def start_new_thread(function: Callable[..., object], args: tuple[Any, ...], kwargs: dict[str, Any] = ...) -> int: ... +@overload +def start_new_thread(function: Callable[[Unpack[_Ts]], object], args: tuple[Unpack[_Ts]]) -> int: ... +@overload +def start_new_thread(function: Callable[..., object], args: tuple[Any, ...], kwargs: dict[str, Any]) -> int: ... def interrupt_main() -> None: ... def exit() -> NoReturn: ... def allocate_lock() -> LockType: ... diff --git a/mypy/typeshed/stdlib/abc.pyi b/mypy/typeshed/stdlib/abc.pyi index c642f8b9f123..e4e7f59b58ca 100644 --- a/mypy/typeshed/stdlib/abc.pyi +++ b/mypy/typeshed/stdlib/abc.pyi @@ -3,7 +3,7 @@ import sys from _typeshed import SupportsWrite from collections.abc import Callable from typing import Any, Literal, TypeVar -from typing_extensions import Concatenate, ParamSpec +from typing_extensions import Concatenate, ParamSpec, deprecated _T = TypeVar("_T") _R_co = TypeVar("_R_co", covariant=True) @@ -28,15 +28,17 @@ class ABCMeta(type): def register(cls: ABCMeta, subclass: type[_T]) -> type[_T]: ... def abstractmethod(funcobj: _FuncT) -> _FuncT: ... - +@deprecated("Deprecated, use 'classmethod' with '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("Deprecated, use 'staticmethod' with 'abstractmethod' instead") class abstractstaticmethod(staticmethod[_P, _R_co]): __isabstractmethod__: Literal[True] def __init__(self, callable: Callable[_P, _R_co]) -> None: ... +@deprecated("Deprecated, use 'property' with 'abstractmethod' instead") class abstractproperty(property): __isabstractmethod__: Literal[True] diff --git a/mypy/typeshed/stdlib/argparse.pyi b/mypy/typeshed/stdlib/argparse.pyi index 489cc6b16634..c34aca1f8c20 100644 --- a/mypy/typeshed/stdlib/argparse.pyi +++ b/mypy/typeshed/stdlib/argparse.pyi @@ -3,7 +3,7 @@ from _typeshed import sentinel from collections.abc import Callable, Generator, Iterable, Sequence from re import Pattern from typing import IO, Any, Generic, Literal, NewType, NoReturn, Protocol, TypeVar, overload -from typing_extensions import Self, TypeAlias +from typing_extensions import Self, TypeAlias, deprecated __all__ = [ "ArgumentParser", @@ -339,11 +339,23 @@ class Action(_AttributeHolder): if sys.version_info >= (3, 12): class BooleanOptionalAction(Action): + @overload def __init__( self, option_strings: Sequence[str], dest: str, - default: _T | str | None = None, + default: bool | None = None, + *, + required: bool = False, + help: str | None = None, + ) -> None: ... + @overload + @deprecated("The `type`, `choices`, and `metavar` parameters are ignored and will be removed in Python 3.14.") + def __init__( + self, + option_strings: Sequence[str], + dest: str, + default: _T | bool | None = None, type: Callable[[str], _T] | FileType | None = sentinel, choices: Iterable[_T] | None = sentinel, required: bool = False, @@ -353,11 +365,23 @@ if sys.version_info >= (3, 12): elif sys.version_info >= (3, 9): class BooleanOptionalAction(Action): + @overload + def __init__( + self, + option_strings: Sequence[str], + dest: str, + default: bool | None = None, + *, + required: bool = False, + help: str | None = None, + ) -> None: ... + @overload + @deprecated("The `type`, `choices`, and `metavar` parameters are ignored and will be removed in Python 3.14.") def __init__( self, option_strings: Sequence[str], dest: str, - default: _T | str | None = None, + default: _T | bool | None = None, type: Callable[[str], _T] | FileType | None = None, choices: Iterable[_T] | None = None, required: bool = False, diff --git a/mypy/typeshed/stdlib/asyncio/events.pyi b/mypy/typeshed/stdlib/asyncio/events.pyi index 649771df8bf1..16f5296e2125 100644 --- a/mypy/typeshed/stdlib/asyncio/events.pyi +++ b/mypy/typeshed/stdlib/asyncio/events.pyi @@ -543,10 +543,18 @@ class AbstractEventLoopPolicy: @abstractmethod def new_event_loop(self) -> AbstractEventLoop: ... # Child processes handling (Unix only). - @abstractmethod - def get_child_watcher(self) -> AbstractChildWatcher: ... - @abstractmethod - def set_child_watcher(self, watcher: AbstractChildWatcher) -> None: ... + if sys.version_info >= (3, 12): + @abstractmethod + @deprecated("Deprecated as of Python 3.12; will be 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") + def set_child_watcher(self, watcher: AbstractChildWatcher) -> None: ... + else: + @abstractmethod + def get_child_watcher(self) -> AbstractChildWatcher: ... + @abstractmethod + def set_child_watcher(self, watcher: AbstractChildWatcher) -> None: ... class BaseDefaultEventLoopPolicy(AbstractEventLoopPolicy, metaclass=ABCMeta): def get_event_loop(self) -> AbstractEventLoop: ... diff --git a/mypy/typeshed/stdlib/asyncio/tasks.pyi b/mypy/typeshed/stdlib/asyncio/tasks.pyi index 23447ba27aa5..028a7571bb79 100644 --- a/mypy/typeshed/stdlib/asyncio/tasks.pyi +++ b/mypy/typeshed/stdlib/asyncio/tasks.pyi @@ -375,6 +375,8 @@ else: if sys.version_info >= (3, 12): _TaskCompatibleCoro: TypeAlias = Coroutine[Any, Any, _T_co] +elif sys.version_info >= (3, 9): + _TaskCompatibleCoro: TypeAlias = Generator[_TaskYieldType, None, _T_co] | Coroutine[Any, Any, _T_co] else: _TaskCompatibleCoro: TypeAlias = Generator[_TaskYieldType, None, _T_co] | Awaitable[_T_co] @@ -382,7 +384,7 @@ else: # While this is true in general, here it's sort-of okay to have a covariant subclass, # since the only reason why `asyncio.Future` is invariant is the `set_result()` method, # and `asyncio.Task.set_result()` always raises. -class Task(Future[_T_co]): # type: ignore[type-var] # pyright: ignore[reportGeneralTypeIssues] +class Task(Future[_T_co]): # type: ignore[type-var] # pyright: ignore[reportInvalidTypeArguments] if sys.version_info >= (3, 12): def __init__( self, diff --git a/mypy/typeshed/stdlib/builtins.pyi b/mypy/typeshed/stdlib/builtins.pyi index 09f082f2fe48..02e128234dc1 100644 --- a/mypy/typeshed/stdlib/builtins.pyi +++ b/mypy/typeshed/stdlib/builtins.pyi @@ -437,7 +437,7 @@ class str(Sequence[str]): def capitalize(self) -> str: ... # type: ignore[misc] def casefold(self) -> str: ... # type: ignore[misc] def center(self, __width: SupportsIndex, __fillchar: str = " ") -> str: ... # type: ignore[misc] - def count(self, x: str, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ...) -> int: ... + def count(self, __sub: str, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ...) -> int: ... def encode(self, encoding: str = "utf-8", errors: str = "strict") -> bytes: ... def endswith( self, __suffix: str | tuple[str, ...], __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... @@ -1130,7 +1130,7 @@ class property: class _NotImplementedType(Any): # A little weird, but typing the __call__ as NotImplemented makes the error message # for NotImplemented() much better - __call__: NotImplemented # type: ignore[valid-type] # pyright: ignore[reportGeneralTypeIssues] + __call__: NotImplemented # type: ignore[valid-type] # pyright: ignore[reportInvalidTypeForm] NotImplemented: _NotImplementedType @@ -1544,9 +1544,9 @@ def quit(code: sys._ExitCode = None) -> NoReturn: ... class reversed(Iterator[_T]): @overload - def __init__(self, __sequence: Reversible[_T]) -> None: ... + def __new__(cls, __sequence: Reversible[_T]) -> Iterator[_T]: ... # type: ignore[misc] @overload - def __init__(self, __sequence: SupportsLenAndGetItem[_T]) -> None: ... + def __new__(cls, __sequence: SupportsLenAndGetItem[_T]) -> Iterator[_T]: ... # type: ignore[misc] def __iter__(self) -> Self: ... def __next__(self) -> _T: ... def __length_hint__(self) -> int: ... diff --git a/mypy/typeshed/stdlib/cProfile.pyi b/mypy/typeshed/stdlib/cProfile.pyi index 7d97fa22c394..c212f0383eaf 100644 --- a/mypy/typeshed/stdlib/cProfile.pyi +++ b/mypy/typeshed/stdlib/cProfile.pyi @@ -1,3 +1,4 @@ +import _lsprof from _typeshed import StrOrBytesPath, Unused from collections.abc import Callable from types import CodeType @@ -15,13 +16,8 @@ _T = TypeVar("_T") _P = ParamSpec("_P") _Label: TypeAlias = tuple[str, int, str] -class Profile: +class Profile(_lsprof.Profiler): stats: dict[_Label, tuple[int, int, int, int, dict[_Label, tuple[int, int, int, int]]]] # undocumented - def __init__( - self, timer: Callable[[], float] = ..., timeunit: float = ..., subcalls: bool = ..., builtins: bool = ... - ) -> None: ... - def enable(self) -> None: ... - def disable(self) -> None: ... def print_stats(self, sort: str | int = -1) -> None: ... def dump_stats(self, file: StrOrBytesPath) -> None: ... def create_stats(self) -> None: ... diff --git a/mypy/typeshed/stdlib/datetime.pyi b/mypy/typeshed/stdlib/datetime.pyi index 54ecddec3a9a..852208cd83a1 100644 --- a/mypy/typeshed/stdlib/datetime.pyi +++ b/mypy/typeshed/stdlib/datetime.pyi @@ -1,16 +1,14 @@ import sys from abc import abstractmethod from time import struct_time -from typing import ClassVar, Literal, NamedTuple, NoReturn, SupportsIndex, TypeVar, final, overload -from typing_extensions import Self, TypeAlias +from typing import ClassVar, Literal, NamedTuple, NoReturn, SupportsIndex, final, overload +from typing_extensions import Self, TypeAlias, deprecated if sys.version_info >= (3, 11): __all__ = ("date", "datetime", "time", "timedelta", "timezone", "tzinfo", "MINYEAR", "MAXYEAR", "UTC") elif sys.version_info >= (3, 9): __all__ = ("date", "datetime", "time", "timedelta", "timezone", "tzinfo", "MINYEAR", "MAXYEAR") -_D = TypeVar("_D", bound=date) - MINYEAR: Literal[1] MAXYEAR: Literal[9999] @@ -90,11 +88,11 @@ class date: def __add__(self, __value: timedelta) -> Self: ... def __radd__(self, __value: timedelta) -> Self: ... @overload - def __sub__(self, __value: timedelta) -> Self: ... - @overload def __sub__(self, __value: datetime) -> NoReturn: ... @overload - def __sub__(self: _D, __value: _D) -> timedelta: ... + def __sub__(self, __value: Self) -> timedelta: ... + @overload + def __sub__(self, __value: timedelta) -> Self: ... def __hash__(self) -> int: ... def weekday(self) -> int: ... def isoweekday(self) -> int: ... @@ -251,10 +249,12 @@ class datetime(date): def fromtimestamp(cls, __timestamp: float, tz: _TzInfo | None = ...) -> Self: ... @classmethod + @deprecated("Use timezone-aware objects to represent datetimes in UTC; e.g. by calling .fromtimestamp(datetime.UTC)") def utcfromtimestamp(cls, __t: float) -> Self: ... @classmethod def now(cls, tz: _TzInfo | None = None) -> Self: ... @classmethod + @deprecated("Use timezone-aware objects to represent datetimes in UTC; e.g. by calling .now(datetime.UTC)") def utcnow(cls) -> Self: ... @classmethod def combine(cls, date: _Date, time: _Time, tzinfo: _TzInfo | None = ...) -> Self: ... @@ -290,6 +290,6 @@ class datetime(date): def __eq__(self, __value: object) -> bool: ... def __hash__(self) -> int: ... @overload # type: ignore[override] - def __sub__(self, __value: timedelta) -> Self: ... + def __sub__(self, __value: Self) -> timedelta: ... @overload - def __sub__(self: _D, __value: _D) -> timedelta: ... + def __sub__(self, __value: timedelta) -> Self: ... diff --git a/mypy/typeshed/stdlib/difflib.pyi b/mypy/typeshed/stdlib/difflib.pyi index 894ebaaeca98..d5b77b8f0e2c 100644 --- a/mypy/typeshed/stdlib/difflib.pyi +++ b/mypy/typeshed/stdlib/difflib.pyi @@ -1,6 +1,6 @@ import sys from collections.abc import Callable, Iterable, Iterator, Sequence -from typing import Any, AnyStr, Generic, NamedTuple, TypeVar, overload +from typing import Any, AnyStr, Generic, Literal, NamedTuple, TypeVar, overload if sys.version_info >= (3, 9): from types import GenericAlias @@ -49,7 +49,7 @@ class SequenceMatcher(Generic[_T]): def find_longest_match(self, alo: int, ahi: int, blo: int, bhi: int) -> Match: ... def get_matching_blocks(self) -> list[Match]: ... - def get_opcodes(self) -> list[tuple[str, int, int, int, int]]: ... + def get_opcodes(self) -> list[tuple[Literal["replace", "delete", "insert", "equal"], int, int, int, int]]: ... def get_grouped_opcodes(self, n: int = 3) -> Iterable[list[tuple[str, int, int, int, int]]]: ... def ratio(self) -> float: ... def quick_ratio(self) -> float: ... diff --git a/mypy/typeshed/stdlib/distutils/sysconfig.pyi b/mypy/typeshed/stdlib/distutils/sysconfig.pyi index 464cfb639c6d..e2399a6cf36b 100644 --- a/mypy/typeshed/stdlib/distutils/sysconfig.pyi +++ b/mypy/typeshed/stdlib/distutils/sysconfig.pyi @@ -1,6 +1,8 @@ import sys from collections.abc import Mapping from distutils.ccompiler import CCompiler +from typing import Literal, overload +from typing_extensions import deprecated PREFIX: str EXEC_PREFIX: str @@ -10,8 +12,15 @@ project_base: str python_build: bool def expand_makefile_vars(s: str, vars: Mapping[str, str]) -> str: ... +@overload +@deprecated("SO is deprecated, use EXT_SUFFIX. Support is removed in Python 3.11") +def get_config_var(name: Literal["SO"]) -> int | str | None: ... +@overload def get_config_var(name: str) -> int | str | None: ... -def get_config_vars(*args: str) -> Mapping[str, int | str]: ... +@overload +def get_config_vars() -> dict[str, str | int]: ... +@overload +def get_config_vars(arg: str, /, *args: str) -> list[str | int]: ... def get_config_h_filename() -> str: ... def get_makefile_filename() -> str: ... def get_python_inc(plat_specific: bool = ..., prefix: str | None = None) -> str: ... diff --git a/mypy/typeshed/stdlib/email/utils.pyi b/mypy/typeshed/stdlib/email/utils.pyi index 186e768050be..0b62647532db 100644 --- a/mypy/typeshed/stdlib/email/utils.pyi +++ b/mypy/typeshed/stdlib/email/utils.pyi @@ -4,7 +4,7 @@ from _typeshed import Unused from email import _ParamType from email.charset import Charset from typing import overload -from typing_extensions import TypeAlias +from typing_extensions import TypeAlias, deprecated __all__ = [ "collapse_rfc2231_value", @@ -54,6 +54,10 @@ def formatdate(timeval: float | None = None, localtime: bool = False, usegmt: bo def format_datetime(dt: datetime.datetime, usegmt: bool = False) -> str: ... if sys.version_info >= (3, 12): + @overload + def localtime(dt: datetime.datetime | None = None) -> datetime.datetime: ... + @overload + @deprecated("The `isdst` parameter does nothing and will be removed in Python 3.14.") def localtime(dt: datetime.datetime | None = None, isdst: Unused = None) -> datetime.datetime: ... else: diff --git a/mypy/typeshed/stdlib/functools.pyi b/mypy/typeshed/stdlib/functools.pyi index 0f1666024f84..991182486113 100644 --- a/mypy/typeshed/stdlib/functools.pyi +++ b/mypy/typeshed/stdlib/functools.pyi @@ -30,6 +30,7 @@ if sys.version_info >= (3, 9): _AnyCallable: TypeAlias = Callable[..., object] _T = TypeVar("_T") +_T_co = TypeVar("_T_co", covariant=True) _S = TypeVar("_S") @overload @@ -171,17 +172,17 @@ class singledispatchmethod(Generic[_T]): def register(self, cls: type[Any], method: Callable[..., _T]) -> Callable[..., _T]: ... def __get__(self, obj: _S, cls: type[_S] | None = None) -> Callable[..., _T]: ... -class cached_property(Generic[_T]): - func: Callable[[Any], _T] +class cached_property(Generic[_T_co]): + func: Callable[[Any], _T_co] attrname: str | None - def __init__(self, func: Callable[[Any], _T]) -> None: ... + def __init__(self, func: Callable[[Any], _T_co]) -> None: ... @overload def __get__(self, instance: None, owner: type[Any] | None = None) -> Self: ... @overload - def __get__(self, instance: object, owner: type[Any] | None = None) -> _T: ... + def __get__(self, instance: object, owner: type[Any] | None = None) -> _T_co: ... def __set_name__(self, owner: type[Any], name: str) -> None: ... # __set__ is not defined at runtime, but @cached_property is designed to be settable - def __set__(self, instance: object, value: _T) -> None: ... + def __set__(self, instance: object, value: _T_co) -> None: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] if sys.version_info >= (3, 9): def __class_getitem__(cls, item: Any) -> GenericAlias: ... diff --git a/mypy/typeshed/stdlib/importlib/metadata/__init__.pyi b/mypy/typeshed/stdlib/importlib/metadata/__init__.pyi index eb4db39ebf40..b2fe14777056 100644 --- a/mypy/typeshed/stdlib/importlib/metadata/__init__.pyi +++ b/mypy/typeshed/stdlib/importlib/metadata/__init__.pyi @@ -10,7 +10,7 @@ from os import PathLike from pathlib import Path from re import Pattern from typing import Any, ClassVar, Generic, NamedTuple, TypeVar, overload -from typing_extensions import Self +from typing_extensions import Self, TypeAlias _T = TypeVar("_T") _KT = TypeVar("_KT") @@ -33,9 +33,17 @@ if sys.version_info >= (3, 10): __all__ += ["PackageMetadata", "packages_distributions"] if sys.version_info >= (3, 10): - from importlib.metadata._meta import PackageMetadata as PackageMetadata + from importlib.metadata._meta import PackageMetadata as PackageMetadata, SimplePath def packages_distributions() -> Mapping[str, list[str]]: ... + if sys.version_info >= (3, 12): + # It's generic but shouldn't be + _SimplePath: TypeAlias = SimplePath[Any] + else: + _SimplePath: TypeAlias = SimplePath +else: + _SimplePath: TypeAlias = Path + class PackageNotFoundError(ModuleNotFoundError): @property def name(self) -> str: ... # type: ignore[override] @@ -184,7 +192,7 @@ class Distribution(_distribution_parent): @abc.abstractmethod def read_text(self, filename: str) -> str | None: ... @abc.abstractmethod - def locate_file(self, path: StrPath) -> PathLike[str]: ... + def locate_file(self, path: StrPath) -> _SimplePath: ... @classmethod def from_name(cls, name: str) -> Distribution: ... @overload @@ -233,14 +241,14 @@ class MetadataPathFinder(DistributionFinder): @classmethod def find_distributions(cls, context: DistributionFinder.Context = ...) -> Iterable[PathDistribution]: ... if sys.version_info >= (3, 10): - # Yes, this is an instance method that has argumend named "cls" + # Yes, this is an instance method that has a parameter named "cls" def invalidate_caches(cls) -> None: ... class PathDistribution(Distribution): - _path: Path - def __init__(self, path: Path) -> None: ... - def read_text(self, filename: StrPath) -> str: ... - def locate_file(self, path: StrPath) -> PathLike[str]: ... + _path: _SimplePath + def __init__(self, path: _SimplePath) -> None: ... + def read_text(self, filename: StrPath) -> str | None: ... + def locate_file(self, path: StrPath) -> _SimplePath: ... def distribution(distribution_name: str) -> Distribution: ... @overload diff --git a/mypy/typeshed/stdlib/importlib/metadata/_meta.pyi b/mypy/typeshed/stdlib/importlib/metadata/_meta.pyi index 64fefa9a84e2..3eac226b7065 100644 --- a/mypy/typeshed/stdlib/importlib/metadata/_meta.pyi +++ b/mypy/typeshed/stdlib/importlib/metadata/_meta.pyi @@ -3,6 +3,7 @@ from collections.abc import Iterator from typing import Any, Protocol, TypeVar, overload _T = TypeVar("_T") +_T_co = TypeVar("_T_co", covariant=True) class PackageMetadata(Protocol): def __len__(self) -> int: ... @@ -22,19 +23,27 @@ class PackageMetadata(Protocol): def get(self, name: str, failobj: _T) -> _T | str: ... if sys.version_info >= (3, 12): - class SimplePath(Protocol[_T]): - def joinpath(self) -> _T: ... + class SimplePath(Protocol[_T_co]): + # At runtime this is defined as taking `str | _T`, but that causes trouble. + # See #11436. + def joinpath(self, other: str, /) -> _T_co: ... @property - def parent(self) -> _T: ... + def parent(self) -> _T_co: ... def read_text(self) -> str: ... - def __truediv__(self, other: _T | str) -> _T: ... + # As with joinpath(), this is annotated as taking `str | _T` at runtime. + def __truediv__(self, other: str, /) -> _T_co: ... else: class SimplePath(Protocol): - def joinpath(self) -> SimplePath: ... - def parent(self) -> SimplePath: ... + # Actually takes only self at runtime, but that's clearly wrong + def joinpath(self, other: Any, /) -> SimplePath: ... + # Not defined as a property at runtime, but it should be + @property + def parent(self) -> Any: ... def read_text(self) -> str: ... # There was a bug in `SimplePath` definition in cpython, see #8451 # Strictly speaking `__div__` was defined in 3.10, not __truediv__, # but it should have always been `__truediv__`. - def __truediv__(self) -> SimplePath: ... + # Also, the runtime defines this method as taking no arguments, + # which is obviously wrong. + def __truediv__(self, other: Any, /) -> SimplePath: ... diff --git a/mypy/typeshed/stdlib/itertools.pyi b/mypy/typeshed/stdlib/itertools.pyi index 1fa76399444a..0e501e1ade4d 100644 --- a/mypy/typeshed/stdlib/itertools.pyi +++ b/mypy/typeshed/stdlib/itertools.pyi @@ -220,21 +220,7 @@ class product(Iterator[_T_co]): __iter6: Iterable[_T6], ) -> product[tuple[_T1, _T2, _T3, _T4, _T5, _T6]]: ... @overload - def __new__( - cls, - __iter1: Iterable[Any], - __iter2: Iterable[Any], - __iter3: Iterable[Any], - __iter4: Iterable[Any], - __iter5: Iterable[Any], - __iter6: Iterable[Any], - __iter7: Iterable[Any], - *iterables: Iterable[Any], - ) -> product[tuple[Any, ...]]: ... - @overload - def __new__(cls, *iterables: Iterable[_T1], repeat: int) -> product[tuple[_T1, ...]]: ... - @overload - def __new__(cls, *iterables: Iterable[Any], repeat: int = ...) -> product[tuple[Any, ...]]: ... + def __new__(cls, *iterables: Iterable[_T1], repeat: int = 1) -> product[tuple[_T1, ...]]: ... def __iter__(self) -> Self: ... def __next__(self) -> _T_co: ... diff --git a/mypy/typeshed/stdlib/numbers.pyi b/mypy/typeshed/stdlib/numbers.pyi index 9f507d8335cf..e129de2cdc67 100644 --- a/mypy/typeshed/stdlib/numbers.pyi +++ b/mypy/typeshed/stdlib/numbers.pyi @@ -1,27 +1,62 @@ # Note: these stubs are incomplete. The more complex type # signatures are currently omitted. # -# Use SupportsComplex, SupportsFloat and SupportsIndex for return types in this module +# Use _ComplexLike, _RealLike and _IntegralLike for return types in this module # rather than `numbers.Complex`, `numbers.Real` and `numbers.Integral`, # to avoid an excessive number of `type: ignore`s in subclasses of these ABCs # (since type checkers don't see `complex` as a subtype of `numbers.Complex`, # nor `float` as a subtype of `numbers.Real`, etc.) -import sys from _typeshed import Incomplete from abc import ABCMeta, abstractmethod -from typing import Literal, SupportsFloat, SupportsIndex, overload -from typing_extensions import TypeAlias +from typing import Literal, Protocol, overload -if sys.version_info >= (3, 11): - from typing import SupportsComplex as _SupportsComplex -else: - # builtins.complex didn't have a __complex__ method on older Pythons - import typing +__all__ = ["Number", "Complex", "Real", "Rational", "Integral"] - _SupportsComplex: TypeAlias = typing.SupportsComplex | complex +############################ +# Protocols for return types +############################ -__all__ = ["Number", "Complex", "Real", "Rational", "Integral"] +# `_ComplexLike` is a structural-typing approximation +# of the `Complex` ABC, which is not (and cannot be) a protocol +# +# NOTE: We can't include `__complex__` here, +# as we want `int` to be seen as a subtype of `_ComplexLike`, +# and `int.__complex__` does not exist :( +class _ComplexLike(Protocol): + def __neg__(self) -> _ComplexLike: ... + def __pos__(self) -> _ComplexLike: ... + def __abs__(self) -> _RealLike: ... + +# _RealLike is a structural-typing approximation +# of the `Real` ABC, which is not (and cannot be) a protocol +class _RealLike(_ComplexLike, Protocol): + def __trunc__(self) -> _IntegralLike: ... + def __floor__(self) -> _IntegralLike: ... + def __ceil__(self) -> _IntegralLike: ... + def __float__(self) -> float: ... + # Overridden from `_ComplexLike` + # for a more precise return type: + def __neg__(self) -> _RealLike: ... + def __pos__(self) -> _RealLike: ... + +# _IntegralLike is a structural-typing approximation +# of the `Integral` ABC, which is not (and cannot be) a protocol +class _IntegralLike(_RealLike, Protocol): + def __invert__(self) -> _IntegralLike: ... + def __int__(self) -> int: ... + def __index__(self) -> int: ... + # Overridden from `_ComplexLike` + # for a more precise return type: + def __abs__(self) -> _IntegralLike: ... + # Overridden from `RealLike` + # for a more precise return type: + def __neg__(self) -> _IntegralLike: ... + def __pos__(self) -> _IntegralLike: ... + +################# +# Module "proper" +################# class Number(metaclass=ABCMeta): @abstractmethod @@ -29,126 +64,146 @@ class Number(metaclass=ABCMeta): # See comment at the top of the file # for why some of these return types are purposefully vague -class Complex(Number): +class Complex(Number, _ComplexLike): @abstractmethod def __complex__(self) -> complex: ... def __bool__(self) -> bool: ... @property @abstractmethod - def real(self) -> SupportsFloat: ... + def real(self) -> _RealLike: ... @property @abstractmethod - def imag(self) -> SupportsFloat: ... + def imag(self) -> _RealLike: ... @abstractmethod - def __add__(self, other) -> _SupportsComplex: ... + def __add__(self, other) -> _ComplexLike: ... @abstractmethod - def __radd__(self, other) -> _SupportsComplex: ... + def __radd__(self, other) -> _ComplexLike: ... @abstractmethod - def __neg__(self) -> _SupportsComplex: ... + def __neg__(self) -> _ComplexLike: ... @abstractmethod - def __pos__(self) -> _SupportsComplex: ... - def __sub__(self, other) -> _SupportsComplex: ... - def __rsub__(self, other) -> _SupportsComplex: ... + def __pos__(self) -> _ComplexLike: ... + def __sub__(self, other) -> _ComplexLike: ... + def __rsub__(self, other) -> _ComplexLike: ... @abstractmethod - def __mul__(self, other) -> _SupportsComplex: ... + def __mul__(self, other) -> _ComplexLike: ... @abstractmethod - def __rmul__(self, other) -> _SupportsComplex: ... + def __rmul__(self, other) -> _ComplexLike: ... @abstractmethod - def __truediv__(self, other) -> _SupportsComplex: ... + def __truediv__(self, other) -> _ComplexLike: ... @abstractmethod - def __rtruediv__(self, other) -> _SupportsComplex: ... + def __rtruediv__(self, other) -> _ComplexLike: ... @abstractmethod - def __pow__(self, exponent) -> _SupportsComplex: ... + def __pow__(self, exponent) -> _ComplexLike: ... @abstractmethod - def __rpow__(self, base) -> _SupportsComplex: ... + def __rpow__(self, base) -> _ComplexLike: ... @abstractmethod - def __abs__(self) -> SupportsFloat: ... + def __abs__(self) -> _RealLike: ... @abstractmethod - def conjugate(self) -> _SupportsComplex: ... + def conjugate(self) -> _ComplexLike: ... @abstractmethod def __eq__(self, other: object) -> bool: ... # See comment at the top of the file # for why some of these return types are purposefully vague -class Real(Complex, SupportsFloat): +class Real(Complex, _RealLike): @abstractmethod def __float__(self) -> float: ... @abstractmethod - def __trunc__(self) -> SupportsIndex: ... + def __trunc__(self) -> _IntegralLike: ... @abstractmethod - def __floor__(self) -> SupportsIndex: ... + def __floor__(self) -> _IntegralLike: ... @abstractmethod - def __ceil__(self) -> SupportsIndex: ... + def __ceil__(self) -> _IntegralLike: ... @abstractmethod @overload - def __round__(self, ndigits: None = None) -> SupportsIndex: ... + def __round__(self, ndigits: None = None) -> _IntegralLike: ... @abstractmethod @overload - def __round__(self, ndigits: int) -> SupportsFloat: ... - def __divmod__(self, other) -> tuple[SupportsFloat, SupportsFloat]: ... - def __rdivmod__(self, other) -> tuple[SupportsFloat, SupportsFloat]: ... + def __round__(self, ndigits: int) -> _RealLike: ... + def __divmod__(self, other) -> tuple[_RealLike, _RealLike]: ... + def __rdivmod__(self, other) -> tuple[_RealLike, _RealLike]: ... @abstractmethod - def __floordiv__(self, other) -> SupportsFloat: ... + def __floordiv__(self, other) -> _RealLike: ... @abstractmethod - def __rfloordiv__(self, other) -> SupportsFloat: ... + def __rfloordiv__(self, other) -> _RealLike: ... @abstractmethod - def __mod__(self, other) -> SupportsFloat: ... + def __mod__(self, other) -> _RealLike: ... @abstractmethod - def __rmod__(self, other) -> SupportsFloat: ... + def __rmod__(self, other) -> _RealLike: ... @abstractmethod def __lt__(self, other) -> bool: ... @abstractmethod def __le__(self, other) -> bool: ... def __complex__(self) -> complex: ... @property - def real(self) -> SupportsFloat: ... + def real(self) -> _RealLike: ... @property def imag(self) -> Literal[0]: ... - def conjugate(self) -> SupportsFloat: ... # type: ignore[override] + def conjugate(self) -> _RealLike: ... + # Not actually overridden at runtime, + # but we override these in the stub to give them more precise return types: + @abstractmethod + def __pos__(self) -> _RealLike: ... + @abstractmethod + def __neg__(self) -> _RealLike: ... # See comment at the top of the file # for why some of these return types are purposefully vague class Rational(Real): @property @abstractmethod - def numerator(self) -> SupportsIndex: ... + def numerator(self) -> _IntegralLike: ... @property @abstractmethod - def denominator(self) -> SupportsIndex: ... + def denominator(self) -> _IntegralLike: ... def __float__(self) -> float: ... # See comment at the top of the file # for why some of these return types are purposefully vague -class Integral(Rational): +class Integral(Rational, _IntegralLike): @abstractmethod def __int__(self) -> int: ... def __index__(self) -> int: ... @abstractmethod - def __pow__(self, exponent, modulus: Incomplete | None = None) -> SupportsIndex: ... # type: ignore[override] + def __pow__(self, exponent, modulus: Incomplete | None = None) -> _IntegralLike: ... @abstractmethod - def __lshift__(self, other) -> SupportsIndex: ... + def __lshift__(self, other) -> _IntegralLike: ... @abstractmethod - def __rlshift__(self, other) -> SupportsIndex: ... + def __rlshift__(self, other) -> _IntegralLike: ... @abstractmethod - def __rshift__(self, other) -> SupportsIndex: ... + def __rshift__(self, other) -> _IntegralLike: ... @abstractmethod - def __rrshift__(self, other) -> SupportsIndex: ... + def __rrshift__(self, other) -> _IntegralLike: ... @abstractmethod - def __and__(self, other) -> SupportsIndex: ... + def __and__(self, other) -> _IntegralLike: ... @abstractmethod - def __rand__(self, other) -> SupportsIndex: ... + def __rand__(self, other) -> _IntegralLike: ... @abstractmethod - def __xor__(self, other) -> SupportsIndex: ... + def __xor__(self, other) -> _IntegralLike: ... @abstractmethod - def __rxor__(self, other) -> SupportsIndex: ... + def __rxor__(self, other) -> _IntegralLike: ... @abstractmethod - def __or__(self, other) -> SupportsIndex: ... + def __or__(self, other) -> _IntegralLike: ... @abstractmethod - def __ror__(self, other) -> SupportsIndex: ... + def __ror__(self, other) -> _IntegralLike: ... @abstractmethod - def __invert__(self) -> SupportsIndex: ... + def __invert__(self) -> _IntegralLike: ... def __float__(self) -> float: ... @property - def numerator(self) -> SupportsIndex: ... + def numerator(self) -> _IntegralLike: ... @property def denominator(self) -> Literal[1]: ... + # Not actually overridden at runtime, + # but we override these in the stub to give them more precise return types: + @abstractmethod + def __pos__(self) -> _IntegralLike: ... + @abstractmethod + def __neg__(self) -> _IntegralLike: ... + @abstractmethod + def __abs__(self) -> _IntegralLike: ... + @abstractmethod + @overload + def __round__(self, ndigits: None = None) -> _IntegralLike: ... + @abstractmethod + @overload + def __round__(self, ndigits: int) -> _IntegralLike: ... diff --git a/mypy/typeshed/stdlib/os/__init__.pyi b/mypy/typeshed/stdlib/os/__init__.pyi index b57678635c07..eef52e7a8b3b 100644 --- a/mypy/typeshed/stdlib/os/__init__.pyi +++ b/mypy/typeshed/stdlib/os/__init__.pyi @@ -40,7 +40,7 @@ from typing import ( overload, runtime_checkable, ) -from typing_extensions import Self, TypeAlias, Unpack +from typing_extensions import Self, TypeAlias, Unpack, deprecated from . import path as _path @@ -308,7 +308,8 @@ if sys.platform != "win32": EX_NOPERM: int EX_CONFIG: int -if sys.platform != "win32" and sys.platform != "darwin": +# Exists on some Unix platforms, e.g. Solaris. +if sys.platform != "win32" and sys.platform != "darwin" and sys.platform != "linux": EX_NOTFOUND: int P_NOWAIT: int @@ -361,8 +362,16 @@ class stat_result(structseq[float], tuple[int, int, int, int, int, int, int, flo @property def st_mtime(self) -> float: ... # time of most recent content modification, # platform dependent (time of most recent metadata change on Unix, or the time of creation on Windows) - @property - def st_ctime(self) -> float: ... + if sys.version_info >= (3, 12) and sys.platform == "win32": + @property + @deprecated( + "Use st_birthtime instead to retrieve the file creation time. In the future, this property will contain the last metadata change time." + ) + def st_ctime(self) -> float: ... + else: + @property + def st_ctime(self) -> float: ... + @property def st_atime_ns(self) -> int: ... # time of most recent access, in nanoseconds @property @@ -860,8 +869,8 @@ if sys.platform != "win32": def abort() -> NoReturn: ... # These are defined as execl(file, *args) but the first *arg is mandatory. -def execl(file: StrOrBytesPath, __arg0: StrOrBytesPath, *args: StrOrBytesPath) -> NoReturn: ... -def execlp(file: StrOrBytesPath, __arg0: StrOrBytesPath, *args: StrOrBytesPath) -> NoReturn: ... +def execl(file: StrOrBytesPath, *args: Unpack[tuple[StrOrBytesPath, Unpack[tuple[StrOrBytesPath, ...]]]]) -> NoReturn: ... +def execlp(file: StrOrBytesPath, *args: Unpack[tuple[StrOrBytesPath, Unpack[tuple[StrOrBytesPath, ...]]]]) -> NoReturn: ... # These are: execle(file, *args, env) but env is pulled from the last element of the args. def execle( diff --git a/mypy/typeshed/stdlib/posix.pyi b/mypy/typeshed/stdlib/posix.pyi index 6cba003bbd5f..b31b8f3d3524 100644 --- a/mypy/typeshed/stdlib/posix.pyi +++ b/mypy/typeshed/stdlib/posix.pyi @@ -239,9 +239,11 @@ if sys.platform != "win32": if sys.platform != "linux": from os import chflags as chflags, lchflags as lchflags, lchmod as lchmod + if sys.platform != "linux" and sys.platform != "darwin": + from os import EX_NOTFOUND as EX_NOTFOUND + if sys.platform != "darwin": from os import ( - EX_NOTFOUND as EX_NOTFOUND, POSIX_FADV_DONTNEED as POSIX_FADV_DONTNEED, POSIX_FADV_NOREUSE as POSIX_FADV_NOREUSE, POSIX_FADV_NORMAL as POSIX_FADV_NORMAL, diff --git a/mypy/typeshed/stdlib/queue.pyi b/mypy/typeshed/stdlib/queue.pyi index 3537e445ed97..d7cae5f2ac79 100644 --- a/mypy/typeshed/stdlib/queue.pyi +++ b/mypy/typeshed/stdlib/queue.pyi @@ -12,6 +12,9 @@ _T = TypeVar("_T") class Empty(Exception): ... class Full(Exception): ... +if sys.version_info >= (3, 13): + class ShutDown(Exception): ... + class Queue(Generic[_T]): maxsize: int @@ -20,6 +23,8 @@ class Queue(Generic[_T]): not_full: Condition # undocumented all_tasks_done: Condition # undocumented unfinished_tasks: int # undocumented + if sys.version_info >= (3, 13): + is_shutdown: bool # undocumented # Despite the fact that `queue` has `deque` type, # we treat it as `Any` to allow different implementations in subtypes. queue: Any # undocumented @@ -29,6 +34,9 @@ class Queue(Generic[_T]): def full(self) -> bool: ... def get(self, block: bool = True, timeout: float | None = None) -> _T: ... def get_nowait(self) -> _T: ... + if sys.version_info >= (3, 13): + def shutdown(self, immediate: bool = False) -> None: ... + def _get(self) -> _T: ... def put(self, item: _T, block: bool = True, timeout: float | None = None) -> None: ... def put_nowait(self, item: _T) -> None: ... diff --git a/mypy/typeshed/stdlib/shlex.pyi b/mypy/typeshed/stdlib/shlex.pyi index 3fda03b5694a..daa8df439b26 100644 --- a/mypy/typeshed/stdlib/shlex.pyi +++ b/mypy/typeshed/stdlib/shlex.pyi @@ -1,13 +1,32 @@ +import sys +from collections import deque from collections.abc import Iterable -from typing import TextIO -from typing_extensions import Self +from io import TextIOWrapper +from typing import Literal, Protocol, overload, type_check_only +from typing_extensions import Self, deprecated __all__ = ["shlex", "split", "quote", "join"] -def split(s: str, comments: bool = False, posix: bool = True) -> list[str]: ... +@type_check_only +class _ShlexInstream(Protocol): + def read(self, size: Literal[1], /) -> str: ... + def readline(self) -> object: ... + def close(self) -> object: ... + +if sys.version_info >= (3, 12): + def split(s: str | _ShlexInstream, comments: bool = False, posix: bool = True) -> list[str]: ... + +else: + @overload + def split(s: str | _ShlexInstream, comments: bool = False, posix: bool = True) -> list[str]: ... + @overload + @deprecated("Passing None for 's' to shlex.split() is deprecated and will raise an error in Python 3.12.") + def split(s: None, comments: bool = False, posix: bool = True) -> list[str]: ... + def join(split_command: Iterable[str]) -> str: ... def quote(s: str) -> str: ... +# TODO: Make generic over infile once PEP 696 is implemented. class shlex(Iterable[str]): commenters: str wordchars: str @@ -17,17 +36,18 @@ class shlex(Iterable[str]): escapedquotes: str whitespace_split: bool infile: str | None - instream: TextIO + instream: _ShlexInstream source: str debug: int lineno: int token: str + filestack: deque[tuple[str | None, _ShlexInstream, int]] eof: str | None @property def punctuation_chars(self) -> str: ... def __init__( self, - instream: str | TextIO | None = None, + instream: str | _ShlexInstream | None = None, infile: str | None = None, posix: bool = False, punctuation_chars: bool | str = False, @@ -35,8 +55,8 @@ class shlex(Iterable[str]): def get_token(self) -> str | None: ... def push_token(self, tok: str) -> None: ... def read_token(self) -> str | None: ... - def sourcehook(self, newfile: str) -> tuple[str, TextIO] | None: ... - def push_source(self, newstream: str | TextIO, newfile: str | None = None) -> None: ... + def sourcehook(self, newfile: str) -> tuple[str, TextIOWrapper] | None: ... + def push_source(self, newstream: str | _ShlexInstream, newfile: str | None = None) -> None: ... def pop_source(self) -> None: ... def error_leader(self, infile: str | None = None, lineno: int | None = None) -> str: ... def __iter__(self) -> Self: ... diff --git a/mypy/typeshed/stdlib/shutil.pyi b/mypy/typeshed/stdlib/shutil.pyi index f6440aa27513..a06181ce876d 100644 --- a/mypy/typeshed/stdlib/shutil.pyi +++ b/mypy/typeshed/stdlib/shutil.pyi @@ -4,7 +4,7 @@ from _typeshed import BytesPath, FileDescriptorOrPath, StrOrBytesPath, StrPath, from collections.abc import Callable, Iterable, Sequence from tarfile import _TarfileFilter from typing import Any, AnyStr, NamedTuple, Protocol, TypeVar, overload -from typing_extensions import TypeAlias +from typing_extensions import TypeAlias, deprecated __all__ = [ "copyfileobj", @@ -78,24 +78,20 @@ class _RmtreeType(Protocol): avoids_symlink_attacks: bool if sys.version_info >= (3, 12): @overload + def __call__(self, path: StrOrBytesPath, ignore_errors: bool = False, *, dir_fd: int | None = None) -> None: ... + @overload + @deprecated("The `onerror` parameter is deprecated and will be removed in Python 3.14. Use `onexc` instead.") def __call__( self, path: StrOrBytesPath, ignore_errors: bool = False, onerror: _OnErrorCallback | None = None, *, - onexc: None = None, dir_fd: int | None = None, ) -> None: ... @overload def __call__( - self, - path: StrOrBytesPath, - ignore_errors: bool = False, - onerror: None = None, - *, - onexc: _OnExcCallback, - dir_fd: int | None = None, + self, path: StrOrBytesPath, ignore_errors: bool = False, *, onexc: _OnExcCallback, dir_fd: int | None = None ) -> None: ... elif sys.version_info >= (3, 11): def __call__( diff --git a/mypy/typeshed/stdlib/sqlite3/dbapi2.pyi b/mypy/typeshed/stdlib/sqlite3/dbapi2.pyi index 659545c50b41..7cf75bbc33c5 100644 --- a/mypy/typeshed/stdlib/sqlite3/dbapi2.pyi +++ b/mypy/typeshed/stdlib/sqlite3/dbapi2.pyi @@ -221,16 +221,32 @@ def adapt(__obj: Any, __proto: Any) -> Any: ... @overload def adapt(__obj: Any, __proto: Any, __alt: _T) -> Any | _T: ... def complete_statement(statement: str) -> bool: ... -def connect( - database: StrOrBytesPath, - timeout: float = ..., - detect_types: int = ..., - isolation_level: str | None = ..., - check_same_thread: bool = ..., - factory: type[Connection] | None = ..., - cached_statements: int = ..., - uri: bool = ..., -) -> Connection: ... + +if sys.version_info >= (3, 12): + def connect( + database: StrOrBytesPath, + timeout: float = ..., + detect_types: int = ..., + isolation_level: str | None = ..., + check_same_thread: bool = ..., + factory: type[Connection] | None = ..., + cached_statements: int = ..., + uri: bool = ..., + autocommit: bool = ..., + ) -> Connection: ... + +else: + def connect( + database: StrOrBytesPath, + timeout: float = ..., + detect_types: int = ..., + isolation_level: str | None = ..., + check_same_thread: bool = ..., + factory: type[Connection] | None = ..., + cached_statements: int = ..., + uri: bool = ..., + ) -> Connection: ... + def enable_callback_tracebacks(__enable: bool) -> None: ... if sys.version_info < (3, 12): @@ -300,17 +316,32 @@ class Connection: def autocommit(self, val: int) -> None: ... row_factory: Any text_factory: Any - def __init__( - self, - database: StrOrBytesPath, - timeout: float = ..., - detect_types: int = ..., - isolation_level: str | None = ..., - check_same_thread: bool = ..., - factory: type[Connection] | None = ..., - cached_statements: int = ..., - uri: bool = ..., - ) -> None: ... + if sys.version_info >= (3, 12): + def __init__( + self, + database: StrOrBytesPath, + timeout: float = ..., + detect_types: int = ..., + isolation_level: str | None = ..., + check_same_thread: bool = ..., + factory: type[Connection] | None = ..., + cached_statements: int = ..., + uri: bool = ..., + autocommit: bool = ..., + ) -> None: ... + else: + def __init__( + self, + database: StrOrBytesPath, + timeout: float = ..., + detect_types: int = ..., + isolation_level: str | None = ..., + check_same_thread: bool = ..., + factory: type[Connection] | None = ..., + cached_statements: int = ..., + uri: bool = ..., + ) -> None: ... + def close(self) -> None: ... if sys.version_info >= (3, 11): def blobopen(self, __table: str, __column: str, __row: int, *, readonly: bool = False, name: str = "main") -> Blob: ... diff --git a/mypy/typeshed/stdlib/sysconfig.pyi b/mypy/typeshed/stdlib/sysconfig.pyi index 2edb71d78cdd..807a979050e8 100644 --- a/mypy/typeshed/stdlib/sysconfig.pyi +++ b/mypy/typeshed/stdlib/sysconfig.pyi @@ -1,5 +1,6 @@ import sys from typing import IO, Any, Literal, overload +from typing_extensions import deprecated __all__ = [ "get_config_h_filename", @@ -15,11 +16,15 @@ __all__ = [ "parse_config_h", ] +@overload +@deprecated("SO is deprecated, use EXT_SUFFIX. Support is removed in Python 3.11") +def get_config_var(name: Literal["SO"]) -> Any: ... +@overload def get_config_var(name: str) -> Any: ... @overload def get_config_vars() -> dict[str, Any]: ... @overload -def get_config_vars(arg: str, *args: str) -> list[Any]: ... +def get_config_vars(arg: str, /, *args: str) -> list[Any]: ... def get_scheme_names() -> tuple[str, ...]: ... if sys.version_info >= (3, 10): diff --git a/mypy/typeshed/stdlib/tarfile.pyi b/mypy/typeshed/stdlib/tarfile.pyi index 0bfd91ce2161..47c831190286 100644 --- a/mypy/typeshed/stdlib/tarfile.pyi +++ b/mypy/typeshed/stdlib/tarfile.pyi @@ -292,6 +292,8 @@ class TarFile: def getnames(self) -> _list[str]: ... def list(self, verbose: bool = True, *, members: _list[TarInfo] | None = None) -> None: ... def next(self) -> TarInfo | None: ... + # Calling this method without `filter` is deprecated, but it may be set either on the class or in an + # individual call, so we can't mark it as @deprecated here. def extractall( self, path: StrOrBytesPath = ".", @@ -300,6 +302,7 @@ class TarFile: numeric_owner: bool = False, filter: _TarfileFilter | None = ..., ) -> None: ... + # Same situation as for `extractall`. def extract( self, member: str | TarInfo, diff --git a/mypy/typeshed/stdlib/tkinter/__init__.pyi b/mypy/typeshed/stdlib/tkinter/__init__.pyi index 4733c31b5bae..3f65eb2c8fe4 100644 --- a/mypy/typeshed/stdlib/tkinter/__init__.pyi +++ b/mypy/typeshed/stdlib/tkinter/__init__.pyi @@ -665,7 +665,7 @@ class Wm: iconmask = wm_iconmask def wm_iconname(self, newName: Incomplete | None = None) -> str: ... iconname = wm_iconname - def wm_iconphoto(self, default: bool, __image1: _PhotoImageLike | str, *args: _PhotoImageLike | str) -> None: ... + def wm_iconphoto(self, default: bool, image1: _PhotoImageLike | str, /, *args: _PhotoImageLike | str) -> None: ... iconphoto = wm_iconphoto def wm_iconposition(self, x: int | None = None, y: int | None = None) -> tuple[int, int] | None: ... iconposition = wm_iconposition @@ -1721,7 +1721,9 @@ class Canvas(Widget, XView, YView): def tag_raise(self, __first: str | int, __second: str | int | None = ...) -> None: ... def tkraise(self, __first: str | int, __second: str | int | None = ...) -> None: ... # type: ignore[override] def lift(self, __first: str | int, __second: str | int | None = ...) -> None: ... # type: ignore[override] - def scale(self, *args) -> None: ... + def scale( + self, __tagOrId: str | int, __xOrigin: _ScreenUnits, __yOrigin: _ScreenUnits, __xScale: float, __yScale: float + ) -> None: ... def scan_mark(self, x, y) -> None: ... def scan_dragto(self, x, y, gain: int = 10) -> None: ... def select_adjust(self, tagOrId, index) -> None: ... diff --git a/mypy/typeshed/stdlib/types.pyi b/mypy/typeshed/stdlib/types.pyi index 05ffc2143233..05c5e85e4a9e 100644 --- a/mypy/typeshed/stdlib/types.pyi +++ b/mypy/typeshed/stdlib/types.pyi @@ -17,7 +17,7 @@ from importlib.machinery import ModuleSpec # pytype crashes if types.MappingProxyType inherits from collections.abc.Mapping instead of typing.Mapping from typing import Any, ClassVar, Literal, Mapping, Protocol, TypeVar, final, overload # noqa: Y022 -from typing_extensions import ParamSpec, Self, TypeVarTuple +from typing_extensions import ParamSpec, Self, TypeVarTuple, deprecated __all__ = [ "FunctionType", @@ -138,8 +138,14 @@ class CodeType: def co_name(self) -> str: ... @property def co_firstlineno(self) -> int: ... - @property - def co_lnotab(self) -> bytes: ... + if sys.version_info >= (3, 10): + @property + @deprecated("Will be removed in Python 3.14. Use the co_lines() method instead.") + def co_lnotab(self) -> bytes: ... + else: + @property + def co_lnotab(self) -> bytes: ... + @property def co_freevars(self) -> tuple[str, ...]: ... @property diff --git a/mypy/typeshed/stdlib/typing_extensions.pyi b/mypy/typeshed/stdlib/typing_extensions.pyi index ea5c7b21aa87..921c1334cfe4 100644 --- a/mypy/typeshed/stdlib/typing_extensions.pyi +++ b/mypy/typeshed/stdlib/typing_extensions.pyi @@ -182,6 +182,7 @@ __all__ = [ "no_type_check", "no_type_check_decorator", "ReadOnly", + "TypeIs", ] _T = typing.TypeVar("_T") @@ -220,10 +221,14 @@ def IntVar(name: str) -> Any: ... # returns a new TypeVar class _TypedDict(Mapping[str, object], metaclass=abc.ABCMeta): __required_keys__: ClassVar[frozenset[str]] __optional_keys__: ClassVar[frozenset[str]] - __readonly_keys__: ClassVar[frozenset[str]] - __mutable_keys__: ClassVar[frozenset[str]] __total__: ClassVar[bool] __orig_bases__: ClassVar[tuple[Any, ...]] + # PEP 705 + __readonly_keys__: ClassVar[frozenset[str]] + __mutable_keys__: ClassVar[frozenset[str]] + # PEP 728 + __closed__: ClassVar[bool] + __extra_items__: ClassVar[Any] def copy(self) -> Self: ... # Using Never so that only calls using mypy plugin hook that specialize the signature # can go through. @@ -501,3 +506,4 @@ class Doc: def __eq__(self, other: object) -> bool: ... ReadOnly: _SpecialForm +TypeIs: _SpecialForm diff --git a/mypy/typeshed/stdlib/xml/etree/ElementTree.pyi b/mypy/typeshed/stdlib/xml/etree/ElementTree.pyi index c508f72892c1..2a363a504dec 100644 --- a/mypy/typeshed/stdlib/xml/etree/ElementTree.pyi +++ b/mypy/typeshed/stdlib/xml/etree/ElementTree.pyi @@ -3,7 +3,7 @@ from _collections_abc import dict_keys from _typeshed import FileDescriptorOrPath, ReadableBuffer, SupportsRead, SupportsWrite from collections.abc import Callable, Generator, ItemsView, Iterable, Iterator, Mapping, Sequence from typing import Any, Literal, SupportsIndex, TypeVar, overload -from typing_extensions import TypeAlias, TypeGuard +from typing_extensions import TypeAlias, TypeGuard, deprecated __all__ = [ "C14NWriterTarget", @@ -121,6 +121,10 @@ class Element: def __setitem__(self, __key: SupportsIndex, __value: Element) -> None: ... @overload def __setitem__(self, __key: slice, __value: Iterable[Element]) -> None: ... + + # Doesn't really exist in earlier versions, where __len__ is called implicitly instead + @deprecated("Testing an element's truth value is deprecated.") + def __bool__(self) -> bool: ... if sys.version_info < (3, 9): def getchildren(self) -> list[Element]: ... def getiterator(self, tag: str | None = None) -> list[Element]: ... From 055184f28dd83f20ba36cadbb7a75e5f30cf36d8 Mon Sep 17 00:00:00 2001 From: Shantanu <12621235+hauntsaninja@users.noreply.github.com> Date: Thu, 29 Feb 2024 22:02:54 -0800 Subject: [PATCH 28/54] Fix override checking for decorated property (#16856) Fixes #16855 --- mypy/checker.py | 39 +++++++++++++++----------- test-data/unit/check-functions.test | 43 +++++++++++++++++++++++++++++ 2 files changed, 66 insertions(+), 16 deletions(-) diff --git a/mypy/checker.py b/mypy/checker.py index 9f987cb5ccdf..a272a3aaac3d 100644 --- a/mypy/checker.py +++ b/mypy/checker.py @@ -2020,22 +2020,29 @@ def check_method_override_for_base_with_name( if original_node and is_property(original_node): original_type = get_property_type(original_type) - if isinstance(typ, FunctionLike) and is_property(defn): - typ = get_property_type(typ) - if ( - isinstance(original_node, Var) - and not original_node.is_final - and (not original_node.is_property or original_node.is_settable_property) - and isinstance(defn, Decorator) - ): - # We only give an error where no other similar errors will be given. - if not isinstance(original_type, AnyType): - self.msg.fail( - "Cannot override writeable attribute with read-only property", - # Give an error on function line to match old behaviour. - defn.func, - code=codes.OVERRIDE, - ) + if is_property(defn): + inner: FunctionLike | None + if isinstance(typ, FunctionLike): + inner = typ + else: + inner = self.extract_callable_type(typ, context) + if inner is not None: + typ = inner + typ = get_property_type(typ) + if ( + isinstance(original_node, Var) + and not original_node.is_final + and (not original_node.is_property or original_node.is_settable_property) + and isinstance(defn, Decorator) + ): + # We only give an error where no other similar errors will be given. + if not isinstance(original_type, AnyType): + self.msg.fail( + "Cannot override writeable attribute with read-only property", + # Give an error on function line to match old behaviour. + defn.func, + code=codes.OVERRIDE, + ) if isinstance(original_type, AnyType) or isinstance(typ, AnyType): pass diff --git a/test-data/unit/check-functions.test b/test-data/unit/check-functions.test index b3df5fddafba..3aecbe065c27 100644 --- a/test-data/unit/check-functions.test +++ b/test-data/unit/check-functions.test @@ -2730,6 +2730,49 @@ f: Callable[[Sequence[TI]], None] g: Callable[[Union[Sequence[TI], Sequence[TS]]], None] f = g +[case testOverrideDecoratedProperty] +class Base: + @property + def foo(self) -> int: ... + +class decorator: + def __init__(self, fn): + self.fn = fn + def __call__(self, decorated_self) -> int: + return self.fn(decorated_self) + +class Child(Base): + @property + @decorator + def foo(self) -> int: + return 42 + +reveal_type(Child().foo) # N: Revealed type is "builtins.int" + +class BadChild1(Base): + @decorator + def foo(self) -> int: # E: Signature of "foo" incompatible with supertype "Base" \ + # N: Superclass: \ + # N: int \ + # N: Subclass: \ + # N: decorator + return 42 + +class not_a_decorator: + def __init__(self, fn): ... + +class BadChild2(Base): + @property + @not_a_decorator + def foo(self) -> int: # E: "not_a_decorator" not callable \ + # E: Signature of "foo" incompatible with supertype "Base" \ + # N: Superclass: \ + # N: int \ + # N: Subclass: \ + # N: not_a_decorator + return 42 +[builtins fixtures/property.pyi] + [case explicitOverride] # flags: --python-version 3.12 from typing import override From 3c87af272cbf7c49699b7508c7f51365da139c05 Mon Sep 17 00:00:00 2001 From: Marc Mueller <30130371+cdce8p@users.noreply.github.com> Date: Fri, 1 Mar 2024 09:08:22 +0100 Subject: [PATCH 29/54] Allow TypedDict initialization from Type (#16963) Fixes #11644 --- mypy/checkexpr.py | 2 ++ test-data/unit/check-typeddict.test | 16 ++++++++++++++++ 2 files changed, 18 insertions(+) diff --git a/mypy/checkexpr.py b/mypy/checkexpr.py index 2842606b7b18..e893410e2b7d 100644 --- a/mypy/checkexpr.py +++ b/mypy/checkexpr.py @@ -1855,6 +1855,8 @@ def analyze_type_type_callee(self, item: ProperType, context: Context) -> Type: # We support Type of namedtuples but not of tuples in general if isinstance(item, TupleType) and tuple_fallback(item).type.fullname != "builtins.tuple": return self.analyze_type_type_callee(tuple_fallback(item), context) + if isinstance(item, TypedDictType): + return self.typeddict_callable_from_context(item) self.msg.unsupported_type_type(item, context) return AnyType(TypeOfAny.from_error) diff --git a/test-data/unit/check-typeddict.test b/test-data/unit/check-typeddict.test index adf4d210ed0c..639be7bde8d8 100644 --- a/test-data/unit/check-typeddict.test +++ b/test-data/unit/check-typeddict.test @@ -3447,3 +3447,19 @@ class Params(TypedDict("Params", {'x': int})): p: Params = {'x': 2} reveal_type(p) # N: Revealed type is "TypedDict('__main__.Params', {'x': builtins.int})" [builtins fixtures/dict.pyi] + +[case testInitTypedDictFromType] +from typing import TypedDict, Type + +class Point(TypedDict): + x: int + y: int + +def func(cls: Type[Point]) -> None: + reveal_type(cls) # N: Revealed type is "Type[TypedDict('__main__.Point', {'x': builtins.int, 'y': builtins.int})]" + cls(x=1, y=2) + cls(1, 2) # E: Too many positional arguments + cls(x=1) # E: Missing named argument "y" + cls(x=1, y=2, error="") # E: Unexpected keyword argument "error" +[typing fixtures/typing-full.pyi] +[builtins fixtures/tuple.pyi] From bcb3747f277745f7a0035bb92cc95ee83f6778dc Mon Sep 17 00:00:00 2001 From: Jelle Zijlstra Date: Fri, 1 Mar 2024 06:01:34 -0800 Subject: [PATCH 30/54] Implement TypeIs (PEP 742) (#16898) Co-authored-by: Marc Mueller <30130371+cdce8p@users.noreply.github.com> --- docs/source/error_code_list2.rst | 16 + mypy/applytype.py | 7 +- mypy/checker.py | 42 +- mypy/checkexpr.py | 13 +- mypy/constraints.py | 16 +- mypy/errorcodes.py | 6 + mypy/expandtype.py | 2 + mypy/fixup.py | 2 + mypy/message_registry.py | 5 +- mypy/messages.py | 4 + mypy/nodes.py | 3 + mypy/semanal.py | 7 + mypy/subtypes.py | 13 + mypy/typeanal.py | 27 +- mypy/types.py | 9 + test-data/unit/check-errorcodes.test | 8 + test-data/unit/check-typeguard.test | 2 +- test-data/unit/check-typeis.test | 798 ++++++++++++++++++ test-data/unit/lib-stub/typing_extensions.pyi | 1 + 19 files changed, 962 insertions(+), 19 deletions(-) create mode 100644 test-data/unit/check-typeis.test diff --git a/docs/source/error_code_list2.rst b/docs/source/error_code_list2.rst index c966fe1f7ea6..465d1c7a6583 100644 --- a/docs/source/error_code_list2.rst +++ b/docs/source/error_code_list2.rst @@ -555,3 +555,19 @@ Correct usage: When this code is enabled, using ``reveal_locals`` is always an error, because there's no way one can import it. + +.. _code-narrowed-type-not-subtype: + +Check that ``TypeIs`` narrows types [narrowed-type-not-subtype] +--------------------------------------------------------------- + +:pep:`742` requires that when ``TypeIs`` is used, the narrowed +type must be a subtype of the original type:: + + from typing_extensions import TypeIs + + def f(x: int) -> TypeIs[str]: # Error, str is not a subtype of int + ... + + def g(x: object) -> TypeIs[str]: # OK + ... diff --git a/mypy/applytype.py b/mypy/applytype.py index e14906fa2772..eecd555bf90d 100644 --- a/mypy/applytype.py +++ b/mypy/applytype.py @@ -137,11 +137,15 @@ def apply_generic_arguments( arg_types=[expand_type(at, id_to_type) for at in callable.arg_types] ) - # Apply arguments to TypeGuard if any. + # Apply arguments to TypeGuard and TypeIs if any. if callable.type_guard is not None: type_guard = expand_type(callable.type_guard, id_to_type) else: type_guard = None + if callable.type_is is not None: + type_is = expand_type(callable.type_is, id_to_type) + else: + type_is = None # The callable may retain some type vars if only some were applied. # TODO: move apply_poly() logic from checkexpr.py here when new inference @@ -164,4 +168,5 @@ def apply_generic_arguments( ret_type=expand_type(callable.ret_type, id_to_type), variables=remaining_tvars, type_guard=type_guard, + type_is=type_is, ) diff --git a/mypy/checker.py b/mypy/checker.py index a272a3aaac3d..941dc06f1c71 100644 --- a/mypy/checker.py +++ b/mypy/checker.py @@ -1203,6 +1203,22 @@ def check_func_def( # visible from *inside* of this function/method. ref_type: Type | None = self.scope.active_self_type() + if typ.type_is: + arg_index = 0 + # For methods and classmethods, we want the second parameter + if ref_type is not None and (not defn.is_static or defn.name == "__new__"): + arg_index = 1 + if arg_index < len(typ.arg_types) and not is_subtype( + typ.type_is, typ.arg_types[arg_index] + ): + self.fail( + message_registry.NARROWED_TYPE_NOT_SUBTYPE.format( + format_type(typ.type_is, self.options), + format_type(typ.arg_types[arg_index], self.options), + ), + item, + ) + # Store argument types. for i in range(len(typ.arg_types)): arg_type = typ.arg_types[i] @@ -2178,6 +2194,8 @@ def check_override( elif isinstance(original, CallableType) and isinstance(override, CallableType): if original.type_guard is not None and override.type_guard is None: fail = True + if original.type_is is not None and override.type_is is None: + fail = True if is_private(name): fail = False @@ -5643,7 +5661,7 @@ def combine_maps(list_maps: list[TypeMap]) -> TypeMap: def find_isinstance_check(self, node: Expression) -> tuple[TypeMap, TypeMap]: """Find any isinstance checks (within a chain of ands). Includes implicit and explicit checks for None and calls to callable. - Also includes TypeGuard functions. + Also includes TypeGuard and TypeIs functions. Return value is a map of variables to their types if the condition is true and a map of variables to their types if the condition is false. @@ -5695,7 +5713,7 @@ def find_isinstance_check_helper(self, node: Expression) -> tuple[TypeMap, TypeM if literal(expr) == LITERAL_TYPE and attr and len(attr) == 1: return self.hasattr_type_maps(expr, self.lookup_type(expr), attr[0]) elif isinstance(node.callee, RefExpr): - if node.callee.type_guard is not None: + if node.callee.type_guard is not None or node.callee.type_is is not None: # TODO: Follow *args, **kwargs if node.arg_kinds[0] != nodes.ARG_POS: # the first argument might be used as a kwarg @@ -5721,7 +5739,12 @@ def find_isinstance_check_helper(self, node: Expression) -> tuple[TypeMap, TypeM # we want the idx-th variable to be narrowed expr = collapse_walrus(node.args[idx]) else: - self.fail(message_registry.TYPE_GUARD_POS_ARG_REQUIRED, node) + kind = ( + "guard" if node.callee.type_guard is not None else "narrower" + ) + self.fail( + message_registry.TYPE_GUARD_POS_ARG_REQUIRED.format(kind), node + ) return {}, {} if literal(expr) == LITERAL_TYPE: # Note: we wrap the target type, so that we can special case later. @@ -5729,7 +5752,18 @@ def find_isinstance_check_helper(self, node: Expression) -> tuple[TypeMap, TypeM # considered "always right" (i.e. even if the types are not overlapping). # Also note that a care must be taken to unwrap this back at read places # where we use this to narrow down declared type. - return {expr: TypeGuardedType(node.callee.type_guard)}, {} + if node.callee.type_guard is not None: + return {expr: TypeGuardedType(node.callee.type_guard)}, {} + else: + assert node.callee.type_is is not None + return conditional_types_to_typemaps( + expr, + *self.conditional_types_with_intersection( + self.lookup_type(expr), + [TypeRange(node.callee.type_is, is_upper_bound=False)], + expr, + ), + ) elif isinstance(node, ComparisonExpr): # Step 1: Obtain the types of each operand and whether or not we can # narrow their types. (For example, we shouldn't try narrowing the diff --git a/mypy/checkexpr.py b/mypy/checkexpr.py index e893410e2b7d..37a90ce55b9e 100644 --- a/mypy/checkexpr.py +++ b/mypy/checkexpr.py @@ -1451,13 +1451,12 @@ def check_call_expr_with_callee_type( object_type=object_type, ) proper_callee = get_proper_type(callee_type) - if ( - isinstance(e.callee, RefExpr) - and isinstance(proper_callee, CallableType) - and proper_callee.type_guard is not None - ): + if isinstance(e.callee, RefExpr) and isinstance(proper_callee, CallableType): # Cache it for find_isinstance_check() - e.callee.type_guard = proper_callee.type_guard + if proper_callee.type_guard is not None: + e.callee.type_guard = proper_callee.type_guard + if proper_callee.type_is is not None: + e.callee.type_is = proper_callee.type_is return ret_type def check_union_call_expr(self, e: CallExpr, object_type: UnionType, member: str) -> Type: @@ -5283,7 +5282,7 @@ def infer_lambda_type_using_context( # is a constructor -- but this fallback doesn't make sense for lambdas. callable_ctx = callable_ctx.copy_modified(fallback=self.named_type("builtins.function")) - if callable_ctx.type_guard is not None: + if callable_ctx.type_guard is not None or callable_ctx.type_is is not None: # Lambda's return type cannot be treated as a `TypeGuard`, # because it is implicit. And `TypeGuard`s must be explicit. # See https://github.com/python/mypy/issues/9927 diff --git a/mypy/constraints.py b/mypy/constraints.py index c4eba2ca1ede..cdfa39ac45f3 100644 --- a/mypy/constraints.py +++ b/mypy/constraints.py @@ -1018,10 +1018,22 @@ def visit_callable_type(self, template: CallableType) -> list[Constraint]: param_spec = template.param_spec() template_ret_type, cactual_ret_type = template.ret_type, cactual.ret_type - if template.type_guard is not None: + if template.type_guard is not None and cactual.type_guard is not None: template_ret_type = template.type_guard - if cactual.type_guard is not None: cactual_ret_type = cactual.type_guard + elif template.type_guard is not None: + template_ret_type = AnyType(TypeOfAny.special_form) + elif cactual.type_guard is not None: + cactual_ret_type = AnyType(TypeOfAny.special_form) + + if template.type_is is not None and cactual.type_is is not None: + template_ret_type = template.type_is + cactual_ret_type = cactual.type_is + elif template.type_is is not None: + template_ret_type = AnyType(TypeOfAny.special_form) + elif cactual.type_is is not None: + cactual_ret_type = AnyType(TypeOfAny.special_form) + res.extend(infer_constraints(template_ret_type, cactual_ret_type, self.direction)) if param_spec is None: diff --git a/mypy/errorcodes.py b/mypy/errorcodes.py index 72ee63a6a897..688bd6a4ddd5 100644 --- a/mypy/errorcodes.py +++ b/mypy/errorcodes.py @@ -281,5 +281,11 @@ def __hash__(self) -> int: sub_code_of=MISC, ) +NARROWED_TYPE_NOT_SUBTYPE: Final[ErrorCode] = ErrorCode( + "narrowed-type-not-subtype", + "Warn if a TypeIs function's narrowed type is not a subtype of the original type", + "General", +) + # This copy will not include any error codes defined later in the plugins. mypy_error_codes = error_codes.copy() diff --git a/mypy/expandtype.py b/mypy/expandtype.py index 3bf45854b2a0..ec6a2ecfd0d2 100644 --- a/mypy/expandtype.py +++ b/mypy/expandtype.py @@ -351,6 +351,7 @@ def visit_callable_type(self, t: CallableType) -> CallableType: arg_names=t.arg_names[:-2] + repl.arg_names, ret_type=t.ret_type.accept(self), type_guard=(t.type_guard.accept(self) if t.type_guard is not None else None), + type_is=(t.type_is.accept(self) if t.type_is is not None else None), imprecise_arg_kinds=(t.imprecise_arg_kinds or repl.imprecise_arg_kinds), variables=[*repl.variables, *t.variables], ) @@ -384,6 +385,7 @@ def visit_callable_type(self, t: CallableType) -> CallableType: arg_types=arg_types, ret_type=t.ret_type.accept(self), type_guard=(t.type_guard.accept(self) if t.type_guard is not None else None), + type_is=(t.type_is.accept(self) if t.type_is is not None else None), ) if needs_normalization: return expanded.with_normalized_var_args() diff --git a/mypy/fixup.py b/mypy/fixup.py index 02c6ab93f29e..849a6483d724 100644 --- a/mypy/fixup.py +++ b/mypy/fixup.py @@ -270,6 +270,8 @@ def visit_callable_type(self, ct: CallableType) -> None: arg.accept(self) if ct.type_guard is not None: ct.type_guard.accept(self) + if ct.type_is is not None: + ct.type_is.accept(self) def visit_overloaded(self, t: Overloaded) -> None: for ct in t.items: diff --git a/mypy/message_registry.py b/mypy/message_registry.py index fb430b63c74b..ccc1443dacf0 100644 --- a/mypy/message_registry.py +++ b/mypy/message_registry.py @@ -262,7 +262,7 @@ def with_additional_msg(self, info: str) -> ErrorMessage: CONTIGUOUS_ITERABLE_EXPECTED: Final = ErrorMessage("Contiguous iterable with same type expected") ITERABLE_TYPE_EXPECTED: Final = ErrorMessage("Invalid type '{}' for *expr (iterable expected)") -TYPE_GUARD_POS_ARG_REQUIRED: Final = ErrorMessage("Type guard requires positional argument") +TYPE_GUARD_POS_ARG_REQUIRED: Final = ErrorMessage("Type {} requires positional argument") # Match Statement MISSING_MATCH_ARGS: Final = 'Class "{}" doesn\'t define "__match_args__"' @@ -324,3 +324,6 @@ def with_additional_msg(self, info: str) -> ErrorMessage: ARG_NAME_EXPECTED_STRING_LITERAL: Final = ErrorMessage( "Expected string literal for argument name, got {}", codes.SYNTAX ) +NARROWED_TYPE_NOT_SUBTYPE: Final = ErrorMessage( + "Narrowed type {} is not a subtype of input type {}", codes.NARROWED_TYPE_NOT_SUBTYPE +) diff --git a/mypy/messages.py b/mypy/messages.py index db6c91ba9008..92b57ef781a2 100644 --- a/mypy/messages.py +++ b/mypy/messages.py @@ -2643,6 +2643,8 @@ def format_literal_value(typ: LiteralType) -> str: elif isinstance(func, CallableType): if func.type_guard is not None: return_type = f"TypeGuard[{format(func.type_guard)}]" + elif func.type_is is not None: + return_type = f"TypeIs[{format(func.type_is)}]" else: return_type = format(func.ret_type) if func.is_ellipsis_args: @@ -2859,6 +2861,8 @@ def [T <: int] f(self, x: int, y: T) -> None s += " -> " if tp.type_guard is not None: s += f"TypeGuard[{format_type_bare(tp.type_guard, options)}]" + elif tp.type_is is not None: + s += f"TypeIs[{format_type_bare(tp.type_is, options)}]" else: s += format_type_bare(tp.ret_type, options) diff --git a/mypy/nodes.py b/mypy/nodes.py index 1c781320580a..bb278d92392d 100644 --- a/mypy/nodes.py +++ b/mypy/nodes.py @@ -1755,6 +1755,7 @@ class RefExpr(Expression): "is_inferred_def", "is_alias_rvalue", "type_guard", + "type_is", ) def __init__(self) -> None: @@ -1776,6 +1777,8 @@ def __init__(self) -> None: self.is_alias_rvalue = False # Cache type guard from callable_type.type_guard self.type_guard: mypy.types.Type | None = None + # And same for TypeIs + self.type_is: mypy.types.Type | None = None @property def fullname(self) -> str: diff --git a/mypy/semanal.py b/mypy/semanal.py index 38d5ddec0818..6bf02382a036 100644 --- a/mypy/semanal.py +++ b/mypy/semanal.py @@ -881,6 +881,13 @@ def analyze_func_def(self, defn: FuncDef) -> None: ) # in this case, we just kind of just ... remove the type guard. result = result.copy_modified(type_guard=None) + if result.type_is and ARG_POS not in result.arg_kinds[skip_self:]: + self.fail( + '"TypeIs" functions must have a positional argument', + result, + code=codes.VALID_TYPE, + ) + result = result.copy_modified(type_is=None) result = self.remove_unpack_kwargs(defn, result) if has_self_type and self.type is not None: diff --git a/mypy/subtypes.py b/mypy/subtypes.py index 2d536f892a2a..4d5e7335b14f 100644 --- a/mypy/subtypes.py +++ b/mypy/subtypes.py @@ -683,10 +683,23 @@ def visit_callable_type(self, left: CallableType) -> bool: if left.type_guard is not None and right.type_guard is not None: if not self._is_subtype(left.type_guard, right.type_guard): return False + elif left.type_is is not None and right.type_is is not None: + # For TypeIs we have to check both ways; it is unsafe to pass + # a TypeIs[Child] when a TypeIs[Parent] is expected, because + # if the narrower returns False, we assume that the narrowed value is + # *not* a Parent. + if not self._is_subtype(left.type_is, right.type_is) or not self._is_subtype( + right.type_is, left.type_is + ): + return False elif right.type_guard is not None and left.type_guard is None: # This means that one function has `TypeGuard` and other does not. # They are not compatible. See https://github.com/python/mypy/issues/11307 return False + elif right.type_is is not None and left.type_is is None: + # Similarly, if one function has `TypeIs` and the other does not, + # they are not compatible. + return False return is_callable_compatible( left, right, diff --git a/mypy/typeanal.py b/mypy/typeanal.py index 9cc0114df333..8a9ac8f4ac31 100644 --- a/mypy/typeanal.py +++ b/mypy/typeanal.py @@ -668,7 +668,10 @@ def try_analyze_special_unbound_type(self, t: UnboundType, fullname: str) -> Typ ) return AnyType(TypeOfAny.from_error) return RequiredType(self.anal_type(t.args[0]), required=False) - elif self.anal_type_guard_arg(t, fullname) is not None: + elif ( + self.anal_type_guard_arg(t, fullname) is not None + or self.anal_type_is_arg(t, fullname) is not None + ): # In most contexts, TypeGuard[...] acts as an alias for bool (ignoring its args) return self.named_type("builtins.bool") elif fullname in ("typing.Unpack", "typing_extensions.Unpack"): @@ -986,7 +989,8 @@ def visit_callable_type(self, t: CallableType, nested: bool = True) -> Type: variables = t.variables else: variables, _ = self.bind_function_type_variables(t, t) - special = self.anal_type_guard(t.ret_type) + type_guard = self.anal_type_guard(t.ret_type) + type_is = self.anal_type_is(t.ret_type) arg_kinds = t.arg_kinds if len(arg_kinds) >= 2 and arg_kinds[-2] == ARG_STAR and arg_kinds[-1] == ARG_STAR2: arg_types = self.anal_array(t.arg_types[:-2], nested=nested) + [ @@ -1041,7 +1045,8 @@ def visit_callable_type(self, t: CallableType, nested: bool = True) -> Type: # its type will be the falsey FakeInfo fallback=(t.fallback if t.fallback.type else self.named_type("builtins.function")), variables=self.anal_var_defs(variables), - type_guard=special, + type_guard=type_guard, + type_is=type_is, unpack_kwargs=unpacked_kwargs, ) return ret @@ -1064,6 +1069,22 @@ def anal_type_guard_arg(self, t: UnboundType, fullname: str) -> Type | None: return self.anal_type(t.args[0]) return None + def anal_type_is(self, t: Type) -> Type | None: + if isinstance(t, UnboundType): + sym = self.lookup_qualified(t.name, t) + if sym is not None and sym.node is not None: + return self.anal_type_is_arg(t, sym.node.fullname) + # TODO: What if it's an Instance? Then use t.type.fullname? + return None + + def anal_type_is_arg(self, t: UnboundType, fullname: str) -> Type | None: + if fullname in ("typing_extensions.TypeIs", "typing.TypeIs"): + if len(t.args) != 1: + self.fail("TypeIs must have exactly one type argument", t, code=codes.VALID_TYPE) + return AnyType(TypeOfAny.from_error) + return self.anal_type(t.args[0]) + return None + def anal_star_arg_type(self, t: Type, kind: ArgKind, nested: bool) -> Type: """Analyze signature argument type for *args and **kwargs argument.""" if isinstance(t, UnboundType) and t.name and "." in t.name and not t.args: diff --git a/mypy/types.py b/mypy/types.py index f76e35784d8f..b34efde15b31 100644 --- a/mypy/types.py +++ b/mypy/types.py @@ -1800,6 +1800,7 @@ class CallableType(FunctionLike): "def_extras", # Information about original definition we want to serialize. # This is used for more detailed error messages. "type_guard", # T, if -> TypeGuard[T] (ret_type is bool in this case). + "type_is", # T, if -> TypeIs[T] (ret_type is bool in this case). "from_concatenate", # whether this callable is from a concatenate object # (this is used for error messages) "imprecise_arg_kinds", @@ -1826,6 +1827,7 @@ def __init__( bound_args: Sequence[Type | None] = (), def_extras: dict[str, Any] | None = None, type_guard: Type | None = None, + type_is: Type | None = None, from_concatenate: bool = False, imprecise_arg_kinds: bool = False, unpack_kwargs: bool = False, @@ -1875,6 +1877,7 @@ def __init__( else: self.def_extras = {} self.type_guard = type_guard + self.type_is = type_is self.unpack_kwargs = unpack_kwargs def copy_modified( @@ -1896,6 +1899,7 @@ def copy_modified( bound_args: Bogus[list[Type | None]] = _dummy, def_extras: Bogus[dict[str, Any]] = _dummy, type_guard: Bogus[Type | None] = _dummy, + type_is: Bogus[Type | None] = _dummy, from_concatenate: Bogus[bool] = _dummy, imprecise_arg_kinds: Bogus[bool] = _dummy, unpack_kwargs: Bogus[bool] = _dummy, @@ -1920,6 +1924,7 @@ def copy_modified( bound_args=bound_args if bound_args is not _dummy else self.bound_args, def_extras=def_extras if def_extras is not _dummy else dict(self.def_extras), type_guard=type_guard if type_guard is not _dummy else self.type_guard, + type_is=type_is if type_is is not _dummy else self.type_is, from_concatenate=( from_concatenate if from_concatenate is not _dummy else self.from_concatenate ), @@ -2233,6 +2238,7 @@ def serialize(self) -> JsonDict: "bound_args": [(None if t is None else t.serialize()) for t in self.bound_args], "def_extras": dict(self.def_extras), "type_guard": self.type_guard.serialize() if self.type_guard is not None else None, + "type_is": (self.type_is.serialize() if self.type_is is not None else None), "from_concatenate": self.from_concatenate, "imprecise_arg_kinds": self.imprecise_arg_kinds, "unpack_kwargs": self.unpack_kwargs, @@ -2257,6 +2263,7 @@ def deserialize(cls, data: JsonDict) -> CallableType: type_guard=( deserialize_type(data["type_guard"]) if data["type_guard"] is not None else None ), + type_is=(deserialize_type(data["type_is"]) if data["type_is"] is not None else None), from_concatenate=data["from_concatenate"], imprecise_arg_kinds=data["imprecise_arg_kinds"], unpack_kwargs=data["unpack_kwargs"], @@ -3315,6 +3322,8 @@ def visit_callable_type(self, t: CallableType) -> str: if not isinstance(get_proper_type(t.ret_type), NoneType): if t.type_guard is not None: s += f" -> TypeGuard[{t.type_guard.accept(self)}]" + elif t.type_is is not None: + s += f" -> TypeIs[{t.type_is.accept(self)}]" else: s += f" -> {t.ret_type.accept(self)}" diff --git a/test-data/unit/check-errorcodes.test b/test-data/unit/check-errorcodes.test index 7f5f05d37595..9d49480539e0 100644 --- a/test-data/unit/check-errorcodes.test +++ b/test-data/unit/check-errorcodes.test @@ -1182,3 +1182,11 @@ class D(C): def other(self) -> None: self.bad2: int = 5 # E: Covariant override of a mutable attribute (base class "C" defined the type as "float", expression has type "int") [mutable-override] [builtins fixtures/property.pyi] + +[case testNarrowedTypeNotSubtype] +from typing_extensions import TypeIs + +def f(x: str) -> TypeIs[int]: # E: Narrowed type "int" is not a subtype of input type "str" [narrowed-type-not-subtype] + pass + +[builtins fixtures/tuple.pyi] diff --git a/test-data/unit/check-typeguard.test b/test-data/unit/check-typeguard.test index c48887bb016a..66c21bf3abe1 100644 --- a/test-data/unit/check-typeguard.test +++ b/test-data/unit/check-typeguard.test @@ -504,7 +504,7 @@ def with_bool(o: object) -> bool: pass accepts_typeguard(with_bool_typeguard) accepts_typeguard(with_str_typeguard) -accepts_typeguard(with_bool) # E: Argument 1 to "accepts_typeguard" has incompatible type "Callable[[object], bool]"; expected "Callable[[object], TypeGuard[bool]]" +accepts_typeguard(with_bool) # E: Argument 1 to "accepts_typeguard" has incompatible type "Callable[[object], bool]"; expected "Callable[[object], TypeGuard[Never]]" [builtins fixtures/tuple.pyi] [case testTypeGuardAsOverloadedFunctionArg] diff --git a/test-data/unit/check-typeis.test b/test-data/unit/check-typeis.test new file mode 100644 index 000000000000..04b64a45c8c1 --- /dev/null +++ b/test-data/unit/check-typeis.test @@ -0,0 +1,798 @@ +[case testTypeIsBasic] +from typing_extensions import TypeIs +class Point: pass +def is_point(a: object) -> TypeIs[Point]: pass +def main(a: object) -> None: + if is_point(a): + reveal_type(a) # N: Revealed type is "__main__.Point" + else: + reveal_type(a) # N: Revealed type is "builtins.object" +[builtins fixtures/tuple.pyi] + +[case testTypeIsElif] +from typing_extensions import TypeIs +from typing import Union +class Point: pass +def is_point(a: object) -> TypeIs[Point]: pass +class Line: pass +def is_line(a: object) -> TypeIs[Line]: pass +def main(a: Union[Point, Line, int]) -> None: + if is_point(a): + reveal_type(a) # N: Revealed type is "__main__.Point" + elif is_line(a): + reveal_type(a) # N: Revealed type is "__main__.Line" + else: + reveal_type(a) # N: Revealed type is "builtins.int" + +[builtins fixtures/tuple.pyi] + +[case testTypeIsTypeArgsNone] +from typing_extensions import TypeIs +def foo(a: object) -> TypeIs: # E: TypeIs must have exactly one type argument + pass +[builtins fixtures/tuple.pyi] + +[case testTypeIsTypeArgsTooMany] +from typing_extensions import TypeIs +def foo(a: object) -> TypeIs[int, int]: # E: TypeIs must have exactly one type argument + pass +[builtins fixtures/tuple.pyi] + +[case testTypeIsTypeArgType] +from typing_extensions import TypeIs +def foo(a: object) -> TypeIs[42]: # E: Invalid type: try using Literal[42] instead? + pass +[builtins fixtures/tuple.pyi] + +[case testTypeIsRepr] +from typing_extensions import TypeIs +def foo(a: object) -> TypeIs[int]: + pass +reveal_type(foo) # N: Revealed type is "def (a: builtins.object) -> TypeIs[builtins.int]" +[builtins fixtures/tuple.pyi] + +[case testTypeIsCallArgsNone] +from typing_extensions import TypeIs +class Point: pass + +def is_point() -> TypeIs[Point]: pass # E: "TypeIs" functions must have a positional argument +def main(a: object) -> None: + if is_point(): + reveal_type(a) # N: Revealed type is "builtins.object" +[builtins fixtures/tuple.pyi] + +[case testTypeIsCallArgsMultiple] +from typing_extensions import TypeIs +class Point: pass +def is_point(a: object, b: object) -> TypeIs[Point]: pass +def main(a: object, b: object) -> None: + if is_point(a, b): + reveal_type(a) # N: Revealed type is "__main__.Point" + reveal_type(b) # N: Revealed type is "builtins.object" +[builtins fixtures/tuple.pyi] + +[case testTypeIsIsBool] +from typing_extensions import TypeIs +def f(a: TypeIs[int]) -> None: pass +reveal_type(f) # N: Revealed type is "def (a: builtins.bool)" +a: TypeIs[int] +reveal_type(a) # N: Revealed type is "builtins.bool" +class C: + a: TypeIs[int] +reveal_type(C().a) # N: Revealed type is "builtins.bool" +[builtins fixtures/tuple.pyi] + +[case testTypeIsWithTypeVar] +from typing import TypeVar, Tuple, Type +from typing_extensions import TypeIs +T = TypeVar('T') +def is_tuple_of_type(a: Tuple[object, ...], typ: Type[T]) -> TypeIs[Tuple[T, ...]]: pass +def main(a: Tuple[object, ...]): + if is_tuple_of_type(a, int): + reveal_type(a) # N: Revealed type is "builtins.tuple[builtins.int, ...]" +[builtins fixtures/tuple.pyi] + +[case testTypeIsUnionIn] +from typing import Union +from typing_extensions import TypeIs +def is_foo(a: Union[int, str]) -> TypeIs[str]: pass +def main(a: Union[str, int]) -> None: + if is_foo(a): + reveal_type(a) # N: Revealed type is "builtins.str" + else: + reveal_type(a) # N: Revealed type is "builtins.int" + reveal_type(a) # N: Revealed type is "Union[builtins.str, builtins.int]" +[builtins fixtures/tuple.pyi] + +[case testTypeIsUnionOut] +from typing import Union +from typing_extensions import TypeIs +def is_foo(a: object) -> TypeIs[Union[int, str]]: pass +def main(a: object) -> None: + if is_foo(a): + reveal_type(a) # N: Revealed type is "Union[builtins.int, builtins.str]" +[builtins fixtures/tuple.pyi] + +[case testTypeIsNonzeroFloat] +from typing_extensions import TypeIs +def is_nonzero(a: object) -> TypeIs[float]: pass +def main(a: int): + if is_nonzero(a): + reveal_type(a) # N: Revealed type is "builtins.int" +[builtins fixtures/tuple.pyi] + +[case testTypeIsHigherOrder] +from typing import Callable, TypeVar, Iterable, List +from typing_extensions import TypeIs +T = TypeVar('T') +R = TypeVar('R') +def filter(f: Callable[[T], TypeIs[R]], it: Iterable[T]) -> Iterable[R]: pass +def is_float(a: object) -> TypeIs[float]: pass +a: List[object] = ["a", 0, 0.0] +b = filter(is_float, a) +reveal_type(b) # N: Revealed type is "typing.Iterable[builtins.float]" +[builtins fixtures/tuple.pyi] + +[case testTypeIsMethod] +from typing_extensions import TypeIs +class C: + def main(self, a: object) -> None: + if self.is_float(a): + reveal_type(self) # N: Revealed type is "__main__.C" + reveal_type(a) # N: Revealed type is "builtins.float" + def is_float(self, a: object) -> TypeIs[float]: pass +[builtins fixtures/tuple.pyi] + +[case testTypeIsCrossModule] +import guard +from points import Point +def main(a: object) -> None: + if guard.is_point(a): + reveal_type(a) # N: Revealed type is "points.Point" +[file guard.py] +from typing_extensions import TypeIs +import points +def is_point(a: object) -> TypeIs[points.Point]: pass +[file points.py] +class Point: pass +[builtins fixtures/tuple.pyi] + +[case testTypeIsBodyRequiresBool] +from typing_extensions import TypeIs +def is_float(a: object) -> TypeIs[float]: + return "not a bool" # E: Incompatible return value type (got "str", expected "bool") +[builtins fixtures/tuple.pyi] + +[case testTypeIsNarrowToTypedDict] +from typing import Mapping, TypedDict +from typing_extensions import TypeIs +class User(TypedDict): + name: str + id: int +def is_user(a: Mapping[str, object]) -> TypeIs[User]: + return isinstance(a.get("name"), str) and isinstance(a.get("id"), int) +def main(a: Mapping[str, object]) -> None: + if is_user(a): + reveal_type(a) # N: Revealed type is "TypedDict('__main__.User', {'name': builtins.str, 'id': builtins.int})" +[builtins fixtures/dict.pyi] +[typing fixtures/typing-typeddict.pyi] + +[case testTypeIsInAssert] +from typing_extensions import TypeIs +def is_float(a: object) -> TypeIs[float]: pass +def main(a: object) -> None: + assert is_float(a) + reveal_type(a) # N: Revealed type is "builtins.float" +[builtins fixtures/tuple.pyi] + +[case testTypeIsFromAny] +from typing import Any +from typing_extensions import TypeIs +def is_objfloat(a: object) -> TypeIs[float]: pass +def is_anyfloat(a: Any) -> TypeIs[float]: pass +def objmain(a: object) -> None: + if is_objfloat(a): + reveal_type(a) # N: Revealed type is "builtins.float" + if is_anyfloat(a): + reveal_type(a) # N: Revealed type is "builtins.float" +def anymain(a: Any) -> None: + if is_objfloat(a): + reveal_type(a) # N: Revealed type is "builtins.float" + if is_anyfloat(a): + reveal_type(a) # N: Revealed type is "builtins.float" +[builtins fixtures/tuple.pyi] + +[case testTypeIsNegatedAndElse] +from typing import Union +from typing_extensions import TypeIs +def is_int(a: object) -> TypeIs[int]: pass +def is_str(a: object) -> TypeIs[str]: pass +def intmain(a: Union[int, str]) -> None: + if not is_int(a): + reveal_type(a) # N: Revealed type is "builtins.str" + else: + reveal_type(a) # N: Revealed type is "builtins.int" +def strmain(a: Union[int, str]) -> None: + if is_str(a): + reveal_type(a) # N: Revealed type is "builtins.str" + else: + reveal_type(a) # N: Revealed type is "builtins.int" +[builtins fixtures/tuple.pyi] + +[case testTypeIsClassMethod] +from typing_extensions import TypeIs +class C: + @classmethod + def is_float(cls, a: object) -> TypeIs[float]: pass + def method(self, a: object) -> None: + if self.is_float(a): + reveal_type(a) # N: Revealed type is "builtins.float" +def main(a: object) -> None: + if C.is_float(a): + reveal_type(a) # N: Revealed type is "builtins.float" +[builtins fixtures/classmethod.pyi] + +[case testTypeIsRequiresPositionalArgs] +from typing_extensions import TypeIs +def is_float(a: object, b: object = 0) -> TypeIs[float]: pass +def main1(a: object) -> None: + if is_float(a=a, b=1): + reveal_type(a) # N: Revealed type is "builtins.float" + + if is_float(b=1, a=a): + reveal_type(a) # N: Revealed type is "builtins.float" + +[builtins fixtures/tuple.pyi] + +[case testTypeIsOverload] +from typing import overload, Any, Callable, Iterable, Iterator, List, Optional, TypeVar +from typing_extensions import TypeIs + +T = TypeVar("T") +R = TypeVar("R") + +@overload +def filter(f: Callable[[T], TypeIs[R]], it: Iterable[T]) -> Iterator[R]: ... +@overload +def filter(f: Callable[[T], bool], it: Iterable[T]) -> Iterator[T]: ... +def filter(*args): pass + +def is_int_typeis(a: object) -> TypeIs[int]: pass +def is_int_bool(a: object) -> bool: pass + +def main(a: List[Optional[int]]) -> None: + bb = filter(lambda x: x is not None, a) + reveal_type(bb) # N: Revealed type is "typing.Iterator[Union[builtins.int, None]]" + # Also, if you replace 'bool' with 'Any' in the second overload, bb is Iterator[Any] + cc = filter(is_int_typeis, a) + reveal_type(cc) # N: Revealed type is "typing.Iterator[builtins.int]" + dd = filter(is_int_bool, a) + reveal_type(dd) # N: Revealed type is "typing.Iterator[Union[builtins.int, None]]" + +[builtins fixtures/tuple.pyi] +[typing fixtures/typing-full.pyi] + +[case testTypeIsDecorated] +from typing import TypeVar +from typing_extensions import TypeIs +T = TypeVar("T") +def decorator(f: T) -> T: pass +@decorator +def is_float(a: object) -> TypeIs[float]: + pass +def main(a: object) -> None: + if is_float(a): + reveal_type(a) # N: Revealed type is "builtins.float" +[builtins fixtures/tuple.pyi] + +[case testTypeIsMethodOverride] +from typing_extensions import TypeIs +class C: + def is_float(self, a: object) -> TypeIs[float]: pass +class D(C): + def is_float(self, a: object) -> bool: pass # Fail +[builtins fixtures/tuple.pyi] +[out] +main:5: error: Signature of "is_float" incompatible with supertype "C" +main:5: note: Superclass: +main:5: note: def is_float(self, a: object) -> TypeIs[float] +main:5: note: Subclass: +main:5: note: def is_float(self, a: object) -> bool + +[case testTypeIsInAnd] +from typing import Any +from typing_extensions import TypeIs +def isclass(a: object) -> bool: + pass +def isfloat(a: object) -> TypeIs[float]: + pass +def isstr(a: object) -> TypeIs[str]: + pass + +def coverage1(obj: Any) -> bool: + if isfloat(obj) and obj.__self__ is not None and isclass(obj.__self__): # E: "float" has no attribute "__self__" + reveal_type(obj) # N: Revealed type is "builtins.float" + return True + reveal_type(obj) # N: Revealed type is "Any" + return False + +def coverage2(obj: Any) -> bool: + if not (isfloat(obj) or isstr(obj)): + reveal_type(obj) # N: Revealed type is "Any" + return True + reveal_type(obj) # N: Revealed type is "Union[builtins.float, builtins.str]" + return False +[builtins fixtures/classmethod.pyi] + +[case testAssignToTypeIsedVariable1] +from typing_extensions import TypeIs + +class A: pass +class B(A): pass + +def guard(a: A) -> TypeIs[B]: + pass + +a = A() +if not guard(a): + a = A() +[builtins fixtures/tuple.pyi] + +[case testAssignToTypeIsedVariable2] +from typing_extensions import TypeIs + +class A: pass +class B: pass + +def guard(a: object) -> TypeIs[B]: + pass + +a = A() +if not guard(a): + a = A() +[builtins fixtures/tuple.pyi] + +[case testAssignToTypeIsedVariable3] +from typing_extensions import TypeIs + +class A: pass +class B: pass + +def guard(a: object) -> TypeIs[B]: + pass + +a = A() +if guard(a): + reveal_type(a) # N: Revealed type is "__main__." + a = B() # E: Incompatible types in assignment (expression has type "B", variable has type "A") + reveal_type(a) # N: Revealed type is "__main__." + a = A() + reveal_type(a) # N: Revealed type is "__main__.A" +reveal_type(a) # N: Revealed type is "__main__.A" +[builtins fixtures/tuple.pyi] + +[case testTypeIsNestedRestrictionAny] +from typing_extensions import TypeIs +from typing import Any + +class A: ... +def f(x: object) -> TypeIs[A]: ... +def g(x: object) -> None: ... + +def test(x: Any) -> None: + if not(f(x) or x): + return + g(reveal_type(x)) # N: Revealed type is "Union[__main__.A, Any]" +[builtins fixtures/tuple.pyi] + +[case testTypeIsNestedRestrictionUnionOther] +from typing_extensions import TypeIs +from typing import Any + +class A: ... +class B: ... +def f(x: object) -> TypeIs[A]: ... +def f2(x: object) -> TypeIs[B]: ... +def g(x: object) -> None: ... + +def test(x: object) -> None: + if not(f(x) or f2(x)): + return + g(reveal_type(x)) # N: Revealed type is "Union[__main__.A, __main__.B]" +[builtins fixtures/tuple.pyi] + +[case testTypeIsComprehensionSubtype] +from typing import List +from typing_extensions import TypeIs + +class Base: ... +class Foo(Base): ... +class Bar(Base): ... + +def is_foo(item: object) -> TypeIs[Foo]: + return isinstance(item, Foo) + +def is_bar(item: object) -> TypeIs[Bar]: + return isinstance(item, Bar) + +def foobar(items: List[object]): + a: List[Base] = [x for x in items if is_foo(x) or is_bar(x)] + b: List[Base] = [x for x in items if is_foo(x)] + c: List[Foo] = [x for x in items if is_foo(x)] + d: List[Bar] = [x for x in items if is_foo(x)] # E: List comprehension has incompatible type List[Foo]; expected List[Bar] +[builtins fixtures/tuple.pyi] + +[case testTypeIsNestedRestrictionUnionIsInstance] +from typing_extensions import TypeIs +from typing import Any, List + +class A: ... +def f(x: List[Any]) -> TypeIs[List[str]]: ... +def g(x: object) -> None: ... + +def test(x: List[Any]) -> None: + if not(f(x) or isinstance(x, A)): + return + g(reveal_type(x)) # N: Revealed type is "Union[builtins.list[builtins.str], __main__.]" +[builtins fixtures/tuple.pyi] + +[case testTypeIsMultipleCondition] +from typing_extensions import TypeIs +from typing import Any, List + +class Foo: ... +class Bar: ... + +def is_foo(item: object) -> TypeIs[Foo]: + return isinstance(item, Foo) + +def is_bar(item: object) -> TypeIs[Bar]: + return isinstance(item, Bar) + +def foobar(x: object): + if not isinstance(x, Foo) or not isinstance(x, Bar): + return + reveal_type(x) # N: Revealed type is "__main__." + +def foobar_typeis(x: object): + if not is_foo(x) or not is_bar(x): + return + # Looks like a typo but this is what our unique name generation produces + reveal_type(x) # N: Revealed type is "__main__.1" +[builtins fixtures/tuple.pyi] + +[case testTypeIsAsFunctionArgAsBoolSubtype] +from typing import Callable +from typing_extensions import TypeIs + +def accepts_bool(f: Callable[[object], bool]): pass + +def with_bool_typeis(o: object) -> TypeIs[bool]: pass +def with_str_typeis(o: object) -> TypeIs[str]: pass +def with_bool(o: object) -> bool: pass + +accepts_bool(with_bool_typeis) +accepts_bool(with_str_typeis) +accepts_bool(with_bool) +[builtins fixtures/tuple.pyi] + +[case testTypeIsAsFunctionArg] +from typing import Callable +from typing_extensions import TypeIs + +def accepts_typeis(f: Callable[[object], TypeIs[bool]]): pass +def different_typeis(f: Callable[[object], TypeIs[str]]): pass + +def with_typeis(o: object) -> TypeIs[bool]: pass +def with_bool(o: object) -> bool: pass + +accepts_typeis(with_typeis) +accepts_typeis(with_bool) # E: Argument 1 to "accepts_typeis" has incompatible type "Callable[[object], bool]"; expected "Callable[[object], TypeIs[bool]]" + +different_typeis(with_typeis) # E: Argument 1 to "different_typeis" has incompatible type "Callable[[object], TypeIs[bool]]"; expected "Callable[[object], TypeIs[str]]" +different_typeis(with_bool) # E: Argument 1 to "different_typeis" has incompatible type "Callable[[object], bool]"; expected "Callable[[object], TypeIs[str]]" +[builtins fixtures/tuple.pyi] + +[case testTypeIsAsGenericFunctionArg] +from typing import Callable, TypeVar +from typing_extensions import TypeIs + +T = TypeVar('T') + +def accepts_typeis(f: Callable[[object], TypeIs[T]]): pass + +def with_bool_typeis(o: object) -> TypeIs[bool]: pass +def with_str_typeis(o: object) -> TypeIs[str]: pass +def with_bool(o: object) -> bool: pass + +accepts_typeis(with_bool_typeis) +accepts_typeis(with_str_typeis) +accepts_typeis(with_bool) # E: Argument 1 to "accepts_typeis" has incompatible type "Callable[[object], bool]"; expected "Callable[[object], TypeIs[Never]]" +[builtins fixtures/tuple.pyi] + +[case testTypeIsAsOverloadedFunctionArg] +# https://github.com/python/mypy/issues/11307 +from typing import Callable, TypeVar, Generic, Any, overload +from typing_extensions import TypeIs + +_T = TypeVar('_T') + +class filter(Generic[_T]): + @overload + def __init__(self, function: Callable[[object], TypeIs[_T]]) -> None: pass + @overload + def __init__(self, function: Callable[[_T], Any]) -> None: pass + def __init__(self, function): pass + +def is_int_typeis(a: object) -> TypeIs[int]: pass +def returns_bool(a: object) -> bool: pass + +reveal_type(filter(is_int_typeis)) # N: Revealed type is "__main__.filter[builtins.int]" +reveal_type(filter(returns_bool)) # N: Revealed type is "__main__.filter[builtins.object]" +[builtins fixtures/tuple.pyi] + +[case testTypeIsSubtypingVariance] +from typing import Callable +from typing_extensions import TypeIs + +class A: pass +class B(A): pass +class C(B): pass + +def accepts_typeis(f: Callable[[object], TypeIs[B]]): pass + +def with_typeis_a(o: object) -> TypeIs[A]: pass +def with_typeis_b(o: object) -> TypeIs[B]: pass +def with_typeis_c(o: object) -> TypeIs[C]: pass + +accepts_typeis(with_typeis_a) # E: Argument 1 to "accepts_typeis" has incompatible type "Callable[[object], TypeIs[A]]"; expected "Callable[[object], TypeIs[B]]" +accepts_typeis(with_typeis_b) +accepts_typeis(with_typeis_c) # E: Argument 1 to "accepts_typeis" has incompatible type "Callable[[object], TypeIs[C]]"; expected "Callable[[object], TypeIs[B]]" +[builtins fixtures/tuple.pyi] + +[case testTypeIsWithIdentityGeneric] +from typing import TypeVar +from typing_extensions import TypeIs + +_T = TypeVar("_T") + +def identity(val: _T) -> TypeIs[_T]: + pass + +def func1(name: _T): + reveal_type(name) # N: Revealed type is "_T`-1" + if identity(name): + reveal_type(name) # N: Revealed type is "_T`-1" + +def func2(name: str): + reveal_type(name) # N: Revealed type is "builtins.str" + if identity(name): + reveal_type(name) # N: Revealed type is "builtins.str" +[builtins fixtures/tuple.pyi] + +[case testTypeIsWithGenericOnSecondParam] +from typing import TypeVar +from typing_extensions import TypeIs + +_R = TypeVar("_R") + +def guard(val: object, param: _R) -> TypeIs[_R]: + pass + +def func1(name: object): + reveal_type(name) # N: Revealed type is "builtins.object" + if guard(name, name): + reveal_type(name) # N: Revealed type is "builtins.object" + if guard(name, 1): + reveal_type(name) # N: Revealed type is "builtins.int" + +def func2(name: int): + reveal_type(name) # N: Revealed type is "builtins.int" + if guard(name, True): + reveal_type(name) # N: Revealed type is "builtins.bool" +[builtins fixtures/tuple.pyi] + +[case testTypeIsWithGenericInstance] +from typing import TypeVar, List, Iterable +from typing_extensions import TypeIs + +_T = TypeVar("_T") + +def is_list_of_str(val: Iterable[_T]) -> TypeIs[List[_T]]: + pass + +def func(name: Iterable[str]): + reveal_type(name) # N: Revealed type is "typing.Iterable[builtins.str]" + if is_list_of_str(name): + reveal_type(name) # N: Revealed type is "builtins.list[builtins.str]" +[builtins fixtures/tuple.pyi] + +[case testTypeIsWithTupleGeneric] +from typing import TypeVar, Tuple +from typing_extensions import TypeIs + +_T = TypeVar("_T") + +def is_two_element_tuple(val: Tuple[_T, ...]) -> TypeIs[Tuple[_T, _T]]: + pass + +def func(names: Tuple[str, ...]): + reveal_type(names) # N: Revealed type is "builtins.tuple[builtins.str, ...]" + if is_two_element_tuple(names): + reveal_type(names) # N: Revealed type is "Tuple[builtins.str, builtins.str]" +[builtins fixtures/tuple.pyi] + +[case testTypeIsErroneousDefinitionFails] +from typing_extensions import TypeIs + +class Z: + def typeis1(self, *, x: object) -> TypeIs[int]: # E: "TypeIs" functions must have a positional argument + ... + + @staticmethod + def typeis2(x: object) -> TypeIs[int]: + ... + + @staticmethod + def typeis3(*, x: object) -> TypeIs[int]: # E: "TypeIs" functions must have a positional argument + ... + +def bad_typeis(*, x: object) -> TypeIs[int]: # E: "TypeIs" functions must have a positional argument + ... + +[builtins fixtures/classmethod.pyi] + +[case testTypeIsWithKeywordArg] +from typing_extensions import TypeIs + +class Z: + def typeis(self, x: object) -> TypeIs[int]: + ... + +def typeis(x: object) -> TypeIs[int]: + ... + +n: object +if typeis(x=n): + reveal_type(n) # N: Revealed type is "builtins.int" + +if Z().typeis(x=n): + reveal_type(n) # N: Revealed type is "builtins.int" +[builtins fixtures/tuple.pyi] + +[case testStaticMethodTypeIs] +from typing_extensions import TypeIs + +class Y: + @staticmethod + def typeis(h: object) -> TypeIs[int]: + ... + +x: object +if Y().typeis(x): + reveal_type(x) # N: Revealed type is "builtins.int" +if Y.typeis(x): + reveal_type(x) # N: Revealed type is "builtins.int" +[builtins fixtures/classmethod.pyi] + +[case testTypeIsKwargFollowingThroughOverloaded] +from typing import overload, Union +from typing_extensions import TypeIs + +@overload +def typeis(x: object, y: str) -> TypeIs[str]: + ... + +@overload +def typeis(x: object, y: int) -> TypeIs[int]: + ... + +def typeis(x: object, y: Union[int, str]) -> Union[TypeIs[int], TypeIs[str]]: + ... + +x: object +if typeis(x=x, y=42): + reveal_type(x) # N: Revealed type is "builtins.int" + +if typeis(y=42, x=x): + reveal_type(x) # N: Revealed type is "builtins.int" + +if typeis(x=x, y="42"): + reveal_type(x) # N: Revealed type is "builtins.str" + +if typeis(y="42", x=x): + reveal_type(x) # N: Revealed type is "builtins.str" +[builtins fixtures/tuple.pyi] + +[case testGenericAliasWithTypeIs] +from typing import Callable, List, TypeVar +from typing_extensions import TypeIs + +T = TypeVar('T') +A = Callable[[object], TypeIs[List[T]]] +def foo(x: object) -> TypeIs[List[str]]: ... + +def test(f: A[T]) -> T: ... +reveal_type(test(foo)) # N: Revealed type is "builtins.str" +[builtins fixtures/list.pyi] + +[case testNoCrashOnDunderCallTypeIs] +from typing_extensions import TypeIs + +class A: + def __call__(self, x) -> TypeIs[int]: + return True + +a: A +assert a(x=1) + +x: object +assert a(x=x) +reveal_type(x) # N: Revealed type is "builtins.int" +[builtins fixtures/tuple.pyi] + +[case testTypeIsMustBeSubtypeFunctions] +from typing_extensions import TypeIs +from typing import List, Sequence, TypeVar + +def f(x: str) -> TypeIs[int]: # E: Narrowed type "int" is not a subtype of input type "str" + pass + +T = TypeVar('T') + +def g(x: List[T]) -> TypeIs[Sequence[T]]: # E: Narrowed type "Sequence[T]" is not a subtype of input type "List[T]" + pass + +[builtins fixtures/tuple.pyi] + +[case testTypeIsMustBeSubtypeMethods] +from typing_extensions import TypeIs + +class NarrowHolder: + @classmethod + def cls_narrower_good(cls, x: object) -> TypeIs[int]: + pass + + @classmethod + def cls_narrower_bad(cls, x: str) -> TypeIs[int]: # E: Narrowed type "int" is not a subtype of input type "str" + pass + + @staticmethod + def static_narrower_good(x: object) -> TypeIs[int]: + pass + + @staticmethod + def static_narrower_bad(x: str) -> TypeIs[int]: # E: Narrowed type "int" is not a subtype of input type "str" + pass + + def inst_narrower_good(self, x: object) -> TypeIs[int]: + pass + + def inst_narrower_bad(self, x: str) -> TypeIs[int]: # E: Narrowed type "int" is not a subtype of input type "str" + pass + + +[builtins fixtures/classmethod.pyi] + +[case testTypeIsTypeGuardNoSubtyping] +from typing_extensions import TypeGuard, TypeIs +from typing import Callable + +def accept_typeis(x: Callable[[object], TypeIs[str]]): + pass + +def accept_typeguard(x: Callable[[object], TypeGuard[str]]): + pass + +def typeis(x: object) -> TypeIs[str]: + pass + +def typeguard(x: object) -> TypeGuard[str]: + pass + +accept_typeis(typeis) +accept_typeis(typeguard) # E: Argument 1 to "accept_typeis" has incompatible type "Callable[[object], TypeGuard[str]]"; expected "Callable[[object], TypeIs[str]]" +accept_typeguard(typeis) # E: Argument 1 to "accept_typeguard" has incompatible type "Callable[[object], TypeIs[str]]"; expected "Callable[[object], TypeGuard[str]]" +accept_typeguard(typeguard) + +[builtins fixtures/tuple.pyi] diff --git a/test-data/unit/lib-stub/typing_extensions.pyi b/test-data/unit/lib-stub/typing_extensions.pyi index 68dd985cfe2a..18b6c8fc477c 100644 --- a/test-data/unit/lib-stub/typing_extensions.pyi +++ b/test-data/unit/lib-stub/typing_extensions.pyi @@ -34,6 +34,7 @@ Concatenate: _SpecialForm TypeAlias: _SpecialForm TypeGuard: _SpecialForm +TypeIs: _SpecialForm Never: _SpecialForm TypeVarTuple: _SpecialForm From 87437b86129a2d6f88137c014241d3610b39a77a Mon Sep 17 00:00:00 2001 From: Jelle Zijlstra Date: Fri, 1 Mar 2024 10:50:28 -0800 Subject: [PATCH 31/54] Add incremental tests for TypeGuard/TypeIs (#16976) --- test-data/unit/check-incremental.test | 76 +++++++++++++++++++ test-data/unit/lib-stub/typing_extensions.pyi | 5 +- 2 files changed, 79 insertions(+), 2 deletions(-) diff --git a/test-data/unit/check-incremental.test b/test-data/unit/check-incremental.test index 69381227ca8e..42faa8c627ba 100644 --- a/test-data/unit/check-incremental.test +++ b/test-data/unit/check-incremental.test @@ -6574,3 +6574,79 @@ class TheClass: [out] [out2] tmp/a.py:3: note: Revealed type is "def (value: builtins.object) -> lib.TheClass.pyenum@6" + +[case testStartUsingTypeGuard] +import a +[file a.py] +from lib import guard +from typing import Union +from typing_extensions import assert_type +x: Union[int, str] + +[file a.py.2] +from lib import guard +from typing import Union +from typing_extensions import assert_type +x: Union[int, str] +if guard(x): + assert_type(x, int) +else: + assert_type(x, Union[int, str]) +[file lib.py] +from typing_extensions import TypeGuard +def guard(x: object) -> TypeGuard[int]: + pass +[builtins fixtures/tuple.pyi] + +[case testStartUsingTypeIs] +import a +[file a.py] +from lib import guard +from typing import Union +from typing_extensions import assert_type +x: Union[int, str] + +[file a.py.2] +from lib import guard +from typing import Union +from typing_extensions import assert_type +x: Union[int, str] +if guard(x): + assert_type(x, int) +else: + assert_type(x, str) +[file lib.py] +from typing_extensions import TypeIs +def guard(x: object) -> TypeIs[int]: + pass +[builtins fixtures/tuple.pyi] + +[case testTypeGuardToTypeIs] +import a +[file a.py] +from lib import guard +from typing import Union +from typing_extensions import assert_type +x: Union[int, str] +if guard(x): + assert_type(x, int) +else: + assert_type(x, Union[int, str]) +[file a.py.2] +from lib import guard +from typing import Union +from typing_extensions import assert_type +x: Union[int, str] +if guard(x): + assert_type(x, int) +else: + assert_type(x, str) +[file lib.py] +from typing_extensions import TypeGuard +def guard(x: object) -> TypeGuard[int]: + pass +[file lib.py.2] +from typing_extensions import TypeIs +def guard(x: object) -> TypeIs[int]: + pass +[builtins fixtures/tuple.pyi] diff --git a/test-data/unit/lib-stub/typing_extensions.pyi b/test-data/unit/lib-stub/typing_extensions.pyi index 18b6c8fc477c..ff55f1b54c7d 100644 --- a/test-data/unit/lib-stub/typing_extensions.pyi +++ b/test-data/unit/lib-stub/typing_extensions.pyi @@ -68,7 +68,8 @@ class _TypedDict(Mapping[str, object]): def TypedDict(typename: str, fields: Dict[str, Type[_T]], *, total: Any = ...) -> Type[dict]: ... -def reveal_type(__obj: T) -> T: pass +def reveal_type(__obj: _T) -> _T: pass +def assert_type(__val: _T, __typ: Any) -> _T: pass def dataclass_transform( *, @@ -77,7 +78,7 @@ def dataclass_transform( kw_only_default: bool = ..., field_specifiers: tuple[type[Any] | Callable[..., Any], ...] = ..., **kwargs: Any, -) -> Callable[[T], T]: ... +) -> Callable[[_T], _T]: ... def override(__arg: _T) -> _T: ... def deprecated(__msg: str) -> Callable[[_T], _T]: ... From 9f36d7c07d251c37f281a6a62d3b96dc12c09e44 Mon Sep 17 00:00:00 2001 From: youkaichao Date: Sat, 2 Mar 2024 03:04:56 +0800 Subject: [PATCH 32/54] docs: Add missing ClassVar import (#16962) --- docs/source/cheat_sheet_py3.rst | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/source/cheat_sheet_py3.rst b/docs/source/cheat_sheet_py3.rst index 7ae8eeb59d66..b8e43960fd09 100644 --- a/docs/source/cheat_sheet_py3.rst +++ b/docs/source/cheat_sheet_py3.rst @@ -152,6 +152,8 @@ Classes .. code-block:: python + from typing import ClassVar + class BankAccount: # The "__init__" method doesn't return anything, so it gets return # type "None" just like any other method that doesn't return anything From 42afe6715f9487d1776158bebecf5bb235034719 Mon Sep 17 00:00:00 2001 From: Nikita Sobolev Date: Mon, 4 Mar 2024 12:13:28 +0300 Subject: [PATCH 33/54] Add `py312` target version to `black` config (#16983) I won't have any effect, but will reflect our target versions better. --- pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index fa6cf876b647..ef8acda3f95d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -17,7 +17,7 @@ build-backend = "setuptools.build_meta" [tool.black] line-length = 99 -target-version = ["py38", "py39", "py310", "py311"] +target-version = ["py38", "py39", "py310", "py311", "py312"] skip-magic-trailing-comma = true force-exclude = ''' ^/mypy/typeshed| From 2c66b4821369494e50aa1487e477790d014f8fcc Mon Sep 17 00:00:00 2001 From: jhance Date: Mon, 4 Mar 2024 07:57:27 -0800 Subject: [PATCH 34/54] Add changelog for 1.9.0 (#16978) I did my best to sort them out in a way I thought was reasonable, but feel free to suggest improvements. I also removed a few that were linter version updates etc. --------- Co-authored-by: Marc Mueller <30130371+cdce8p@users.noreply.github.com> Co-authored-by: Jelle Zijlstra --- CHANGELOG.md | 61 +++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 58 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bae881656865..86e4dc91aaec 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,9 +1,64 @@ # Mypy Release Notes -## Next release +## Mypy 1.9 + +We’ve just uploaded mypy 1.9 to the Python Package Index ([PyPI](https://pypi.org/project/mypy/)). Mypy is a static type checker for Python. This release includes new features, performance improvements and bug fixes. You can install it as follows: + + python3 -m pip install -U mypy + +You can read the full documentation for this release on [Read the Docs](http://mypy.readthedocs.io). + +#### Breaking Changes + +Because the version of typeshed we use in mypy 1.9 doesn't support 3.7, neither does mypy 1.9. (Jared Hance, PR [16883](https://github.com/python/mypy/pull/16883)) + +#### Basic PEP 696 Support + +This release contains new support for PEP 696 (https://peps.python.org/pep-0696). Please try it out! (Contributed by Marc Mueller). + +#### Type-checking improvements + * Fix duplicated TypeVarTuple test (Jelle Zijlstra, PR [16853](https://github.com/python/mypy/pull/16853)) + * Fix missing type store for overloads (Marc Mueller, PR [16803](https://github.com/python/mypy/pull/16803)) + * Fix `'WriteToConn' object has no attribute 'flush'` (Charlie Denton, PR [16801](https://github.com/python/mypy/pull/16801)) + * Update TypeAlias error messages to remove colon (Marc Mueller, PR [16831](https://github.com/python/mypy/pull/16831)) + * Support narrowing unions that include type[None] (Christoph Tyralla, PR [16315](https://github.com/python/mypy/pull/16315)) + * Support TypedDict functional syntax as class base type (anniel-stripe, PR [16703](https://github.com/python/mypy/pull/16703)) + * Accept multiline quoted annotations (Shantanu, PR [16765](https://github.com/python/mypy/pull/16765)) + * Allow unary + in Literal (Jelle Zijlstra, PR [16729](https://github.com/python/mypy/pull/16729)) + * Speed up finding function type variables (Jukka Lehtosalo, PR [16562](https://github.com/python/mypy/pull/16562)) + * Substitute type variables in return type of static methods (Kouroche Bouchiat, PR [16670](https://github.com/python/mypy/pull/16670)) + * Consider TypeVarTuple to be invariant (Marc Mueller, PR [16759](https://github.com/python/mypy/pull/16759)) + * Add `alias` support to `field()` in `attrs` plugin (Nikita Sobolev, PR [16610](https://github.com/python/mypy/pull/16610)) + * Improve attrs hashability detection (Tin Tvrtković, PR [16556](https://github.com/python/mypy/pull/16556)) + +#### Documentation Updates + * Document --enable-incomplete-feature possible values in "mypy --help" (Froger David, PR [16661](https://github.com/python/mypy/pull/16661)) + * Update new type system discussion links (thomaswhaley, PR [16841](https://github.com/python/mypy/pull/16841)) + * Docs: Add missing class instantiation to cheat sheet (Aleksi Tarvainen, PR [16817](https://github.com/python/mypy/pull/16817)) + * Fix typo in getting_started.rst (zipperer, PR [16700](https://github.com/python/mypy/pull/16700)) + * Document how evil `--no-strict-optional` is (Shantanu, PR [16731](https://github.com/python/mypy/pull/16731)) + * Improve mypy daemon documentation note about local partial types (Makonnen Makonnen, PR [16782](https://github.com/python/mypy/pull/16782)) + * Fix numbering error in docs (Stefanie Molin, PR [16838](https://github.com/python/mypy/pull/16838)) + * Various docs improvements (Shantanu, PR [16836](https://github.com/python/mypy/pull/16836)) + +#### Stubtest Improvements + * Stubtest will ignore private function/method parameters when they are missing from the stub. +Private parameters names start with a single underscore and have a default +(PR [16507](https://github.com/python/mypy/pull/16507)). + * Stubtest: ignore a new protocol dunder (Alex Waygood, PR [16895](https://github.com/python/mypy/pull/16895)) + * stubtest: Private parameters can be omitted (Sebastian Rittau, PR [16507](https://github.com/python/mypy/pull/16507)) + * stubtest: Add support for setting enum members to "..." (Jelle Zijlstra, PR [16807](https://github.com/python/mypy/pull/16807)) + * stubtest: adjust symtable logic (Shantanu, PR [16823](https://github.com/python/mypy/pull/16823)) + * stubtest: fix pos-only handling in overload resolution (Shantanu, PR [16750](https://github.com/python/mypy/pull/16750)) + +#### Stubgen Improvements + * stubgen: Fix crash on star unpack of TypeVarTuple (Ali Hamdan, PR [16869](https://github.com/python/mypy/pull/16869)) + * Fix failing stubgen tests (Ali Hamdan, PR [16779](https://github.com/python/mypy/pull/16779)) + * stubgen: use PEP 604 unions everywhere (Ali Hamdan, PR [16519](https://github.com/python/mypy/pull/16519)) + * Improve stubgen tests (Fabian Keller, PR [16760](https://github.com/python/mypy/pull/16760)) + * stubgen: Do not ignore property deleter (Ali Hamdan, PR [16781](https://github.com/python/mypy/pull/16781)) + * Support type stub generation for `staticmethod` (WeilerMarcel, PR [14934](https://github.com/python/mypy/pull/14934)) -Stubtest will ignore private function/method parameters when they are missing from the stub. Private parameters -names start with a single underscore and have a default (PR [16507](https://github.com/python/mypy/pull/16507)). ## Mypy 1.8 From d354e763084e3890972c0c912a8290e440959f26 Mon Sep 17 00:00:00 2001 From: Jukka Lehtosalo Date: Mon, 4 Mar 2024 20:18:27 +0000 Subject: [PATCH 35/54] Various 1.9 CHANGELOG updates (#16984) Mostly minor, but also announce that `--local-partial-types` will be enabled by default soon and explain type parameter defaults in more detail. --- CHANGELOG.md | 94 +++++++++++++++++++++++++++++++++++++--------------- 1 file changed, 68 insertions(+), 26 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 86e4dc91aaec..59085dea4d1f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,51 +12,93 @@ You can read the full documentation for this release on [Read the Docs](http://m Because the version of typeshed we use in mypy 1.9 doesn't support 3.7, neither does mypy 1.9. (Jared Hance, PR [16883](https://github.com/python/mypy/pull/16883)) -#### Basic PEP 696 Support +We are planning to enable +[local partial types](https://mypy.readthedocs.io/en/stable/command_line.html#cmdoption-mypy-local-partial-types) (enabled via the +`--local-partial-types` flag) later this year by default. This change +was announced years ago, but now it's finally happening. This is a +major backward-incompatible change, so we'll probably include it as +part of the upcoming mypy 2.0 release. This makes daemon and +non-daemon mypy runs have the same behavior by default. + +Local partial types can also be enabled in the mypy config file: +``` +local_partial_types = True +``` + +We are looking at providing a tool to make it easier to migrate +projects to use `--local-partial-types`, but it's not yet clear whether +this is practical. The migration usually involves adding some +explicit type annotations to module-level and class-level variables. + +#### Basic Support for Type Parameter Defaults (PEP 696) + +This release contains new experimental support for type parameter +defaults ([PEP 696](https://peps.python.org/pep-0696)). Please try it +out! This feature was contributed by Marc Mueller. + +Since this feature will be officially introduced in the next Python +feature release (3.13), you will need to import `TypeVar`, `ParamSpec` +or `TypeVarTuple` from `typing_extensions` to use defaults for now. + +This example adapted from the PEP defines a default for `BotT`: +```python +from typing import Generic +from typing_extensions import TypeVar + +class Bot: ... + +BotT = TypeVar("BotT", bound=Bot, default=Bot) -This release contains new support for PEP 696 (https://peps.python.org/pep-0696). Please try it out! (Contributed by Marc Mueller). +class Context(Generic[BotT]): + bot: BotT -#### Type-checking improvements - * Fix duplicated TypeVarTuple test (Jelle Zijlstra, PR [16853](https://github.com/python/mypy/pull/16853)) +class MyBot(Bot): ... + +# type is Bot (the default) +reveal_type(Context().bot) +# type is MyBot +reveal_type(Context[MyBot]().bot) +``` + +#### Type-checking Improvements * Fix missing type store for overloads (Marc Mueller, PR [16803](https://github.com/python/mypy/pull/16803)) * Fix `'WriteToConn' object has no attribute 'flush'` (Charlie Denton, PR [16801](https://github.com/python/mypy/pull/16801)) - * Update TypeAlias error messages to remove colon (Marc Mueller, PR [16831](https://github.com/python/mypy/pull/16831)) - * Support narrowing unions that include type[None] (Christoph Tyralla, PR [16315](https://github.com/python/mypy/pull/16315)) + * Improve TypeAlias error messages (Marc Mueller, PR [16831](https://github.com/python/mypy/pull/16831)) + * Support narrowing unions that include `type[None]` (Christoph Tyralla, PR [16315](https://github.com/python/mypy/pull/16315)) * Support TypedDict functional syntax as class base type (anniel-stripe, PR [16703](https://github.com/python/mypy/pull/16703)) * Accept multiline quoted annotations (Shantanu, PR [16765](https://github.com/python/mypy/pull/16765)) - * Allow unary + in Literal (Jelle Zijlstra, PR [16729](https://github.com/python/mypy/pull/16729)) - * Speed up finding function type variables (Jukka Lehtosalo, PR [16562](https://github.com/python/mypy/pull/16562)) + * Allow unary + in `Literal` (Jelle Zijlstra, PR [16729](https://github.com/python/mypy/pull/16729)) * Substitute type variables in return type of static methods (Kouroche Bouchiat, PR [16670](https://github.com/python/mypy/pull/16670)) * Consider TypeVarTuple to be invariant (Marc Mueller, PR [16759](https://github.com/python/mypy/pull/16759)) * Add `alias` support to `field()` in `attrs` plugin (Nikita Sobolev, PR [16610](https://github.com/python/mypy/pull/16610)) * Improve attrs hashability detection (Tin Tvrtković, PR [16556](https://github.com/python/mypy/pull/16556)) +#### Performance Improvements + + * Speed up finding function type variables (Jukka Lehtosalo, PR [16562](https://github.com/python/mypy/pull/16562)) + #### Documentation Updates - * Document --enable-incomplete-feature possible values in "mypy --help" (Froger David, PR [16661](https://github.com/python/mypy/pull/16661)) + + * Document supported values for `--enable-incomplete-feature` in "mypy --help" (Froger David, PR [16661](https://github.com/python/mypy/pull/16661)) * Update new type system discussion links (thomaswhaley, PR [16841](https://github.com/python/mypy/pull/16841)) - * Docs: Add missing class instantiation to cheat sheet (Aleksi Tarvainen, PR [16817](https://github.com/python/mypy/pull/16817)) - * Fix typo in getting_started.rst (zipperer, PR [16700](https://github.com/python/mypy/pull/16700)) + * Add missing class instantiation to cheat sheet (Aleksi Tarvainen, PR [16817](https://github.com/python/mypy/pull/16817)) * Document how evil `--no-strict-optional` is (Shantanu, PR [16731](https://github.com/python/mypy/pull/16731)) * Improve mypy daemon documentation note about local partial types (Makonnen Makonnen, PR [16782](https://github.com/python/mypy/pull/16782)) - * Fix numbering error in docs (Stefanie Molin, PR [16838](https://github.com/python/mypy/pull/16838)) - * Various docs improvements (Shantanu, PR [16836](https://github.com/python/mypy/pull/16836)) + * Fix numbering error (Stefanie Molin, PR [16838](https://github.com/python/mypy/pull/16838)) + * Various documentation improvements (Shantanu, PR [16836](https://github.com/python/mypy/pull/16836)) #### Stubtest Improvements - * Stubtest will ignore private function/method parameters when they are missing from the stub. -Private parameters names start with a single underscore and have a default -(PR [16507](https://github.com/python/mypy/pull/16507)). - * Stubtest: ignore a new protocol dunder (Alex Waygood, PR [16895](https://github.com/python/mypy/pull/16895)) - * stubtest: Private parameters can be omitted (Sebastian Rittau, PR [16507](https://github.com/python/mypy/pull/16507)) - * stubtest: Add support for setting enum members to "..." (Jelle Zijlstra, PR [16807](https://github.com/python/mypy/pull/16807)) - * stubtest: adjust symtable logic (Shantanu, PR [16823](https://github.com/python/mypy/pull/16823)) - * stubtest: fix pos-only handling in overload resolution (Shantanu, PR [16750](https://github.com/python/mypy/pull/16750)) + * Ignore private function/method parameters when they are missing from the stub (private parameter names start with a single underscore and have a default) (PR [16507](https://github.com/python/mypy/pull/16507)) + * Ignore a new protocol dunder (Alex Waygood, PR [16895](https://github.com/python/mypy/pull/16895)) + * Private parameters can be omitted (Sebastian Rittau, PR [16507](https://github.com/python/mypy/pull/16507)) + * Add support for setting enum members to "..." (Jelle Zijlstra, PR [16807](https://github.com/python/mypy/pull/16807)) + * Adjust symbol table logic (Shantanu, PR [16823](https://github.com/python/mypy/pull/16823)) + * Fix posisitional-only handling in overload resolution (Shantanu, PR [16750](https://github.com/python/mypy/pull/16750)) #### Stubgen Improvements - * stubgen: Fix crash on star unpack of TypeVarTuple (Ali Hamdan, PR [16869](https://github.com/python/mypy/pull/16869)) - * Fix failing stubgen tests (Ali Hamdan, PR [16779](https://github.com/python/mypy/pull/16779)) - * stubgen: use PEP 604 unions everywhere (Ali Hamdan, PR [16519](https://github.com/python/mypy/pull/16519)) - * Improve stubgen tests (Fabian Keller, PR [16760](https://github.com/python/mypy/pull/16760)) - * stubgen: Do not ignore property deleter (Ali Hamdan, PR [16781](https://github.com/python/mypy/pull/16781)) + * Fix crash on star unpack of TypeVarTuple (Ali Hamdan, PR [16869](https://github.com/python/mypy/pull/16869)) + * Use PEP 604 unions everywhere (Ali Hamdan, PR [16519](https://github.com/python/mypy/pull/16519)) + * Do not ignore property deleter (Ali Hamdan, PR [16781](https://github.com/python/mypy/pull/16781)) * Support type stub generation for `staticmethod` (WeilerMarcel, PR [14934](https://github.com/python/mypy/pull/14934)) From 2f0f8f26d7aa3dab3c44a621bbed58c7816db2a4 Mon Sep 17 00:00:00 2001 From: jhance Date: Tue, 5 Mar 2024 13:58:22 -0800 Subject: [PATCH 36/54] Update changelog for 1.9 with acknowledgements. (#16989) Co-authored-by: Jukka Lehtosalo Co-authored-by: Alex Waygood --- CHANGELOG.md | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 59085dea4d1f..8bd537d46e9c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -101,6 +101,41 @@ reveal_type(Context[MyBot]().bot) * Do not ignore property deleter (Ali Hamdan, PR [16781](https://github.com/python/mypy/pull/16781)) * Support type stub generation for `staticmethod` (WeilerMarcel, PR [14934](https://github.com/python/mypy/pull/14934)) +#### Acknowledgements + +​Thanks to all mypy contributors who contributed to this release: + +- Aleksi Tarvainen +- Alex Waygood +- Ali Hamdan +- anniel-stripe +- Charlie Denton +- Christoph Tyralla +- Dheeraj +- Fabian Keller +- Fabian Lewis +- Froger David +- Ihor +- Jared Hance +- Jelle Zijlstra +- Jukka Lehtosalo +- Kouroche Bouchiat +- Lukas Geiger +- Maarten Huijsmans +- Makonnen Makonnen +- Marc Mueller +- Nikita Sobolev +- Sebastian Rittau +- Shantanu +- Stefanie Molin +- Stephen Morton +- thomaswhaley +- Tin Tvrtković +- WeilerMarcel +- Wesley Collin Wright +- zipperer + +I’d also like to thank my employer, Dropbox, for supporting mypy development. ## Mypy 1.8 From 2fbfb6060a4549a1837d5eed4ad7ef1e8da256b9 Mon Sep 17 00:00:00 2001 From: Marc Mueller <30130371+cdce8p@users.noreply.github.com> Date: Thu, 7 Mar 2024 02:25:06 +0100 Subject: [PATCH 37/54] Fix inference with UninhabitedType (#16994) At the moment, inference fails if an empty dict is used (without annotation) as one of the types. It's because the constraint solver can't resolve `dict[str, int]` and `dict[Never, Never]`. However in this case it's more reasonable to interpret the empty dict as `dict[Any, Any]` and just using the first type instead. That matches the behavior of pyright. ```py T = TypeVar("T") class A(Generic[T]): ... def func1(a: A[T], b: T) -> T: ... def a1(a: A[Dict[str, int]]) -> None: reveal_type(func1(a, {})) ``` ``` # before main: error: Cannot infer type argument 1 of "func1" (diff) main: note: Revealed type is "Any" (diff) # after main: note: Revealed type is "builtins.dict[builtins.str, builtins.int]" ``` --- mypy/join.py | 13 +++++++---- test-data/unit/check-inference.test | 34 +++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 4 deletions(-) diff --git a/mypy/join.py b/mypy/join.py index bf88f43d88fe..3603e9fefb7a 100644 --- a/mypy/join.py +++ b/mypy/join.py @@ -108,12 +108,17 @@ def join_instances(self, t: Instance, s: Instance) -> ProperType: # TODO: contravariant case should use meet but pass seen instances as # an argument to keep track of recursive checks. elif type_var.variance in (INVARIANT, CONTRAVARIANT): - if not is_equivalent(ta, sa): + if isinstance(ta_proper, UninhabitedType) and not ta_proper.is_noreturn: + new_type = sa + elif isinstance(sa_proper, UninhabitedType) and not sa_proper.is_noreturn: + new_type = ta + elif not is_equivalent(ta, sa): self.seen_instances.pop() return object_from_instance(t) - # If the types are different but equivalent, then an Any is involved - # so using a join in the contravariant case is also OK. - new_type = join_types(ta, sa, self) + else: + # If the types are different but equivalent, then an Any is involved + # so using a join in the contravariant case is also OK. + new_type = join_types(ta, sa, self) elif isinstance(type_var, TypeVarTupleType): new_type = get_proper_type(join_types(ta, sa, self)) # Put the joined arguments back into instance in the normal form: diff --git a/test-data/unit/check-inference.test b/test-data/unit/check-inference.test index 953855e502d6..1b1ce607bf28 100644 --- a/test-data/unit/check-inference.test +++ b/test-data/unit/check-inference.test @@ -3813,3 +3813,37 @@ def m1() -> float: ... def m2() -> float: ... reveal_type(Combine(m1, m2)) # N: Revealed type is "builtins.float" [builtins fixtures/list.pyi] + +[case testInferenceWithUninhabitedType] +from typing import Dict, Generic, List, Never, TypeVar + +T = TypeVar("T") + +class A(Generic[T]): ... +class B(Dict[T, T]): ... + +def func1(a: A[T], b: T) -> T: ... +def func2(a: T, b: A[T]) -> T: ... + +def a1(a: A[Dict[str, int]]) -> None: + reveal_type(func1(a, {})) # N: Revealed type is "builtins.dict[builtins.str, builtins.int]" + reveal_type(func2({}, a)) # N: Revealed type is "builtins.dict[builtins.str, builtins.int]" + +def a2(check: bool, a: B[str]) -> None: + reveal_type(a if check else {}) # N: Revealed type is "builtins.dict[builtins.str, builtins.str]" + +def a3() -> None: + a = {} # E: Need type annotation for "a" (hint: "a: Dict[, ] = ...") + b = {1: {}} # E: Need type annotation for "b" + c = {1: {}, 2: {"key": {}}} # E: Need type annotation for "c" + reveal_type(a) # N: Revealed type is "builtins.dict[Any, Any]" + reveal_type(b) # N: Revealed type is "builtins.dict[builtins.int, builtins.dict[Any, Any]]" + reveal_type(c) # N: Revealed type is "builtins.dict[builtins.int, builtins.dict[builtins.str, builtins.dict[Any, Any]]]" + +def a4(x: List[str], y: List[Never]) -> None: + z1 = [x, y] + z2 = [y, x] + reveal_type(z1) # N: Revealed type is "builtins.list[builtins.object]" + reveal_type(z2) # N: Revealed type is "builtins.list[builtins.object]" + z1[1].append("asdf") # E: "object" has no attribute "append" +[builtins fixtures/dict.pyi] From 0b8fed526de75284349afbd4b448172b61148931 Mon Sep 17 00:00:00 2001 From: Oskari Lehto Date: Thu, 7 Mar 2024 05:40:10 +0200 Subject: [PATCH 38/54] Fix single item enum match type exhaustion (#16966) Fixes #14109 --------- Co-authored-by: Shantanu Jain --- mypy/checkpattern.py | 2 +- test-data/unit/check-python310.test | 24 ++++++++++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/mypy/checkpattern.py b/mypy/checkpattern.py index 7b6a55324741..a23be464b825 100644 --- a/mypy/checkpattern.py +++ b/mypy/checkpattern.py @@ -202,7 +202,7 @@ def visit_value_pattern(self, o: ValuePattern) -> PatternType: typ = self.chk.expr_checker.accept(o.expr) typ = coerce_to_literal(typ) narrowed_type, rest_type = self.chk.conditional_types_with_intersection( - current_type, [get_type_range(typ)], o, default=current_type + current_type, [get_type_range(typ)], o, default=get_proper_type(typ) ) if not isinstance(get_proper_type(narrowed_type), (LiteralType, UninhabitedType)): return PatternType(narrowed_type, UnionType.make_union([narrowed_type, rest_type]), {}) diff --git a/test-data/unit/check-python310.test b/test-data/unit/check-python310.test index b0e27fe1e3a0..3a040d94d7ba 100644 --- a/test-data/unit/check-python310.test +++ b/test-data/unit/check-python310.test @@ -1369,6 +1369,27 @@ match m3: reveal_type(m3) # N: Revealed type is "Tuple[Union[builtins.int, builtins.str]]" [builtins fixtures/tuple.pyi] +[case testMatchEnumSingleChoice] +from enum import Enum +from typing import NoReturn + +def assert_never(x: NoReturn) -> None: ... + +class Medal(Enum): + gold = 1 + +def f(m: Medal) -> None: + always_assigned: int | None = None + match m: + case Medal.gold: + always_assigned = 1 + reveal_type(m) # N: Revealed type is "Literal[__main__.Medal.gold]" + case _: + assert_never(m) + + reveal_type(always_assigned) # N: Revealed type is "builtins.int" +[builtins fixtures/bool.pyi] + [case testMatchLiteralPatternEnumNegativeNarrowing] from enum import Enum class Medal(Enum): @@ -1388,10 +1409,13 @@ def f(m: Medal) -> int: def g(m: Medal) -> int: match m: case Medal.gold: + reveal_type(m) # N: Revealed type is "Literal[__main__.Medal.gold]" return 0 case Medal.silver: + reveal_type(m) # N: Revealed type is "Literal[__main__.Medal.silver]" return 1 case Medal.bronze: + reveal_type(m) # N: Revealed type is "Literal[__main__.Medal.bronze]" return 2 [case testMatchLiteralPatternEnumCustomEquals-skip] From e0ad95296037446fccb398b8dadc54ae0751df46 Mon Sep 17 00:00:00 2001 From: Shantanu <12621235+hauntsaninja@users.noreply.github.com> Date: Fri, 8 Mar 2024 07:05:05 -0800 Subject: [PATCH 39/54] Disallow all super calls to methods with trivial bodies (#16756) Relates to: https://discuss.python.org/t/calling-abstract-methods/42576 I think this makes mypy's behaviour more predictable --- mypy/checkmember.py | 8 +------- test-data/unit/check-abstract.test | 12 ++++++------ 2 files changed, 7 insertions(+), 13 deletions(-) diff --git a/mypy/checkmember.py b/mypy/checkmember.py index c24edacf0ee1..afa8f37ff7d5 100644 --- a/mypy/checkmember.py +++ b/mypy/checkmember.py @@ -359,13 +359,7 @@ def validate_super_call(node: FuncBase, mx: MemberContext) -> None: impl = node.impl if isinstance(node.impl, FuncDef) else node.impl.func unsafe_super = impl.is_trivial_body if unsafe_super: - ret_type = ( - impl.type.ret_type - if isinstance(impl.type, CallableType) - else AnyType(TypeOfAny.unannotated) - ) - if not subtypes.is_subtype(NoneType(), ret_type): - mx.msg.unsafe_super(node.name, node.info.name, mx.context) + mx.msg.unsafe_super(node.name, node.info.name, mx.context) def analyze_type_callable_member_access(name: str, typ: FunctionLike, mx: MemberContext) -> Type: diff --git a/test-data/unit/check-abstract.test b/test-data/unit/check-abstract.test index 7f91eb8e7145..3b0b9c520b75 100644 --- a/test-data/unit/check-abstract.test +++ b/test-data/unit/check-abstract.test @@ -896,9 +896,9 @@ class A(metaclass=ABCMeta): class B(A): @property def x(self) -> int: - return super().x.y # E: "int" has no attribute "y" + return super().x.y # E: Call to abstract method "x" of "A" with trivial body via super() is unsafe \ + # E: "int" has no attribute "y" [builtins fixtures/property.pyi] -[out] [case testSuperWithReadWriteAbstractProperty] from abc import abstractproperty, ABCMeta @@ -1659,10 +1659,10 @@ class Abstract: class SubProto(Proto): def meth(self) -> int: - return super().meth() + return super().meth() # E: Call to abstract method "meth" of "Proto" with trivial body via super() is unsafe class SubAbstract(Abstract): def meth(self) -> int: - return super().meth() + return super().meth() # E: Call to abstract method "meth" of "Abstract" with trivial body via super() is unsafe [case testEmptyBodyNoSuperWarningOptionalReturn] from typing import Protocol, Optional @@ -1676,10 +1676,10 @@ class Abstract: class SubProto(Proto): def meth(self) -> Optional[int]: - return super().meth() + return super().meth() # E: Call to abstract method "meth" of "Proto" with trivial body via super() is unsafe class SubAbstract(Abstract): def meth(self) -> Optional[int]: - return super().meth() + return super().meth() # E: Call to abstract method "meth" of "Abstract" with trivial body via super() is unsafe [case testEmptyBodyTypeCheckingOnly] from typing import TYPE_CHECKING From c94d8e3cd02e8be5e4594d84ec77c84b3faf7948 Mon Sep 17 00:00:00 2001 From: Jukka Lehtosalo Date: Sat, 9 Mar 2024 09:16:41 +0000 Subject: [PATCH 40/54] [mypyc] Provide an easier way to define IR-to-IR transforms (#16998) This makes it easy to define simple IR-to-IR transforms by subclassing `IRTansform` and overriding some visit methods. Add an implementation of a simple copy propagation optimization as an example. This will be used by the implementation of mypyc/mypyc#854, and this can also be used for various optimizations. The IR transform preserves the identities of ops that are not modified. This means that the old IR is no longer valid after the transform, but the transform can be fast since we don't need to allocate many objects if only a small subset of ops will be modified by a transform. --- mypyc/codegen/emitmodule.py | 13 +- mypyc/irbuild/builder.py | 6 +- mypyc/irbuild/ll_builder.py | 8 +- mypyc/test-data/opt-copy-propagation.test | 400 ++++++++++++++++++++++ mypyc/test/test_copy_propagation.py | 47 +++ mypyc/transform/copy_propagation.py | 94 +++++ mypyc/transform/ir_transform.py | 353 +++++++++++++++++++ 7 files changed, 904 insertions(+), 17 deletions(-) create mode 100644 mypyc/test-data/opt-copy-propagation.test create mode 100644 mypyc/test/test_copy_propagation.py create mode 100644 mypyc/transform/copy_propagation.py create mode 100644 mypyc/transform/ir_transform.py diff --git a/mypyc/codegen/emitmodule.py b/mypyc/codegen/emitmodule.py index 6c0dfd43b9af..0035bd53188b 100644 --- a/mypyc/codegen/emitmodule.py +++ b/mypyc/codegen/emitmodule.py @@ -56,6 +56,7 @@ from mypyc.irbuild.prepare import load_type_map from mypyc.namegen import NameGenerator, exported_name from mypyc.options import CompilerOptions +from mypyc.transform.copy_propagation import do_copy_propagation from mypyc.transform.exceptions import insert_exception_handling from mypyc.transform.refcount import insert_ref_count_opcodes from mypyc.transform.uninit import insert_uninit_checks @@ -225,18 +226,16 @@ def compile_scc_to_ir( if errors.num_errors > 0: return modules - # Insert uninit checks. for module in modules.values(): for fn in module.functions: + # Insert uninit checks. insert_uninit_checks(fn) - # Insert exception handling. - for module in modules.values(): - for fn in module.functions: + # Insert exception handling. insert_exception_handling(fn) - # Insert refcount handling. - for module in modules.values(): - for fn in module.functions: + # Insert refcount handling. insert_ref_count_opcodes(fn) + # Perform copy propagation optimization. + do_copy_propagation(fn, compiler_options) return modules diff --git a/mypyc/irbuild/builder.py b/mypyc/irbuild/builder.py index f201a4737f89..52891d68e3b2 100644 --- a/mypyc/irbuild/builder.py +++ b/mypyc/irbuild/builder.py @@ -160,7 +160,7 @@ def __init__( options: CompilerOptions, singledispatch_impls: dict[FuncDef, list[RegisterImplInfo]], ) -> None: - self.builder = LowLevelIRBuilder(current_module, errors, mapper, options) + self.builder = LowLevelIRBuilder(errors, options) self.builders = [self.builder] self.symtables: list[dict[SymbolNode, SymbolTarget]] = [{}] self.runtime_args: list[list[RuntimeArg]] = [[]] @@ -1111,9 +1111,7 @@ def flatten_classes(self, arg: RefExpr | TupleExpr) -> list[ClassIR] | None: def enter(self, fn_info: FuncInfo | str = "") -> None: if isinstance(fn_info, str): fn_info = FuncInfo(name=fn_info) - self.builder = LowLevelIRBuilder( - self.current_module, self.errors, self.mapper, self.options - ) + self.builder = LowLevelIRBuilder(self.errors, self.options) self.builder.set_module(self.module_name, self.module_path) self.builders.append(self.builder) self.symtables.append({}) diff --git a/mypyc/irbuild/ll_builder.py b/mypyc/irbuild/ll_builder.py index d1ea91476a66..45c06e11befd 100644 --- a/mypyc/irbuild/ll_builder.py +++ b/mypyc/irbuild/ll_builder.py @@ -126,7 +126,6 @@ short_int_rprimitive, str_rprimitive, ) -from mypyc.irbuild.mapper import Mapper from mypyc.irbuild.util import concrete_arg_kind from mypyc.options import CompilerOptions from mypyc.primitives.bytes_ops import bytes_compare @@ -220,12 +219,8 @@ class LowLevelIRBuilder: - def __init__( - self, current_module: str, errors: Errors, mapper: Mapper, options: CompilerOptions - ) -> None: - self.current_module = current_module + def __init__(self, errors: Errors | None, options: CompilerOptions) -> None: self.errors = errors - self.mapper = mapper self.options = options self.args: list[Register] = [] self.blocks: list[BasicBlock] = [] @@ -2394,6 +2389,7 @@ def _create_dict(self, keys: list[Value], values: list[Value], line: int) -> Val return self.call_c(dict_new_op, [], line) def error(self, msg: str, line: int) -> None: + assert self.errors is not None, "cannot generate errors in this compiler phase" self.errors.error(msg, self.module_path, line) diff --git a/mypyc/test-data/opt-copy-propagation.test b/mypyc/test-data/opt-copy-propagation.test new file mode 100644 index 000000000000..49b80f4385fc --- /dev/null +++ b/mypyc/test-data/opt-copy-propagation.test @@ -0,0 +1,400 @@ +-- Test cases for copy propagation optimization. This also tests IR transforms in general, +-- as copy propagation was the first IR transform that was implemented. + +[case testCopyPropagationSimple] +def g() -> int: + return 1 + +def f() -> int: + y = g() + return y +[out] +def g(): +L0: + return 2 +def f(): + r0 :: int +L0: + r0 = g() + return r0 + +[case testCopyPropagationChain] +def f(x: int) -> int: + y = x + z = y + return z +[out] +def f(x): + x :: int +L0: + return x + +[case testCopyPropagationChainPartial] +def f(x: int) -> int: + y = x + z = y + x = 2 + return z +[out] +def f(x): + x, y :: int +L0: + y = x + x = 4 + return y + +[case testCopyPropagationChainBad] +def f(x: int) -> int: + y = x + z = y + y = 2 + return z +[out] +def f(x): + x, y, z :: int +L0: + y = x + z = y + y = 4 + return z + +[case testCopyPropagationMutatedSource1] +def f(x: int) -> int: + y = x + x = 1 + return y +[out] +def f(x): + x, y :: int +L0: + y = x + x = 2 + return y + +[case testCopyPropagationMutatedSource2] +def f() -> int: + z = 1 + y = z + z = 2 + return y +[out] +def f(): + z, y :: int +L0: + z = 2 + y = z + z = 4 + return y + +[case testCopyPropagationTooComplex] +def f(b: bool, x: int) -> int: + if b: + y = x + return y + else: + y = 1 + return y +[out] +def f(b, x): + b :: bool + x, y :: int +L0: + if b goto L1 else goto L2 :: bool +L1: + y = x + return y +L2: + y = 2 + return y + +[case testCopyPropagationArg] +def f(x: int) -> int: + x = 2 + return x +[out] +def f(x): + x :: int +L0: + x = 4 + return x + +[case testCopyPropagationPartiallyDefined1] +def f(b: bool) -> int: + if b: + x = 1 + y = x + return y +[out] +def f(b): + b :: bool + r0, x :: int + r1 :: bool + y :: int +L0: + r0 = :: int + x = r0 + if b goto L1 else goto L2 :: bool +L1: + x = 2 +L2: + if is_error(x) goto L3 else goto L4 +L3: + r1 = raise UnboundLocalError('local variable "x" referenced before assignment') + unreachable +L4: + y = x + return y + +-- The remaining test cases test basic IRTransform functionality and are not +-- all needed for testing copy propagation as such. + +[case testIRTransformBranch] +from mypy_extensions import i64 + +def f(x: bool) -> int: + y = x + if y: + return 1 + else: + return 2 +[out] +def f(x): + x :: bool +L0: + if x goto L1 else goto L2 :: bool +L1: + return 2 +L2: + return 4 + +[case testIRTransformAssignment] +def f(b: bool, x: int) -> int: + y = x + if b: + return y + else: + return 1 +[out] +def f(b, x): + b :: bool + x :: int +L0: + if b goto L1 else goto L2 :: bool +L1: + return x +L2: + return 2 + +[case testIRTransformRegisterOps1] +from __future__ import annotations +from typing import cast + +class C: + a: int + + def m(self, x: int) -> None: pass + +def get_attr(x: C) -> int: + y = x + return y.a + +def set_attr(x: C) -> None: + y = x + y.a = 1 + +def tuple_get(x: tuple[int, int]) -> int: + y = x + return y[0] + +def tuple_set(x: int, xx: int) -> tuple[int, int]: + y = x + z = xx + return y, z + +def call(x: int) -> int: + y = x + return call(y) + +def method_call(c: C, x: int) -> None: + y = x + c.m(y) + +def cast_op(x: object) -> str: + y = x + return cast(str, y) + +def box(x: int) -> object: + y = x + return y + +def unbox(x: object) -> int: + y = x + return cast(int, y) + +def call_c(x: list[str]) -> None: + y = x + y.append("x") + +def keep_alive(x: C) -> int: + y = x + return y.a + 1 +[out] +def C.m(self, x): + self :: __main__.C + x :: int +L0: + return 1 +def get_attr(x): + x :: __main__.C + r0 :: int +L0: + r0 = x.a + return r0 +def set_attr(x): + x :: __main__.C + r0 :: bool +L0: + x.a = 2; r0 = is_error + return 1 +def tuple_get(x): + x :: tuple[int, int] + r0 :: int +L0: + r0 = x[0] + return r0 +def tuple_set(x, xx): + x, xx :: int + r0 :: tuple[int, int] +L0: + r0 = (x, xx) + return r0 +def call(x): + x, r0 :: int +L0: + r0 = call(x) + return r0 +def method_call(c, x): + c :: __main__.C + x :: int + r0 :: None +L0: + r0 = c.m(x) + return 1 +def cast_op(x): + x :: object + r0 :: str +L0: + r0 = cast(str, x) + return r0 +def box(x): + x :: int + r0 :: object +L0: + r0 = box(int, x) + return r0 +def unbox(x): + x :: object + r0 :: int +L0: + r0 = unbox(int, x) + return r0 +def call_c(x): + x :: list + r0 :: str + r1 :: i32 + r2 :: bit +L0: + r0 = 'x' + r1 = PyList_Append(x, r0) + r2 = r1 >= 0 :: signed + return 1 +def keep_alive(x): + x :: __main__.C + r0, r1 :: int +L0: + r0 = borrow x.a + r1 = CPyTagged_Add(r0, 2) + keep_alive x + return r1 + +[case testIRTransformRegisterOps2] +from mypy_extensions import i32, i64 + +def truncate(x: i64) -> i32: + y = x + return i32(y) + +def extend(x: i32) -> i64: + y = x + return i64(y) + +def int_op(x: i64, xx: i64) -> i64: + y = x + z = xx + return y + z + +def comparison_op(x: i64, xx: i64) -> bool: + y = x + z = xx + return y == z + +def float_op(x: float, xx: float) -> float: + y = x + z = xx + return y + z + +def float_neg(x: float) -> float: + y = x + return -y + +def float_comparison_op(x: float, xx: float) -> bool: + y = x + z = xx + return y == z +[out] +def truncate(x): + x :: i64 + r0 :: i32 +L0: + r0 = truncate x: i64 to i32 + return r0 +def extend(x): + x :: i32 + r0 :: i64 +L0: + r0 = extend signed x: i32 to i64 + return r0 +def int_op(x, xx): + x, xx, r0 :: i64 +L0: + r0 = x + xx + return r0 +def comparison_op(x, xx): + x, xx :: i64 + r0 :: bit +L0: + r0 = x == xx + return r0 +def float_op(x, xx): + x, xx, r0 :: float +L0: + r0 = x + xx + return r0 +def float_neg(x): + x, r0 :: float +L0: + r0 = -x + return r0 +def float_comparison_op(x, xx): + x, xx :: float + r0 :: bit +L0: + r0 = x == xx + return r0 + +-- Note that transforms of these ops aren't tested here: +-- * LoadMem +-- * SetMem +-- * GetElementPtr +-- * LoadAddress +-- * Unborrow diff --git a/mypyc/test/test_copy_propagation.py b/mypyc/test/test_copy_propagation.py new file mode 100644 index 000000000000..c729e3d186c3 --- /dev/null +++ b/mypyc/test/test_copy_propagation.py @@ -0,0 +1,47 @@ +"""Runner for copy propagation optimization tests.""" + +from __future__ import annotations + +import os.path + +from mypy.errors import CompileError +from mypy.test.config import test_temp_dir +from mypy.test.data import DataDrivenTestCase +from mypyc.common import TOP_LEVEL_NAME +from mypyc.ir.pprint import format_func +from mypyc.options import CompilerOptions +from mypyc.test.testutil import ( + ICODE_GEN_BUILTINS, + MypycDataSuite, + assert_test_output, + build_ir_for_single_file, + remove_comment_lines, + use_custom_builtins, +) +from mypyc.transform.copy_propagation import do_copy_propagation +from mypyc.transform.uninit import insert_uninit_checks + +files = ["opt-copy-propagation.test"] + + +class TestCopyPropagation(MypycDataSuite): + files = files + base_path = test_temp_dir + + def run_case(self, testcase: DataDrivenTestCase) -> None: + with use_custom_builtins(os.path.join(self.data_prefix, ICODE_GEN_BUILTINS), testcase): + expected_output = remove_comment_lines(testcase.output) + try: + ir = build_ir_for_single_file(testcase.input) + except CompileError as e: + actual = e.messages + else: + actual = [] + for fn in ir: + if fn.name == TOP_LEVEL_NAME and not testcase.name.endswith("_toplevel"): + continue + insert_uninit_checks(fn) + do_copy_propagation(fn, CompilerOptions()) + actual.extend(format_func(fn)) + + assert_test_output(testcase, actual, "Invalid source code output", expected_output) diff --git a/mypyc/transform/copy_propagation.py b/mypyc/transform/copy_propagation.py new file mode 100644 index 000000000000..49de616f85a3 --- /dev/null +++ b/mypyc/transform/copy_propagation.py @@ -0,0 +1,94 @@ +"""Simple copy propagation optimization. + +Example input: + + x = f() + y = x + +The register x is redundant and we can directly assign its value to y: + + y = f() + +This can optimize away registers that are assigned to once. +""" + +from __future__ import annotations + +from mypyc.ir.func_ir import FuncIR +from mypyc.ir.ops import Assign, AssignMulti, LoadAddress, LoadErrorValue, Register, Value +from mypyc.irbuild.ll_builder import LowLevelIRBuilder +from mypyc.options import CompilerOptions +from mypyc.sametype import is_same_type +from mypyc.transform.ir_transform import IRTransform + + +def do_copy_propagation(fn: FuncIR, options: CompilerOptions) -> None: + """Perform copy propagation optimization for fn.""" + + # Anything with an assignment count >1 will not be optimized + # here, as it would be require data flow analysis and we want to + # keep this simple and fast, at least until we've made data flow + # analysis much faster. + counts: dict[Value, int] = {} + replacements: dict[Value, Value] = {} + for arg in fn.arg_regs: + # Arguments are always assigned to initially + counts[arg] = 1 + + for block in fn.blocks: + for op in block.ops: + if isinstance(op, Assign): + c = counts.get(op.dest, 0) + counts[op.dest] = c + 1 + # Does this look like a supported assignment? + # TODO: Something needs LoadErrorValue assignments to be preserved? + if ( + c == 0 + and is_same_type(op.dest.type, op.src.type) + and not isinstance(op.src, LoadErrorValue) + ): + replacements[op.dest] = op.src + elif c == 1: + # Too many assignments -- don't replace this one + replacements.pop(op.dest, 0) + elif isinstance(op, AssignMulti): + # Copy propagation not supported for AssignMulti destinations + counts[op.dest] = 2 + replacements.pop(op.dest, 0) + elif isinstance(op, LoadAddress): + # We don't support taking the address of an arbitrary Value, + # so we'll need to preserve the operands of LoadAddress. + if isinstance(op.src, Register): + counts[op.src] = 2 + replacements.pop(op.src, 0) + + # Follow chains of propagation with more than one assignment. + for src, dst in list(replacements.items()): + if counts.get(dst, 0) > 1: + # Not supported + del replacements[src] + else: + while dst in replacements: + dst = replacements[dst] + if counts.get(dst, 0) > 1: + # Not supported + del replacements[src] + if src in replacements: + replacements[src] = dst + + builder = LowLevelIRBuilder(None, options) + transform = CopyPropagationTransform(builder, replacements) + transform.transform_blocks(fn.blocks) + fn.blocks = builder.blocks + + +class CopyPropagationTransform(IRTransform): + def __init__(self, builder: LowLevelIRBuilder, map: dict[Value, Value]) -> None: + super().__init__(builder) + self.op_map.update(map) + self.removed = set(map) + + def visit_assign(self, op: Assign) -> Value | None: + if op.dest in self.removed: + return None + return self.add(op) diff --git a/mypyc/transform/ir_transform.py b/mypyc/transform/ir_transform.py new file mode 100644 index 000000000000..1bcfc8fb5feb --- /dev/null +++ b/mypyc/transform/ir_transform.py @@ -0,0 +1,353 @@ +"""Helpers for implementing generic IR to IR transforms.""" + +from __future__ import annotations + +from typing import Final, Optional + +from mypyc.ir.ops import ( + Assign, + AssignMulti, + BasicBlock, + Box, + Branch, + Call, + CallC, + Cast, + ComparisonOp, + DecRef, + Extend, + FloatComparisonOp, + FloatNeg, + FloatOp, + GetAttr, + GetElementPtr, + Goto, + IncRef, + InitStatic, + IntOp, + KeepAlive, + LoadAddress, + LoadErrorValue, + LoadGlobal, + LoadLiteral, + LoadMem, + LoadStatic, + MethodCall, + Op, + OpVisitor, + RaiseStandardError, + Return, + SetAttr, + SetMem, + Truncate, + TupleGet, + TupleSet, + Unborrow, + Unbox, + Unreachable, + Value, +) +from mypyc.irbuild.ll_builder import LowLevelIRBuilder + + +class IRTransform(OpVisitor[Optional[Value]]): + """Identity transform. + + Subclass and override to perform changes to IR. + + Subclass IRTransform and override any OpVisitor visit_* methods + that perform any IR changes. The default implementations implement + an identity transform. + + A visit method can return None to remove ops. In this case the + transform must ensure that no op uses the original removed op + as a source after the transform. + + You can retain old BasicBlock and op references in ops. The transform + will automatically patch these for you as needed. + """ + + def __init__(self, builder: LowLevelIRBuilder) -> None: + self.builder = builder + # Subclasses add additional op mappings here. A None value indicates + # that the op/register is deleted. + self.op_map: dict[Value, Value | None] = {} + + def transform_blocks(self, blocks: list[BasicBlock]) -> None: + """Transform basic blocks that represent a single function. + + The result of the transform will be collected at self.builder.blocks. + """ + block_map: dict[BasicBlock, BasicBlock] = {} + op_map = self.op_map + for block in blocks: + new_block = BasicBlock() + block_map[block] = new_block + self.builder.activate_block(new_block) + new_block.error_handler = block.error_handler + for op in block.ops: + new_op = op.accept(self) + if new_op is not op: + op_map[op] = new_op + + # Update all op/block references to point to the transformed ones. + patcher = PatchVisitor(op_map, block_map) + for block in self.builder.blocks: + for op in block.ops: + op.accept(patcher) + if block.error_handler is not None: + block.error_handler = block_map.get(block.error_handler, block.error_handler) + + def add(self, op: Op) -> Value: + return self.builder.add(op) + + def visit_goto(self, op: Goto) -> Value: + return self.add(op) + + def visit_branch(self, op: Branch) -> Value: + return self.add(op) + + def visit_return(self, op: Return) -> Value: + return self.add(op) + + def visit_unreachable(self, op: Unreachable) -> Value: + return self.add(op) + + def visit_assign(self, op: Assign) -> Value | None: + return self.add(op) + + def visit_assign_multi(self, op: AssignMulti) -> Value | None: + return self.add(op) + + def visit_load_error_value(self, op: LoadErrorValue) -> Value | None: + return self.add(op) + + def visit_load_literal(self, op: LoadLiteral) -> Value | None: + return self.add(op) + + def visit_get_attr(self, op: GetAttr) -> Value | None: + return self.add(op) + + def visit_set_attr(self, op: SetAttr) -> Value | None: + return self.add(op) + + def visit_load_static(self, op: LoadStatic) -> Value | None: + return self.add(op) + + def visit_init_static(self, op: InitStatic) -> Value | None: + return self.add(op) + + def visit_tuple_get(self, op: TupleGet) -> Value | None: + return self.add(op) + + def visit_tuple_set(self, op: TupleSet) -> Value | None: + return self.add(op) + + def visit_inc_ref(self, op: IncRef) -> Value | None: + return self.add(op) + + def visit_dec_ref(self, op: DecRef) -> Value | None: + return self.add(op) + + def visit_call(self, op: Call) -> Value | None: + return self.add(op) + + def visit_method_call(self, op: MethodCall) -> Value | None: + return self.add(op) + + def visit_cast(self, op: Cast) -> Value | None: + return self.add(op) + + def visit_box(self, op: Box) -> Value | None: + return self.add(op) + + def visit_unbox(self, op: Unbox) -> Value | None: + return self.add(op) + + def visit_raise_standard_error(self, op: RaiseStandardError) -> Value | None: + return self.add(op) + + def visit_call_c(self, op: CallC) -> Value | None: + return self.add(op) + + def visit_truncate(self, op: Truncate) -> Value | None: + return self.add(op) + + def visit_extend(self, op: Extend) -> Value | None: + return self.add(op) + + def visit_load_global(self, op: LoadGlobal) -> Value | None: + return self.add(op) + + def visit_int_op(self, op: IntOp) -> Value | None: + return self.add(op) + + def visit_comparison_op(self, op: ComparisonOp) -> Value | None: + return self.add(op) + + def visit_float_op(self, op: FloatOp) -> Value | None: + return self.add(op) + + def visit_float_neg(self, op: FloatNeg) -> Value | None: + return self.add(op) + + def visit_float_comparison_op(self, op: FloatComparisonOp) -> Value | None: + return self.add(op) + + def visit_load_mem(self, op: LoadMem) -> Value | None: + return self.add(op) + + def visit_set_mem(self, op: SetMem) -> Value | None: + return self.add(op) + + def visit_get_element_ptr(self, op: GetElementPtr) -> Value | None: + return self.add(op) + + def visit_load_address(self, op: LoadAddress) -> Value | None: + return self.add(op) + + def visit_keep_alive(self, op: KeepAlive) -> Value | None: + return self.add(op) + + def visit_unborrow(self, op: Unborrow) -> Value | None: + return self.add(op) + + +class PatchVisitor(OpVisitor[None]): + def __init__( + self, op_map: dict[Value, Value | None], block_map: dict[BasicBlock, BasicBlock] + ) -> None: + self.op_map: Final = op_map + self.block_map: Final = block_map + + def fix_op(self, op: Value) -> Value: + new = self.op_map.get(op, op) + assert new is not None, "use of removed op" + return new + + def fix_block(self, block: BasicBlock) -> BasicBlock: + return self.block_map.get(block, block) + + def visit_goto(self, op: Goto) -> None: + op.label = self.fix_block(op.label) + + def visit_branch(self, op: Branch) -> None: + op.value = self.fix_op(op.value) + op.true = self.fix_block(op.true) + op.false = self.fix_block(op.false) + + def visit_return(self, op: Return) -> None: + op.value = self.fix_op(op.value) + + def visit_unreachable(self, op: Unreachable) -> None: + pass + + def visit_assign(self, op: Assign) -> None: + op.src = self.fix_op(op.src) + + def visit_assign_multi(self, op: AssignMulti) -> None: + op.src = [self.fix_op(s) for s in op.src] + + def visit_load_error_value(self, op: LoadErrorValue) -> None: + pass + + def visit_load_literal(self, op: LoadLiteral) -> None: + pass + + def visit_get_attr(self, op: GetAttr) -> None: + op.obj = self.fix_op(op.obj) + + def visit_set_attr(self, op: SetAttr) -> None: + op.obj = self.fix_op(op.obj) + op.src = self.fix_op(op.src) + + def visit_load_static(self, op: LoadStatic) -> None: + pass + + def visit_init_static(self, op: InitStatic) -> None: + op.value = self.fix_op(op.value) + + def visit_tuple_get(self, op: TupleGet) -> None: + op.src = self.fix_op(op.src) + + def visit_tuple_set(self, op: TupleSet) -> None: + op.items = [self.fix_op(item) for item in op.items] + + def visit_inc_ref(self, op: IncRef) -> None: + op.src = self.fix_op(op.src) + + def visit_dec_ref(self, op: DecRef) -> None: + op.src = self.fix_op(op.src) + + def visit_call(self, op: Call) -> None: + op.args = [self.fix_op(arg) for arg in op.args] + + def visit_method_call(self, op: MethodCall) -> None: + op.obj = self.fix_op(op.obj) + op.args = [self.fix_op(arg) for arg in op.args] + + def visit_cast(self, op: Cast) -> None: + op.src = self.fix_op(op.src) + + def visit_box(self, op: Box) -> None: + op.src = self.fix_op(op.src) + + def visit_unbox(self, op: Unbox) -> None: + op.src = self.fix_op(op.src) + + def visit_raise_standard_error(self, op: RaiseStandardError) -> None: + if isinstance(op.value, Value): + op.value = self.fix_op(op.value) + + def visit_call_c(self, op: CallC) -> None: + op.args = [self.fix_op(arg) for arg in op.args] + + def visit_truncate(self, op: Truncate) -> None: + op.src = self.fix_op(op.src) + + def visit_extend(self, op: Extend) -> None: + op.src = self.fix_op(op.src) + + def visit_load_global(self, op: LoadGlobal) -> None: + pass + + def visit_int_op(self, op: IntOp) -> None: + op.lhs = self.fix_op(op.lhs) + op.rhs = self.fix_op(op.rhs) + + def visit_comparison_op(self, op: ComparisonOp) -> None: + op.lhs = self.fix_op(op.lhs) + op.rhs = self.fix_op(op.rhs) + + def visit_float_op(self, op: FloatOp) -> None: + op.lhs = self.fix_op(op.lhs) + op.rhs = self.fix_op(op.rhs) + + def visit_float_neg(self, op: FloatNeg) -> None: + op.src = self.fix_op(op.src) + + def visit_float_comparison_op(self, op: FloatComparisonOp) -> None: + op.lhs = self.fix_op(op.lhs) + op.rhs = self.fix_op(op.rhs) + + def visit_load_mem(self, op: LoadMem) -> None: + op.src = self.fix_op(op.src) + + def visit_set_mem(self, op: SetMem) -> None: + op.dest = self.fix_op(op.dest) + op.src = self.fix_op(op.src) + + def visit_get_element_ptr(self, op: GetElementPtr) -> None: + op.src = self.fix_op(op.src) + + def visit_load_address(self, op: LoadAddress) -> None: + if isinstance(op.src, LoadStatic): + new = self.fix_op(op.src) + assert isinstance(new, LoadStatic) + op.src = new + + def visit_keep_alive(self, op: KeepAlive) -> None: + op.src = [self.fix_op(s) for s in op.src] + + def visit_unborrow(self, op: Unborrow) -> None: + op.src = self.fix_op(op.src) From 4259e37875219d30427a66304033f661f8b47f8f Mon Sep 17 00:00:00 2001 From: Hugo van Kemenade <1324225+hugovk@users.noreply.github.com> Date: Sat, 9 Mar 2024 16:31:16 +0200 Subject: [PATCH 41/54] Remove redundant Python 3.7 code (#17004) Some follow on from https://github.com/python/mypy/pull/15566. Also add 3.12 to tox.ini. --- mypy/modulefinder.py | 4 ++-- mypy/stubgenc.py | 2 +- mypy/util.py | 2 +- mypyc/lib-rt/CPy.h | 5 ----- mypyc/lib-rt/pythonsupport.h | 15 --------------- tox.ini | 1 + 6 files changed, 5 insertions(+), 24 deletions(-) diff --git a/mypy/modulefinder.py b/mypy/modulefinder.py index 455aa40e5975..452cfef20f4c 100644 --- a/mypy/modulefinder.py +++ b/mypy/modulefinder.py @@ -870,6 +870,6 @@ def parse_version(version: str) -> tuple[int, int]: def typeshed_py_version(options: Options) -> tuple[int, int]: """Return Python version used for checking whether module supports typeshed.""" - # Typeshed no longer covers Python 3.x versions before 3.7, so 3.7 is + # Typeshed no longer covers Python 3.x versions before 3.8, so 3.8 is # the earliest we can support. - return max(options.python_version, (3, 7)) + return max(options.python_version, (3, 8)) diff --git a/mypy/stubgenc.py b/mypy/stubgenc.py index 3bec0c246d9a..29b2636d39cc 100755 --- a/mypy/stubgenc.py +++ b/mypy/stubgenc.py @@ -495,7 +495,7 @@ def get_type_annotation(self, obj: object) -> str: if obj is None or obj is type(None): return "None" elif inspect.isclass(obj): - return "type[{}]".format(self.get_type_fullname(obj)) + return f"type[{self.get_type_fullname(obj)}]" elif isinstance(obj, FunctionType): return self.add_name("typing.Callable") elif isinstance(obj, ModuleType): diff --git a/mypy/util.py b/mypy/util.py index 968774ee7c98..bbb5a8610f7f 100644 --- a/mypy/util.py +++ b/mypy/util.py @@ -298,7 +298,7 @@ def _generate_junit_contents( text=escape("\n".join(messages)), filename="mypy", time=dt, - name="mypy-py{ver}-{platform}".format(ver=version, platform=platform), + name=f"mypy-py{version}-{platform}", ) xml += JUNIT_FOOTER diff --git a/mypyc/lib-rt/CPy.h b/mypyc/lib-rt/CPy.h index 64b716945b94..1a03f049ecb0 100644 --- a/mypyc/lib-rt/CPy.h +++ b/mypyc/lib-rt/CPy.h @@ -544,13 +544,8 @@ void CPy_AttributeError(const char *filename, const char *funcname, const char * // Misc operations -#if PY_VERSION_HEX >= 0x03080000 #define CPy_TRASHCAN_BEGIN(op, dealloc) Py_TRASHCAN_BEGIN(op, dealloc) #define CPy_TRASHCAN_END(op) Py_TRASHCAN_END -#else -#define CPy_TRASHCAN_BEGIN(op, dealloc) Py_TRASHCAN_SAFE_BEGIN(op) -#define CPy_TRASHCAN_END(op) Py_TRASHCAN_SAFE_END(op) -#endif // Tweaked version of _PyArg_Parser in CPython typedef struct CPyArg_Parser { diff --git a/mypyc/lib-rt/pythonsupport.h b/mypyc/lib-rt/pythonsupport.h index 1d493b45b89d..f7d501f44a27 100644 --- a/mypyc/lib-rt/pythonsupport.h +++ b/mypyc/lib-rt/pythonsupport.h @@ -354,21 +354,6 @@ list_count(PyListObject *self, PyObject *value) return CPyTagged_ShortFromSsize_t(count); } -#if PY_VERSION_HEX < 0x03080000 -static PyObject * -_PyDict_GetItemStringWithError(PyObject *v, const char *key) -{ - PyObject *kv, *rv; - kv = PyUnicode_FromString(key); - if (kv == NULL) { - return NULL; - } - rv = PyDict_GetItemWithError(v, kv); - Py_DECREF(kv); - return rv; -} -#endif - #define CPyUnicode_EqualToASCIIString(x, y) _PyUnicode_EqualToASCIIString(x, y) // Adapted from genobject.c in Python 3.7.2 diff --git a/tox.ini b/tox.ini index 31aed1a1ef48..c2abd05d7b6c 100644 --- a/tox.ini +++ b/tox.ini @@ -6,6 +6,7 @@ envlist = py39, py310, py311, + py312, docs, lint, type, From 16abf5cbe08c8b399381fc38220586cf2e49c2bc Mon Sep 17 00:00:00 2001 From: Shantanu <12621235+hauntsaninja@users.noreply.github.com> Date: Sat, 9 Mar 2024 19:40:22 -0800 Subject: [PATCH 42/54] Fix type narrowing for types.EllipsisType (#17003) Fixes #17002 --- mypy/types.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mypy/types.py b/mypy/types.py index b34efde15b31..d3c4df8b3b09 100644 --- a/mypy/types.py +++ b/mypy/types.py @@ -1524,7 +1524,7 @@ def is_singleton_type(self) -> bool: return ( self.type.is_enum and len(self.get_enum_values()) == 1 - or self.type.fullname == "builtins.ellipsis" + or self.type.fullname in {"builtins.ellipsis", "types.EllipsisType"} ) def get_enum_values(self) -> list[str]: From ea49e1fa488810997d192a36d85357dadb4a7f14 Mon Sep 17 00:00:00 2001 From: Ali Hamdan Date: Mon, 11 Mar 2024 15:18:39 +0100 Subject: [PATCH 43/54] Support `TypeAliasType` (#16926) Builds on top of and supersedes #16644 --------- Co-authored-by: sobolevn --- mypy/semanal.py | 132 +++++++++++++++-- mypy/typeanal.py | 49 ++++-- test-data/unit/check-generics.test | 54 +++---- test-data/unit/check-inference.test | 2 +- .../unit/check-parameter-specification.test | 18 +-- test-data/unit/check-python312.test | 23 +++ test-data/unit/check-type-aliases.test | 139 ++++++++++++++++++ test-data/unit/fixtures/typing-full.pyi | 17 ++- test-data/unit/lib-stub/typing_extensions.pyi | 8 +- 9 files changed, 373 insertions(+), 69 deletions(-) diff --git a/mypy/semanal.py b/mypy/semanal.py index 6bf02382a036..93e84ced4639 100644 --- a/mypy/semanal.py +++ b/mypy/semanal.py @@ -52,7 +52,7 @@ from contextlib import contextmanager from typing import Any, Callable, Collection, Final, Iterable, Iterator, List, TypeVar, cast -from typing_extensions import TypeAlias as _TypeAlias +from typing_extensions import TypeAlias as _TypeAlias, TypeGuard from mypy import errorcodes as codes, message_registry from mypy.constant_fold import constant_fold_expr @@ -2018,34 +2018,35 @@ def analyze_class_typevar_declaration(self, base: Type) -> tuple[TypeVarLikeList def analyze_unbound_tvar(self, t: Type) -> tuple[str, TypeVarLikeExpr] | None: if isinstance(t, UnpackType) and isinstance(t.type, UnboundType): - return self.analyze_unbound_tvar_impl(t.type, allow_tvt=True) + return self.analyze_unbound_tvar_impl(t.type, is_unpacked=True) if isinstance(t, UnboundType): sym = self.lookup_qualified(t.name, t) if sym and sym.fullname in ("typing.Unpack", "typing_extensions.Unpack"): inner_t = t.args[0] if isinstance(inner_t, UnboundType): - return self.analyze_unbound_tvar_impl(inner_t, allow_tvt=True) + return self.analyze_unbound_tvar_impl(inner_t, is_unpacked=True) return None return self.analyze_unbound_tvar_impl(t) return None def analyze_unbound_tvar_impl( - self, t: UnboundType, allow_tvt: bool = False + self, t: UnboundType, is_unpacked: bool = False, is_typealias_param: bool = False ) -> tuple[str, TypeVarLikeExpr] | None: + assert not is_unpacked or not is_typealias_param, "Mutually exclusive conditions" sym = self.lookup_qualified(t.name, t) if sym and isinstance(sym.node, PlaceholderNode): self.record_incomplete_ref() - if not allow_tvt and sym and isinstance(sym.node, ParamSpecExpr): + if not is_unpacked and sym and isinstance(sym.node, ParamSpecExpr): if sym.fullname and not self.tvar_scope.allow_binding(sym.fullname): # It's bound by our type variable scope return None return t.name, sym.node - if allow_tvt and sym and isinstance(sym.node, TypeVarTupleExpr): + if (is_unpacked or is_typealias_param) and sym and isinstance(sym.node, TypeVarTupleExpr): if sym.fullname and not self.tvar_scope.allow_binding(sym.fullname): # It's bound by our type variable scope return None return t.name, sym.node - if sym is None or not isinstance(sym.node, TypeVarExpr) or allow_tvt: + if sym is None or not isinstance(sym.node, TypeVarExpr) or is_unpacked: return None elif sym.fullname and not self.tvar_scope.allow_binding(sym.fullname): # It's bound by our type variable scope @@ -3515,7 +3516,11 @@ def analyze_simple_literal_type(self, rvalue: Expression, is_final: bool) -> Typ return typ def analyze_alias( - self, name: str, rvalue: Expression, allow_placeholder: bool = False + self, + name: str, + rvalue: Expression, + allow_placeholder: bool = False, + declared_type_vars: TypeVarLikeList | None = None, ) -> tuple[Type | None, list[TypeVarLikeType], set[str], list[str], bool]: """Check if 'rvalue' is a valid type allowed for aliasing (e.g. not a type variable). @@ -3540,9 +3545,10 @@ def analyze_alias( found_type_vars = self.find_type_var_likes(typ) tvar_defs: list[TypeVarLikeType] = [] namespace = self.qualified_name(name) + alias_type_vars = found_type_vars if declared_type_vars is None else declared_type_vars last_tvar_name_with_default: str | None = None with self.tvar_scope_frame(self.tvar_scope.class_frame(namespace)): - for name, tvar_expr in found_type_vars: + for name, tvar_expr in alias_type_vars: tvar_expr.default = tvar_expr.default.accept( TypeVarDefaultTranslator(self, tvar_expr.name, typ) ) @@ -3567,6 +3573,7 @@ def analyze_alias( in_dynamic_func=dynamic, global_scope=global_scope, allowed_alias_tvars=tvar_defs, + has_type_params=declared_type_vars is not None, ) # There can be only one variadic variable at most, the error is reported elsewhere. @@ -3579,7 +3586,7 @@ def analyze_alias( variadic = True new_tvar_defs.append(td) - qualified_tvars = [node.fullname for _name, node in found_type_vars] + qualified_tvars = [node.fullname for _name, node in alias_type_vars] empty_tuple_index = typ.empty_tuple_index if isinstance(typ, UnboundType) else False return analyzed, new_tvar_defs, depends_on, qualified_tvars, empty_tuple_index @@ -3612,7 +3619,19 @@ def check_and_set_up_type_alias(self, s: AssignmentStmt) -> bool: # unless using PEP 613 `cls: TypeAlias = A` return False - if isinstance(s.rvalue, CallExpr) and s.rvalue.analyzed: + # It can be `A = TypeAliasType('A', ...)` call, in this case, + # we just take the second argument and analyze it: + type_params: TypeVarLikeList | None + if self.check_type_alias_type_call(s.rvalue, name=lvalue.name): + rvalue = s.rvalue.args[1] + pep_695 = True + type_params = self.analyze_type_alias_type_params(s.rvalue) + else: + rvalue = s.rvalue + pep_695 = False + type_params = None + + if isinstance(rvalue, CallExpr) and rvalue.analyzed: return False existing = self.current_symbol_table().get(lvalue.name) @@ -3638,7 +3657,7 @@ def check_and_set_up_type_alias(self, s: AssignmentStmt) -> bool: return False non_global_scope = self.type or self.is_func_scope() - if not pep_613 and isinstance(s.rvalue, RefExpr) and non_global_scope: + if not pep_613 and isinstance(rvalue, RefExpr) and non_global_scope: # Fourth rule (special case): Non-subscripted right hand side creates a variable # at class and function scopes. For example: # @@ -3650,8 +3669,7 @@ def check_and_set_up_type_alias(self, s: AssignmentStmt) -> bool: # without this rule, this typical use case will require a lot of explicit # annotations (see the second rule). return False - rvalue = s.rvalue - if not pep_613 and not self.can_be_type_alias(rvalue): + if not pep_613 and not pep_695 and not self.can_be_type_alias(rvalue): return False if existing and not isinstance(existing.node, (PlaceholderNode, TypeAlias)): @@ -3668,7 +3686,7 @@ def check_and_set_up_type_alias(self, s: AssignmentStmt) -> bool: else: tag = self.track_incomplete_refs() res, alias_tvars, depends_on, qualified_tvars, empty_tuple_index = self.analyze_alias( - lvalue.name, rvalue, allow_placeholder=True + lvalue.name, rvalue, allow_placeholder=True, declared_type_vars=type_params ) if not res: return False @@ -3698,13 +3716,15 @@ def check_and_set_up_type_alias(self, s: AssignmentStmt) -> bool: # so we need to replace it with non-explicit Anys. res = make_any_non_explicit(res) # Note: with the new (lazy) type alias representation we only need to set no_args to True - # if the expected number of arguments is non-zero, so that aliases like A = List work. + # if the expected number of arguments is non-zero, so that aliases like `A = List` work + # but not aliases like `A = TypeAliasType("A", List)` as these need explicit type params. # However, eagerly expanding aliases like Text = str is a nice performance optimization. no_args = ( isinstance(res, ProperType) and isinstance(res, Instance) and not res.args and not empty_tuple_index + and not pep_695 ) if isinstance(res, ProperType) and isinstance(res, Instance): if not validate_instance(res, self.fail, empty_tuple_index): @@ -3771,6 +3791,80 @@ def check_and_set_up_type_alias(self, s: AssignmentStmt) -> bool: self.note("Use variable annotation syntax to define protocol members", s) return True + def check_type_alias_type_call(self, rvalue: Expression, *, name: str) -> TypeGuard[CallExpr]: + if not isinstance(rvalue, CallExpr): + return False + + names = ["typing_extensions.TypeAliasType"] + if self.options.python_version >= (3, 12): + names.append("typing.TypeAliasType") + if not refers_to_fullname(rvalue.callee, tuple(names)): + return False + + return self.check_typevarlike_name(rvalue, name, rvalue) + + def analyze_type_alias_type_params(self, rvalue: CallExpr) -> TypeVarLikeList: + if "type_params" in rvalue.arg_names: + type_params_arg = rvalue.args[rvalue.arg_names.index("type_params")] + if not isinstance(type_params_arg, TupleExpr): + self.fail( + "Tuple literal expected as the type_params argument to TypeAliasType", + type_params_arg, + ) + return [] + type_params = type_params_arg.items + else: + type_params = [] + + declared_tvars: TypeVarLikeList = [] + have_type_var_tuple = False + for tp_expr in type_params: + if isinstance(tp_expr, StarExpr): + tp_expr.valid = False + self.analyze_type_expr(tp_expr) + try: + base = self.expr_to_unanalyzed_type(tp_expr) + except TypeTranslationError: + continue + if not isinstance(base, UnboundType): + continue + + tag = self.track_incomplete_refs() + tvar = self.analyze_unbound_tvar_impl(base, is_typealias_param=True) + if tvar: + if isinstance(tvar[1], TypeVarTupleExpr): + if have_type_var_tuple: + self.fail( + "Can only use one TypeVarTuple in type_params argument to TypeAliasType", + base, + code=codes.TYPE_VAR, + ) + have_type_var_tuple = True + continue + have_type_var_tuple = True + elif not self.found_incomplete_ref(tag): + self.fail( + "Free type variable expected in type_params argument to TypeAliasType", + base, + code=codes.TYPE_VAR, + ) + sym = self.lookup_qualified(base.name, base) + if sym and sym.fullname in ("typing.Unpack", "typing_extensions.Unpack"): + self.note( + "Don't Unpack type variables in type_params", base, code=codes.TYPE_VAR + ) + continue + if tvar in declared_tvars: + self.fail( + f'Duplicate type variable "{tvar[0]}" in type_params argument to TypeAliasType', + base, + code=codes.TYPE_VAR, + ) + continue + if tvar: + declared_tvars.append(tvar) + return declared_tvars + def disable_invalid_recursive_aliases( self, s: AssignmentStmt, current_node: TypeAlias ) -> None: @@ -5187,6 +5281,12 @@ def visit_call_expr(self, expr: CallExpr) -> None: expr.analyzed = OpExpr("divmod", expr.args[0], expr.args[1]) expr.analyzed.line = expr.line expr.analyzed.accept(self) + elif refers_to_fullname( + expr.callee, ("typing.TypeAliasType", "typing_extensions.TypeAliasType") + ): + with self.allow_unbound_tvars_set(): + for a in expr.args: + a.accept(self) else: # Normal call expression. for a in expr.args: diff --git a/mypy/typeanal.py b/mypy/typeanal.py index 8a9ac8f4ac31..470b07948535 100644 --- a/mypy/typeanal.py +++ b/mypy/typeanal.py @@ -141,6 +141,7 @@ def analyze_type_alias( in_dynamic_func: bool = False, global_scope: bool = True, allowed_alias_tvars: list[TypeVarLikeType] | None = None, + has_type_params: bool = False, ) -> tuple[Type, set[str]]: """Analyze r.h.s. of a (potential) type alias definition. @@ -158,6 +159,7 @@ def analyze_type_alias( allow_placeholder=allow_placeholder, prohibit_self_type="type alias target", allowed_alias_tvars=allowed_alias_tvars, + has_type_params=has_type_params, ) analyzer.in_dynamic_func = in_dynamic_func analyzer.global_scope = global_scope @@ -210,6 +212,7 @@ def __init__( prohibit_self_type: str | None = None, allowed_alias_tvars: list[TypeVarLikeType] | None = None, allow_type_any: bool = False, + has_type_params: bool = False, ) -> None: self.api = api self.fail_func = api.fail @@ -231,6 +234,7 @@ def __init__( if allowed_alias_tvars is None: allowed_alias_tvars = [] self.allowed_alias_tvars = allowed_alias_tvars + self.has_type_params = has_type_params # If false, record incomplete ref if we generate PlaceholderType. self.allow_placeholder = allow_placeholder # Are we in a context where Required[] is allowed? @@ -325,7 +329,11 @@ def visit_unbound_type_nonoptional(self, t: UnboundType, defining_literal: bool) if tvar_def is None: if self.allow_unbound_tvars: return t - self.fail(f'ParamSpec "{t.name}" is unbound', t, code=codes.VALID_TYPE) + if self.defining_alias and self.has_type_params: + msg = f'ParamSpec "{t.name}" is not included in type_params' + else: + msg = f'ParamSpec "{t.name}" is unbound' + self.fail(msg, t, code=codes.VALID_TYPE) return AnyType(TypeOfAny.from_error) assert isinstance(tvar_def, ParamSpecType) if len(t.args) > 0: @@ -349,11 +357,11 @@ def visit_unbound_type_nonoptional(self, t: UnboundType, defining_literal: bool) and not defining_literal and (tvar_def is None or tvar_def not in self.allowed_alias_tvars) ): - self.fail( - f'Can\'t use bound type variable "{t.name}" to define generic alias', - t, - code=codes.VALID_TYPE, - ) + if self.has_type_params: + msg = f'Type variable "{t.name}" is not included in type_params' + else: + msg = f'Can\'t use bound type variable "{t.name}" to define generic alias' + self.fail(msg, t, code=codes.VALID_TYPE) return AnyType(TypeOfAny.from_error) if isinstance(sym.node, TypeVarExpr) and tvar_def is not None: assert isinstance(tvar_def, TypeVarType) @@ -368,17 +376,21 @@ def visit_unbound_type_nonoptional(self, t: UnboundType, defining_literal: bool) and self.defining_alias and tvar_def not in self.allowed_alias_tvars ): - self.fail( - f'Can\'t use bound type variable "{t.name}" to define generic alias', - t, - code=codes.VALID_TYPE, - ) + if self.has_type_params: + msg = f'Type variable "{t.name}" is not included in type_params' + else: + msg = f'Can\'t use bound type variable "{t.name}" to define generic alias' + self.fail(msg, t, code=codes.VALID_TYPE) return AnyType(TypeOfAny.from_error) if isinstance(sym.node, TypeVarTupleExpr): if tvar_def is None: if self.allow_unbound_tvars: return t - self.fail(f'TypeVarTuple "{t.name}" is unbound', t, code=codes.VALID_TYPE) + if self.defining_alias and self.has_type_params: + msg = f'TypeVarTuple "{t.name}" is not included in type_params' + else: + msg = f'TypeVarTuple "{t.name}" is unbound' + self.fail(msg, t, code=codes.VALID_TYPE) return AnyType(TypeOfAny.from_error) assert isinstance(tvar_def, TypeVarTupleType) if not self.allow_type_var_tuple: @@ -1267,6 +1279,19 @@ def analyze_callable_args_for_paramspec( AnyType(TypeOfAny.explicit), ret_type=ret_type, fallback=fallback ) return None + elif ( + self.defining_alias + and self.has_type_params + and tvar_def not in self.allowed_alias_tvars + ): + self.fail( + f'ParamSpec "{callable_args.name}" is not included in type_params', + callable_args, + code=codes.VALID_TYPE, + ) + return callable_with_ellipsis( + AnyType(TypeOfAny.special_form), ret_type=ret_type, fallback=fallback + ) return CallableType( [ diff --git a/test-data/unit/check-generics.test b/test-data/unit/check-generics.test index f4b7c14bd053..b1d1ff3f46a1 100644 --- a/test-data/unit/check-generics.test +++ b/test-data/unit/check-generics.test @@ -3124,8 +3124,8 @@ def dec(f: Callable[P, T]) -> Callable[P, List[T]]: ... def id(x: U) -> U: ... def either(x: U, y: U) -> U: ... def pair(x: U, y: V) -> Tuple[U, V]: ... -reveal_type(dec(id)) # N: Revealed type is "def [T] (x: T`2) -> builtins.list[T`2]" -reveal_type(dec(either)) # N: Revealed type is "def [T] (x: T`4, y: T`4) -> builtins.list[T`4]" +reveal_type(dec(id)) # N: Revealed type is "def [T] (x: T`3) -> builtins.list[T`3]" +reveal_type(dec(either)) # N: Revealed type is "def [T] (x: T`5, y: T`5) -> builtins.list[T`5]" reveal_type(dec(pair)) # N: Revealed type is "def [U, V] (x: U`-1, y: V`-2) -> builtins.list[Tuple[U`-1, V`-2]]" [builtins fixtures/list.pyi] @@ -3142,8 +3142,8 @@ V = TypeVar('V') def dec(f: Callable[P, List[T]]) -> Callable[P, T]: ... def id(x: U) -> U: ... def either(x: U, y: U) -> U: ... -reveal_type(dec(id)) # N: Revealed type is "def [T] (x: builtins.list[T`2]) -> T`2" -reveal_type(dec(either)) # N: Revealed type is "def [T] (x: builtins.list[T`4], y: builtins.list[T`4]) -> T`4" +reveal_type(dec(id)) # N: Revealed type is "def [T] (x: builtins.list[T`3]) -> T`3" +reveal_type(dec(either)) # N: Revealed type is "def [T] (x: builtins.list[T`5], y: builtins.list[T`5]) -> T`5" [builtins fixtures/list.pyi] [case testInferenceAgainstGenericParamSpecPopOff] @@ -3161,9 +3161,9 @@ def dec(f: Callable[Concatenate[T, P], S]) -> Callable[P, Callable[[T], S]]: ... def id(x: U) -> U: ... def either(x: U, y: U) -> U: ... def pair(x: U, y: V) -> Tuple[U, V]: ... -reveal_type(dec(id)) # N: Revealed type is "def () -> def [T] (T`1) -> T`1" -reveal_type(dec(either)) # N: Revealed type is "def [T] (y: T`4) -> def (T`4) -> T`4" -reveal_type(dec(pair)) # N: Revealed type is "def [V] (y: V`-2) -> def [T] (T`7) -> Tuple[T`7, V`-2]" +reveal_type(dec(id)) # N: Revealed type is "def () -> def [T] (T`2) -> T`2" +reveal_type(dec(either)) # N: Revealed type is "def [T] (y: T`5) -> def (T`5) -> T`5" +reveal_type(dec(pair)) # N: Revealed type is "def [V] (y: V`-2) -> def [T] (T`8) -> Tuple[T`8, V`-2]" reveal_type(dec(dec)) # N: Revealed type is "def () -> def [T, P, S] (def (T`-1, *P.args, **P.kwargs) -> S`-3) -> def (*P.args, **P.kwargs) -> def (T`-1) -> S`-3" [builtins fixtures/list.pyi] @@ -3182,11 +3182,11 @@ def dec(f: Callable[P, Callable[[T], S]]) -> Callable[Concatenate[T, P], S]: ... def id() -> Callable[[U], U]: ... def either(x: U) -> Callable[[U], U]: ... def pair(x: U) -> Callable[[V], Tuple[V, U]]: ... -reveal_type(dec(id)) # N: Revealed type is "def [T] (T`2) -> T`2" -reveal_type(dec(either)) # N: Revealed type is "def [T] (T`5, x: T`5) -> T`5" -reveal_type(dec(pair)) # N: Revealed type is "def [T, U] (T`8, x: U`-1) -> Tuple[T`8, U`-1]" +reveal_type(dec(id)) # N: Revealed type is "def [T] (T`3) -> T`3" +reveal_type(dec(either)) # N: Revealed type is "def [T] (T`6, x: T`6) -> T`6" +reveal_type(dec(pair)) # N: Revealed type is "def [T, U] (T`9, x: U`-1) -> Tuple[T`9, U`-1]" # This is counter-intuitive but looks correct, dec matches itself only if P can be empty -reveal_type(dec(dec)) # N: Revealed type is "def [T, S] (T`11, f: def () -> def (T`11) -> S`12) -> S`12" +reveal_type(dec(dec)) # N: Revealed type is "def [T, S] (T`12, f: def () -> def (T`12) -> S`13) -> S`13" [builtins fixtures/list.pyi] [case testInferenceAgainstGenericParamSpecVsParamSpec] @@ -3203,7 +3203,7 @@ class Bar(Generic[P, T]): ... def dec(f: Callable[P, T]) -> Callable[P, List[T]]: ... def f(*args: Q.args, **kwargs: Q.kwargs) -> Foo[Q]: ... -reveal_type(dec(f)) # N: Revealed type is "def [P] (*P.args, **P.kwargs) -> builtins.list[__main__.Foo[P`1]]" +reveal_type(dec(f)) # N: Revealed type is "def [P] (*P.args, **P.kwargs) -> builtins.list[__main__.Foo[P`2]]" g: Callable[Concatenate[int, Q], Foo[Q]] reveal_type(dec(g)) # N: Revealed type is "def [Q] (builtins.int, *Q.args, **Q.kwargs) -> builtins.list[__main__.Foo[Q`-1]]" h: Callable[Concatenate[T, Q], Bar[Q, T]] @@ -3264,8 +3264,8 @@ def transform( def dec(f: Callable[W, U]) -> Callable[W, U]: ... def dec2(f: Callable[Concatenate[str, W], U]) -> Callable[Concatenate[bytes, W], U]: ... -reveal_type(transform(dec)) # N: Revealed type is "def [P, T] (def (builtins.int, *P.args, **P.kwargs) -> T`2) -> def (builtins.int, *P.args, **P.kwargs) -> T`2" -reveal_type(transform(dec2)) # N: Revealed type is "def [W, T] (def (builtins.int, builtins.str, *W.args, **W.kwargs) -> T`6) -> def (builtins.int, builtins.bytes, *W.args, **W.kwargs) -> T`6" +reveal_type(transform(dec)) # N: Revealed type is "def [P, T] (def (builtins.int, *P.args, **P.kwargs) -> T`3) -> def (builtins.int, *P.args, **P.kwargs) -> T`3" +reveal_type(transform(dec2)) # N: Revealed type is "def [W, T] (def (builtins.int, builtins.str, *W.args, **W.kwargs) -> T`7) -> def (builtins.int, builtins.bytes, *W.args, **W.kwargs) -> T`7" [builtins fixtures/tuple.pyi] [case testNoAccidentalVariableClashInNestedGeneric] @@ -3319,8 +3319,8 @@ def id(x: U) -> U: ... def either(x: U, y: U) -> U: ... def pair(x: U, y: V) -> Tuple[U, V]: ... -reveal_type(dec(id)) # N: Revealed type is "def [T] (T`2) -> builtins.list[T`2]" -reveal_type(dec(either)) # N: Revealed type is "def [T] (T`4, T`4) -> builtins.list[T`4]" +reveal_type(dec(id)) # N: Revealed type is "def [T] (T`3) -> builtins.list[T`3]" +reveal_type(dec(either)) # N: Revealed type is "def [T] (T`5, T`5) -> builtins.list[T`5]" reveal_type(dec(pair)) # N: Revealed type is "def [U, V] (U`-1, V`-2) -> builtins.list[Tuple[U`-1, V`-2]]" [builtins fixtures/tuple.pyi] @@ -3338,8 +3338,8 @@ V = TypeVar("V") def id(x: U) -> U: ... def either(x: U, y: U) -> U: ... -reveal_type(dec(id)) # N: Revealed type is "def [T] (builtins.list[T`2]) -> T`2" -reveal_type(dec(either)) # N: Revealed type is "def [T] (builtins.list[T`4], builtins.list[T`4]) -> T`4" +reveal_type(dec(id)) # N: Revealed type is "def [T] (builtins.list[T`3]) -> T`3" +reveal_type(dec(either)) # N: Revealed type is "def [T] (builtins.list[T`5], builtins.list[T`5]) -> T`5" [builtins fixtures/tuple.pyi] [case testInferenceAgainstGenericVariadicPopOff] @@ -3358,9 +3358,9 @@ def id(x: U) -> U: ... def either(x: U, y: U) -> U: ... def pair(x: U, y: V) -> Tuple[U, V]: ... -reveal_type(dec(id)) # N: Revealed type is "def () -> def [T] (T`1) -> T`1" -reveal_type(dec(either)) # N: Revealed type is "def [T] (T`4) -> def (T`4) -> T`4" -reveal_type(dec(pair)) # N: Revealed type is "def [V] (V`-2) -> def [T] (T`7) -> Tuple[T`7, V`-2]" +reveal_type(dec(id)) # N: Revealed type is "def () -> def [T] (T`2) -> T`2" +reveal_type(dec(either)) # N: Revealed type is "def [T] (T`5) -> def (T`5) -> T`5" +reveal_type(dec(pair)) # N: Revealed type is "def [V] (V`-2) -> def [T] (T`8) -> Tuple[T`8, V`-2]" reveal_type(dec(dec)) # N: Revealed type is "def () -> def [T, Ts, S] (def (T`-1, *Unpack[Ts`-2]) -> S`-3) -> def (*Unpack[Ts`-2]) -> def (T`-1) -> S`-3" [builtins fixtures/list.pyi] @@ -3380,11 +3380,11 @@ def id() -> Callable[[U], U]: ... def either(x: U) -> Callable[[U], U]: ... def pair(x: U) -> Callable[[V], Tuple[V, U]]: ... -reveal_type(dec(id)) # N: Revealed type is "def [T] (T`2) -> T`2" -reveal_type(dec(either)) # N: Revealed type is "def [T] (T`5, T`5) -> T`5" -reveal_type(dec(pair)) # N: Revealed type is "def [T, U] (T`8, U`-1) -> Tuple[T`8, U`-1]" +reveal_type(dec(id)) # N: Revealed type is "def [T] (T`3) -> T`3" +reveal_type(dec(either)) # N: Revealed type is "def [T] (T`6, T`6) -> T`6" +reveal_type(dec(pair)) # N: Revealed type is "def [T, U] (T`9, U`-1) -> Tuple[T`9, U`-1]" # This is counter-intuitive but looks correct, dec matches itself only if Ts is empty -reveal_type(dec(dec)) # N: Revealed type is "def [T, S] (T`11, def () -> def (T`11) -> S`12) -> S`12" +reveal_type(dec(dec)) # N: Revealed type is "def [T, S] (T`12, def () -> def (T`12) -> S`13) -> S`13" [builtins fixtures/list.pyi] [case testInferenceAgainstGenericVariadicVsVariadic] @@ -3402,9 +3402,9 @@ class Bar(Generic[Unpack[Ts], T]): ... def dec(f: Callable[[Unpack[Ts]], T]) -> Callable[[Unpack[Ts]], List[T]]: ... def f(*args: Unpack[Us]) -> Foo[Unpack[Us]]: ... -reveal_type(dec(f)) # N: Revealed type is "def [Ts] (*Unpack[Ts`1]) -> builtins.list[__main__.Foo[Unpack[Ts`1]]]" +reveal_type(dec(f)) # N: Revealed type is "def [Ts] (*Unpack[Ts`2]) -> builtins.list[__main__.Foo[Unpack[Ts`2]]]" g: Callable[[Unpack[Us]], Foo[Unpack[Us]]] -reveal_type(dec(g)) # N: Revealed type is "def [Ts] (*Unpack[Ts`3]) -> builtins.list[__main__.Foo[Unpack[Ts`3]]]" +reveal_type(dec(g)) # N: Revealed type is "def [Ts] (*Unpack[Ts`4]) -> builtins.list[__main__.Foo[Unpack[Ts`4]]]" [builtins fixtures/list.pyi] [case testInferenceAgainstGenericVariadicVsVariadicConcatenate] diff --git a/test-data/unit/check-inference.test b/test-data/unit/check-inference.test index 1b1ce607bf28..08b53ab16972 100644 --- a/test-data/unit/check-inference.test +++ b/test-data/unit/check-inference.test @@ -3807,7 +3807,7 @@ def Negate(count: int, /, metric: Metric[float]) -> float: ... def Combine(count: int, m1: Metric[T], m2: Metric[T], /, *more: Metric[T]) -> T: ... reveal_type(Negate) # N: Revealed type is "def (metric: __main__.Metric[builtins.float]) -> builtins.float" -reveal_type(Combine) # N: Revealed type is "def [T] (def () -> T`4, def () -> T`4, *more: def () -> T`4) -> T`4" +reveal_type(Combine) # N: Revealed type is "def [T] (def () -> T`5, def () -> T`5, *more: def () -> T`5) -> T`5" def m1() -> float: ... def m2() -> float: ... diff --git a/test-data/unit/check-parameter-specification.test b/test-data/unit/check-parameter-specification.test index b212c7585993..8fd9abcb9752 100644 --- a/test-data/unit/check-parameter-specification.test +++ b/test-data/unit/check-parameter-specification.test @@ -901,8 +901,8 @@ class A: def func(self, action: Callable[_P, _R], *args: _P.args, **kwargs: _P.kwargs) -> _R: ... -reveal_type(A.func) # N: Revealed type is "def [_P, _R] (self: __main__.A, action: def (*_P.args, **_P.kwargs) -> _R`3, *_P.args, **_P.kwargs) -> _R`3" -reveal_type(A().func) # N: Revealed type is "def [_P, _R] (action: def (*_P.args, **_P.kwargs) -> _R`7, *_P.args, **_P.kwargs) -> _R`7" +reveal_type(A.func) # N: Revealed type is "def [_P, _R] (self: __main__.A, action: def (*_P.args, **_P.kwargs) -> _R`4, *_P.args, **_P.kwargs) -> _R`4" +reveal_type(A().func) # N: Revealed type is "def [_P, _R] (action: def (*_P.args, **_P.kwargs) -> _R`8, *_P.args, **_P.kwargs) -> _R`8" def f(x: int) -> int: ... @@ -933,8 +933,8 @@ class A: def func(self, action: Job[_P, None]) -> Job[_P, None]: ... -reveal_type(A.func) # N: Revealed type is "def [_P] (self: __main__.A, action: __main__.Job[_P`2, None]) -> __main__.Job[_P`2, None]" -reveal_type(A().func) # N: Revealed type is "def [_P] (action: __main__.Job[_P`4, None]) -> __main__.Job[_P`4, None]" +reveal_type(A.func) # N: Revealed type is "def [_P] (self: __main__.A, action: __main__.Job[_P`3, None]) -> __main__.Job[_P`3, None]" +reveal_type(A().func) # N: Revealed type is "def [_P] (action: __main__.Job[_P`5, None]) -> __main__.Job[_P`5, None]" reveal_type(A().func(Job(lambda x: x))) # N: Revealed type is "__main__.Job[[x: Any], None]" def f(x: int, y: int) -> None: ... @@ -1096,7 +1096,7 @@ j = Job(generic_f) reveal_type(j) # N: Revealed type is "__main__.Job[[x: _T`-1]]" jf = j.into_callable() -reveal_type(jf) # N: Revealed type is "def [_T] (x: _T`2)" +reveal_type(jf) # N: Revealed type is "def [_T] (x: _T`3)" reveal_type(jf(1)) # N: Revealed type is "None" [builtins fixtures/paramspec.pyi] @@ -1115,10 +1115,10 @@ class Job(Generic[_P, _T]): def generic_f(x: _T) -> _T: ... j = Job(generic_f) -reveal_type(j) # N: Revealed type is "__main__.Job[[x: _T`2], _T`2]" +reveal_type(j) # N: Revealed type is "__main__.Job[[x: _T`3], _T`3]" jf = j.into_callable() -reveal_type(jf) # N: Revealed type is "def [_T] (x: _T`3) -> _T`3" +reveal_type(jf) # N: Revealed type is "def [_T] (x: _T`4) -> _T`4" reveal_type(jf(1)) # N: Revealed type is "builtins.int" [builtins fixtures/paramspec.pyi] @@ -1619,13 +1619,13 @@ U = TypeVar("U") def dec(f: Callable[P, T]) -> Callable[P, List[T]]: ... def test(x: U) -> U: ... reveal_type(dec) # N: Revealed type is "def [P, T] (f: def (*P.args, **P.kwargs) -> T`-2) -> def (*P.args, **P.kwargs) -> builtins.list[T`-2]" -reveal_type(dec(test)) # N: Revealed type is "def [T] (x: T`2) -> builtins.list[T`2]" +reveal_type(dec(test)) # N: Revealed type is "def [T] (x: T`3) -> builtins.list[T`3]" class A: ... TA = TypeVar("TA", bound=A) def test_with_bound(x: TA) -> TA: ... -reveal_type(dec(test_with_bound)) # N: Revealed type is "def [T <: __main__.A] (x: T`4) -> builtins.list[T`4]" +reveal_type(dec(test_with_bound)) # N: Revealed type is "def [T <: __main__.A] (x: T`5) -> builtins.list[T`5]" dec(test_with_bound)(0) # E: Value of type variable "T" of function cannot be "int" dec(test_with_bound)(A()) # OK [builtins fixtures/paramspec.pyi] diff --git a/test-data/unit/check-python312.test b/test-data/unit/check-python312.test index 285563c19991..188c51f98185 100644 --- a/test-data/unit/check-python312.test +++ b/test-data/unit/check-python312.test @@ -60,3 +60,26 @@ def func2[**P](x: Callable[P, int]) -> Callable[P, str]: ... # E: PEP 695 gener def func3[*Ts](x: tuple[*Ts]) -> tuple[int, *Ts]: ... # E: PEP 695 generics are not yet supported \ # E: Name "Ts" is not defined [builtins fixtures/tuple.pyi] + +[case test695TypeAliasType] +from typing import Callable, TypeAliasType, TypeVar, TypeVarTuple + +T = TypeVar("T") +Ts = TypeVarTuple("Ts") + +TestType = TypeAliasType("TestType", int | str) +x: TestType = 42 +y: TestType = 'a' +z: TestType = object() # E: Incompatible types in assignment (expression has type "object", variable has type "Union[int, str]") + +BadAlias1 = TypeAliasType("BadAlias1", tuple[*Ts]) # E: TypeVarTuple "Ts" is not included in type_params +ba1: BadAlias1[int] # E: Bad number of arguments for type alias, expected 0, given 1 +reveal_type(ba1) # N: Revealed type is "builtins.tuple[Any, ...]" + +# TODO this should report errors on the two following lines +#BadAlias2 = TypeAliasType("BadAlias2", Callable[[*Ts], str]) +#ba2: BadAlias2[int] +#reveal_type(ba2) + +[builtins fixtures/tuple.pyi] +[typing fixtures/typing-full.pyi] diff --git a/test-data/unit/check-type-aliases.test b/test-data/unit/check-type-aliases.test index a43233eed973..79a443dbeedc 100644 --- a/test-data/unit/check-type-aliases.test +++ b/test-data/unit/check-type-aliases.test @@ -1065,3 +1065,142 @@ def eval(e: Expr) -> int: elif e[0] == 456: return -eval(e[1]) [builtins fixtures/dict-full.pyi] + +[case testTypeAliasType] +from typing import Union +from typing_extensions import TypeAliasType + +TestType = TypeAliasType("TestType", Union[int, str]) +x: TestType = 42 +y: TestType = 'a' +z: TestType = object() # E: Incompatible types in assignment (expression has type "object", variable has type "Union[int, str]") +[builtins fixtures/tuple.pyi] + +[case testTypeAliasTypeInvalid] +from typing_extensions import TypeAliasType + +TestType = TypeAliasType("T", int) # E: String argument 1 "T" to TypeAliasType(...) does not match variable name "TestType" + +T1 = T2 = TypeAliasType("T", int) +t1: T1 # E: Variable "__main__.T1" is not valid as a type \ + # N: See https://mypy.readthedocs.io/en/stable/common_issues.html#variables-vs-type-aliases + +T3 = TypeAliasType("T3", -1) # E: Invalid type: try using Literal[-1] instead? +t3: T3 +reveal_type(t3) # N: Revealed type is "Any" +[builtins fixtures/tuple.pyi] + +[case testTypeAliasTypeGeneric] +from typing import Callable, Dict, Generic, TypeVar, Tuple +from typing_extensions import TypeAliasType, TypeVarTuple, ParamSpec, Unpack + +K = TypeVar('K') +V = TypeVar('V') +T = TypeVar('T') +Ts = TypeVarTuple("Ts") +Ts1 = TypeVarTuple("Ts1") +P = ParamSpec("P") + +TestType = TypeAliasType("TestType", Dict[K, V], type_params=(K, V)) +x: TestType[int, str] = {1: 'a'} +y: TestType[str, int] = {'a': 1} +z: TestType[str, int] = {1: 'a'} # E: Dict entry 0 has incompatible type "int": "str"; expected "str": "int" +w: TestType[int] # E: Bad number of arguments for type alias, expected 2, given 1 + +InvertedDict = TypeAliasType("InvertedDict", Dict[K, V], type_params=(V, K)) +xi: InvertedDict[str, int] = {1: 'a'} +yi: InvertedDict[str, int] = {'a': 1} # E: Dict entry 0 has incompatible type "str": "int"; expected "int": "str" +zi: InvertedDict[int, str] = {1: 'a'} # E: Dict entry 0 has incompatible type "int": "str"; expected "str": "int" +reveal_type(xi) # N: Revealed type is "builtins.dict[builtins.int, builtins.str]" + +VariadicAlias1 = TypeAliasType("VariadicAlias1", Tuple[Unpack[Ts]], type_params=(Ts,)) +VariadicAlias2 = TypeAliasType("VariadicAlias2", Tuple[Unpack[Ts], K], type_params=(Ts, K)) +VariadicAlias3 = TypeAliasType("VariadicAlias3", Callable[[Unpack[Ts]], int], type_params=(Ts,)) +xv: VariadicAlias1[int, str] = (1, 'a') +yv: VariadicAlias1[str, int] = (1, 'a') # E: Incompatible types in assignment (expression has type "Tuple[int, str]", variable has type "Tuple[str, int]") +zv: VariadicAlias2[int, str] = (1, 'a') +def int_in_int_out(x: int) -> int: return x +wv: VariadicAlias3[int] = int_in_int_out +reveal_type(wv) # N: Revealed type is "def (builtins.int) -> builtins.int" + +ParamAlias = TypeAliasType("ParamAlias", Callable[P, int], type_params=(P,)) +def f(x: str, y: float) -> int: return 1 +def g(x: int, y: float) -> int: return 1 +xp1: ParamAlias[str, float] = f +xp2: ParamAlias[str, float] = g # E: Incompatible types in assignment (expression has type "Callable[[int, float], int]", variable has type "Callable[[str, float], int]") +xp3: ParamAlias[str, float] = lambda x, y: 1 + +class G(Generic[P, T]): ... +ParamAlias2 = TypeAliasType("ParamAlias2", G[P, T], type_params=(P, T)) +xp: ParamAlias2[[int], str] +reveal_type(xp) # N: Revealed type is "__main__.G[[builtins.int], builtins.str]" +[builtins fixtures/dict.pyi] + +[case testTypeAliasTypeInvalidGeneric] +from typing_extensions import TypeAliasType, TypeVarTuple, ParamSpec +from typing import Callable, Dict, Generic, TypeVar, Tuple, Unpack + +K = TypeVar('K') +V = TypeVar('V') +T = TypeVar('T') +Ts = TypeVarTuple("Ts") +Ts1 = TypeVarTuple("Ts1") +P = ParamSpec("P") + +Ta0 = TypeAliasType("Ta0", int, type_params=(T, T)) # E: Duplicate type variable "T" in type_params argument to TypeAliasType + +Ta1 = TypeAliasType("Ta1", int, type_params=K) # E: Tuple literal expected as the type_params argument to TypeAliasType + +Ta2 = TypeAliasType("Ta2", int, type_params=(None,)) # E: Free type variable expected in type_params argument to TypeAliasType + +Ta3 = TypeAliasType("Ta3", Dict[K, V], type_params=(V,)) # E: Type variable "K" is not included in type_params +partially_generic1: Ta3[int] = {"a": 1} +reveal_type(partially_generic1) # N: Revealed type is "builtins.dict[Any, builtins.int]" +partially_generic2: Ta3[int] = {1: "a"} # E: Dict entry 0 has incompatible type "int": "str"; expected "Any": "int" + +Ta4 = TypeAliasType("Ta4", Tuple[Unpack[Ts]], type_params=(Ts, Ts1)) # E: Can only use one TypeVarTuple in type_params argument to TypeAliasType + +Ta5 = TypeAliasType("Ta5", Dict) # Unlike old style aliases, this is not generic +non_generic_dict: Ta5[int, str] # E: Bad number of arguments for type alias, expected 0, given 2 +reveal_type(non_generic_dict) # N: Revealed type is "builtins.dict[Any, Any]" + +Ta6 = TypeAliasType("Ta6", Tuple[Unpack[Ts]]) # E: TypeVarTuple "Ts" is not included in type_params +unbound_tvt_alias: Ta6[int] # E: Bad number of arguments for type alias, expected 0, given 1 +reveal_type(unbound_tvt_alias) # N: Revealed type is "builtins.tuple[Any, ...]" + +class G(Generic[P, T]): ... +Ta7 = TypeAliasType("Ta7", G[P, T]) # E: ParamSpec "P" is not included in type_params \ + # E: Type variable "T" is not included in type_params +unbound_ps_alias: Ta7[[int], str] # E: Bracketed expression "[...]" is not valid as a type \ + # N: Did you mean "List[...]"? \ + # E: Bad number of arguments for type alias, expected 0, given 2 +reveal_type(unbound_ps_alias) # N: Revealed type is "__main__.G[Any, Any]" + +Ta8 = TypeAliasType("Ta8", Callable[P, int]) # E: ParamSpec "P" is not included in type_params +unbound_ps_alias2: Ta8[int] # E: Bad number of arguments for type alias, expected 0, given 1 +reveal_type(unbound_ps_alias2) # N: Revealed type is "def [P] (*Any, **Any) -> builtins.int" + +Ta9 = TypeAliasType("Ta9", Callable[P, T]) # E: ParamSpec "P" is not included in type_params \ + # E: Type variable "T" is not included in type_params +unbound_ps_alias3: Ta9[int, str] # E: Bad number of arguments for type alias, expected 0, given 2 +reveal_type(unbound_ps_alias3) # N: Revealed type is "def [P] (*Any, **Any) -> Any" + +# TODO this should report errors on the two following lines +#Ta10 = TypeAliasType("Ta10", Callable[[Unpack[Ts]], str]) +#unbound_tvt_alias2: Ta10[int] +#reveal_type(unbound_tvt_alias2) + +[builtins fixtures/dict.pyi] + +[case testTypeAliasTypeNoUnpackInTypeParams311] +# flags: --python-version 3.11 +from typing_extensions import TypeAliasType, TypeVar, TypeVarTuple, Unpack + +T = TypeVar("T") +Ts = TypeVarTuple("Ts") + +Ta1 = TypeAliasType("Ta1", None, type_params=(*Ts,)) # E: can't use starred expression here +Ta2 = TypeAliasType("Ta2", None, type_params=(Unpack[Ts],)) # E: Free type variable expected in type_params argument to TypeAliasType \ + # N: Don't Unpack type variables in type_params + +[builtins fixtures/tuple.pyi] diff --git a/test-data/unit/fixtures/typing-full.pyi b/test-data/unit/fixtures/typing-full.pyi index ca8a2413f05f..f7da75fa4cd0 100644 --- a/test-data/unit/fixtures/typing-full.pyi +++ b/test-data/unit/fixtures/typing-full.pyi @@ -10,13 +10,17 @@ from abc import abstractmethod, ABCMeta class GenericMeta(type): pass +class _SpecialForm: ... +class TypeVar: ... +class ParamSpec: ... +class TypeVarTuple: ... + def cast(t, o): ... def assert_type(o, t): ... overload = 0 Any = 0 Union = 0 Optional = 0 -TypeVar = 0 Generic = 0 Protocol = 0 Tuple = 0 @@ -39,6 +43,8 @@ U = TypeVar('U') V = TypeVar('V') S = TypeVar('S') +def final(x: T) -> T: ... + class NamedTuple(tuple[Any, ...]): ... # Note: definitions below are different from typeshed, variances are declared @@ -182,8 +188,6 @@ class _TypedDict(Mapping[str, object]): def update(self: T, __m: T) -> None: ... def __delitem__(self, k: NoReturn) -> None: ... -class _SpecialForm: pass - def dataclass_transform( *, eq_default: bool = ..., @@ -199,3 +203,10 @@ def reveal_type(__obj: T) -> T: ... # Only exists in type checking time: def type_check_only(__func_or_class: T) -> T: ... + +# Was added in 3.12 +@final +class TypeAliasType: + def __init__( + self, name: str, value: Any, *, type_params: Tuple[Union[TypeVar, ParamSpec, TypeVarTuple], ...] = () + ) -> None: ... diff --git a/test-data/unit/lib-stub/typing_extensions.pyi b/test-data/unit/lib-stub/typing_extensions.pyi index ff55f1b54c7d..b7b738f63d92 100644 --- a/test-data/unit/lib-stub/typing_extensions.pyi +++ b/test-data/unit/lib-stub/typing_extensions.pyi @@ -1,5 +1,5 @@ import typing -from typing import Any, Callable, Mapping, Iterable, Iterator, NoReturn as NoReturn, Dict, Tuple, Type +from typing import Any, Callable, Mapping, Iterable, Iterator, NoReturn as NoReturn, Dict, Tuple, Type, Union from typing import TYPE_CHECKING as TYPE_CHECKING from typing import NewType as NewType, overload as overload @@ -40,6 +40,12 @@ Never: _SpecialForm TypeVarTuple: _SpecialForm Unpack: _SpecialForm +@final +class TypeAliasType: + def __init__( + self, name: str, value: Any, *, type_params: Tuple[Union[TypeVar, ParamSpec, TypeVarTuple], ...] = () + ) -> None: ... + # Fallback type for all typed dicts (does not exist at runtime). class _TypedDict(Mapping[str, object]): # Needed to make this class non-abstract. It is explicitly declared abstract in From a00fcba1e77ac944276b8c4ad0a31b7b05ded59f Mon Sep 17 00:00:00 2001 From: Tamir Duberstein Date: Wed, 13 Mar 2024 16:42:20 +0000 Subject: [PATCH 44/54] Revert "Revert use of `ParamSpec` for `functools.wraps`" (#16942) ParamSpec support has improved so it doesn't seem necessary to revert the changes any more. --- misc/generate_changelog.py | 1 - misc/sync-typeshed.py | 1 - mypy/typeshed/stdlib/functools.pyi | 40 +++++++++++++++++++----------- 3 files changed, 26 insertions(+), 16 deletions(-) diff --git a/misc/generate_changelog.py b/misc/generate_changelog.py index 7c7f28b6eeb7..ebab6c569152 100644 --- a/misc/generate_changelog.py +++ b/misc/generate_changelog.py @@ -79,7 +79,6 @@ def filter_omitted_commits(commits: list[CommitInfo]) -> list[CommitInfo]: "Revert sum literal integer change", "Remove use of LiteralString in builtins", "Revert typeshed ctypes change", - "Revert use of `ParamSpec` for `functools.wraps`", ) ): # These are generated by a typeshed sync. diff --git a/misc/sync-typeshed.py b/misc/sync-typeshed.py index ee6414ab7b19..56bc1624d5d0 100644 --- a/misc/sync-typeshed.py +++ b/misc/sync-typeshed.py @@ -182,7 +182,6 @@ def main() -> None: "d25e4a9eb", # LiteralString reverts "d132999ba", # sum reverts "dd12a2d81", # ctypes reverts - "0dd4b6f75", # ParamSpec for functools.wraps ] for commit in commits_to_cherry_pick: try: diff --git a/mypy/typeshed/stdlib/functools.pyi b/mypy/typeshed/stdlib/functools.pyi index 991182486113..d3f702bcef4f 100644 --- a/mypy/typeshed/stdlib/functools.pyi +++ b/mypy/typeshed/stdlib/functools.pyi @@ -1,9 +1,9 @@ import sys import types -from _typeshed import IdentityFunction, SupportsAllComparisons, SupportsItems +from _typeshed import SupportsAllComparisons, SupportsItems from collections.abc import Callable, Hashable, Iterable, Sequence, Sized from typing import Any, Generic, Literal, NamedTuple, TypedDict, TypeVar, final, overload -from typing_extensions import Self, TypeAlias +from typing_extensions import ParamSpec, Self, TypeAlias if sys.version_info >= (3, 9): from types import GenericAlias @@ -27,11 +27,13 @@ __all__ = [ if sys.version_info >= (3, 9): __all__ += ["cache"] -_AnyCallable: TypeAlias = Callable[..., object] - _T = TypeVar("_T") _T_co = TypeVar("_T_co", covariant=True) _S = TypeVar("_S") +_PWrapped = ParamSpec("_PWrapped") +_RWrapped = TypeVar("_RWrapped") +_PWrapper = ParamSpec("_PWrapper") +_RWrapper = TypeVar("_RWrapper") @overload def reduce(__function: Callable[[_T, _S], _T], __sequence: Iterable[_S], __initial: _T) -> _T: ... @@ -81,31 +83,41 @@ else: ] WRAPPER_UPDATES: tuple[Literal["__dict__"]] +class _Wrapped(Generic[_PWrapped, _RWrapped, _PWrapper, _RWrapper]): + __wrapped__: Callable[_PWrapped, _RWrapped] + def __call__(self, *args: _PWrapper.args, **kwargs: _PWrapper.kwargs) -> _RWrapper: ... + # as with ``Callable``, we'll assume that these attributes exist + __name__: str + __qualname__: str + +class _Wrapper(Generic[_PWrapped, _RWrapped]): + def __call__(self, f: Callable[_PWrapper, _RWrapper]) -> _Wrapped[_PWrapped, _RWrapped, _PWrapper, _RWrapper]: ... + if sys.version_info >= (3, 12): def update_wrapper( - wrapper: _T, - wrapped: _AnyCallable, + wrapper: Callable[_PWrapper, _RWrapper], + wrapped: Callable[_PWrapped, _RWrapped], assigned: Sequence[str] = ("__module__", "__name__", "__qualname__", "__doc__", "__annotations__", "__type_params__"), updated: Sequence[str] = ("__dict__",), - ) -> _T: ... + ) -> _Wrapped[_PWrapped, _RWrapped, _PWrapper, _RWrapper]: ... def wraps( - wrapped: _AnyCallable, + wrapped: Callable[_PWrapped, _RWrapped], assigned: Sequence[str] = ("__module__", "__name__", "__qualname__", "__doc__", "__annotations__", "__type_params__"), updated: Sequence[str] = ("__dict__",), - ) -> IdentityFunction: ... + ) -> _Wrapper[_PWrapped, _RWrapped]: ... else: def update_wrapper( - wrapper: _T, - wrapped: _AnyCallable, + wrapper: Callable[_PWrapper, _RWrapper], + wrapped: Callable[_PWrapped, _RWrapped], assigned: Sequence[str] = ("__module__", "__name__", "__qualname__", "__doc__", "__annotations__"), updated: Sequence[str] = ("__dict__",), - ) -> _T: ... + ) -> _Wrapped[_PWrapped, _RWrapped, _PWrapper, _RWrapper]: ... def wraps( - wrapped: _AnyCallable, + wrapped: Callable[_PWrapped, _RWrapped], assigned: Sequence[str] = ("__module__", "__name__", "__qualname__", "__doc__", "__annotations__"), updated: Sequence[str] = ("__dict__",), - ) -> IdentityFunction: ... + ) -> _Wrapper[_PWrapped, _RWrapped]: ... def total_ordering(cls: type[_T]) -> type[_T]: ... def cmp_to_key(mycmp: Callable[[_T, _T], int]) -> Callable[[_T], SupportsAllComparisons]: ... From a18a0db0c77e71050aaf31a53ad1fba8c663fd1a Mon Sep 17 00:00:00 2001 From: Jukka Lehtosalo Date: Thu, 14 Mar 2024 17:14:59 +0000 Subject: [PATCH 45/54] [mypyc] Optimize away some bool/bit registers (#17022) If a register is always used in a branch immediately after assignment, and it isn't used for anything else, we can replace the assignment with a branch op. This avoids some assignment ops and gotos. This is not a very interesting optimization in general, but it will help a lot with tagged integer operations once I refactor them to be generated in the lowering pass (in follow-up PRs). --- mypyc/codegen/emitmodule.py | 4 +- mypyc/test-data/opt-flag-elimination.test | 300 ++++++++++++++++++ ...y_propagation.py => test_optimizations.py} | 31 +- mypyc/transform/flag_elimination.py | 108 +++++++ mypyc/transform/ir_transform.py | 16 +- 5 files changed, 445 insertions(+), 14 deletions(-) create mode 100644 mypyc/test-data/opt-flag-elimination.test rename mypyc/test/{test_copy_propagation.py => test_optimizations.py} (62%) create mode 100644 mypyc/transform/flag_elimination.py diff --git a/mypyc/codegen/emitmodule.py b/mypyc/codegen/emitmodule.py index 0035bd53188b..9466bc2cea79 100644 --- a/mypyc/codegen/emitmodule.py +++ b/mypyc/codegen/emitmodule.py @@ -58,6 +58,7 @@ from mypyc.options import CompilerOptions from mypyc.transform.copy_propagation import do_copy_propagation from mypyc.transform.exceptions import insert_exception_handling +from mypyc.transform.flag_elimination import do_flag_elimination from mypyc.transform.refcount import insert_ref_count_opcodes from mypyc.transform.uninit import insert_uninit_checks @@ -234,8 +235,9 @@ def compile_scc_to_ir( insert_exception_handling(fn) # Insert refcount handling. insert_ref_count_opcodes(fn) - # Perform copy propagation optimization. + # Perform optimizations. do_copy_propagation(fn, compiler_options) + do_flag_elimination(fn, compiler_options) return modules diff --git a/mypyc/test-data/opt-flag-elimination.test b/mypyc/test-data/opt-flag-elimination.test new file mode 100644 index 000000000000..f047a87dc3fa --- /dev/null +++ b/mypyc/test-data/opt-flag-elimination.test @@ -0,0 +1,300 @@ +-- Test cases for "flag elimination" optimization. Used to optimize away +-- registers that are always used immediately after assignment as branch conditions. + +[case testFlagEliminationSimple] +def c() -> bool: + return True +def d() -> bool: + return True + +def f(x: bool) -> int: + if x: + b = c() + else: + b = d() + if b: + return 1 + else: + return 2 +[out] +def c(): +L0: + return 1 +def d(): +L0: + return 1 +def f(x): + x, r0, r1 :: bool +L0: + if x goto L1 else goto L2 :: bool +L1: + r0 = c() + if r0 goto L4 else goto L5 :: bool +L2: + r1 = d() + if r1 goto L4 else goto L5 :: bool +L3: + unreachable +L4: + return 2 +L5: + return 4 + +[case testFlagEliminationOneAssignment] +def c() -> bool: + return True + +def f(x: bool) -> int: + # Not applied here + b = c() + if b: + return 1 + else: + return 2 +[out] +def c(): +L0: + return 1 +def f(x): + x, r0, b :: bool +L0: + r0 = c() + b = r0 + if b goto L1 else goto L2 :: bool +L1: + return 2 +L2: + return 4 + +[case testFlagEliminationThreeCases] +def c(x: int) -> bool: + return True + +def f(x: bool, y: bool) -> int: + if x: + b = c(1) + elif y: + b = c(2) + else: + b = c(3) + if b: + return 1 + else: + return 2 +[out] +def c(x): + x :: int +L0: + return 1 +def f(x, y): + x, y, r0, r1, r2 :: bool +L0: + if x goto L1 else goto L2 :: bool +L1: + r0 = c(2) + if r0 goto L6 else goto L7 :: bool +L2: + if y goto L3 else goto L4 :: bool +L3: + r1 = c(4) + if r1 goto L6 else goto L7 :: bool +L4: + r2 = c(6) + if r2 goto L6 else goto L7 :: bool +L5: + unreachable +L6: + return 2 +L7: + return 4 + +[case testFlagEliminationAssignmentNotLastOp] +def f(x: bool) -> int: + y = 0 + if x: + b = True + y = 1 + else: + b = False + if b: + return 1 + else: + return 2 +[out] +def f(x): + x :: bool + y :: int + b :: bool +L0: + y = 0 + if x goto L1 else goto L2 :: bool +L1: + b = 1 + y = 2 + goto L3 +L2: + b = 0 +L3: + if b goto L4 else goto L5 :: bool +L4: + return 2 +L5: + return 4 + +[case testFlagEliminationAssignmentNoDirectGoto] +def f(x: bool) -> int: + if x: + b = True + else: + b = False + if x: + if b: + return 1 + else: + return 2 + return 4 +[out] +def f(x): + x, b :: bool +L0: + if x goto L1 else goto L2 :: bool +L1: + b = 1 + goto L3 +L2: + b = 0 +L3: + if x goto L4 else goto L7 :: bool +L4: + if b goto L5 else goto L6 :: bool +L5: + return 2 +L6: + return 4 +L7: + return 8 + +[case testFlagEliminationBranchNotNextOpAfterGoto] +def f(x: bool) -> int: + if x: + b = True + else: + b = False + y = 1 # Prevents the optimization + if b: + return 1 + else: + return 2 +[out] +def f(x): + x, b :: bool + y :: int +L0: + if x goto L1 else goto L2 :: bool +L1: + b = 1 + goto L3 +L2: + b = 0 +L3: + y = 2 + if b goto L4 else goto L5 :: bool +L4: + return 2 +L5: + return 4 + +[case testFlagEliminationFlagReadTwice] +def f(x: bool) -> bool: + if x: + b = True + else: + b = False + if b: + return b # Prevents the optimization + else: + return False +[out] +def f(x): + x, b :: bool +L0: + if x goto L1 else goto L2 :: bool +L1: + b = 1 + goto L3 +L2: + b = 0 +L3: + if b goto L4 else goto L5 :: bool +L4: + return b +L5: + return 0 + +[case testFlagEliminationArgumentNotEligible] +def f(x: bool, b: bool) -> bool: + if x: + b = True + else: + b = False + if b: + return True + else: + return False +[out] +def f(x, b): + x, b :: bool +L0: + if x goto L1 else goto L2 :: bool +L1: + b = 1 + goto L3 +L2: + b = 0 +L3: + if b goto L4 else goto L5 :: bool +L4: + return 1 +L5: + return 0 + +[case testFlagEliminationFlagNotAlwaysDefined] +def f(x: bool, y: bool) -> bool: + if x: + b = True + elif y: + b = False + else: + bb = False # b not assigned here -> can't optimize + if b: + return True + else: + return False +[out] +def f(x, y): + x, y, r0, b, bb, r1 :: bool +L0: + r0 = :: bool + b = r0 + if x goto L1 else goto L2 :: bool +L1: + b = 1 + goto L5 +L2: + if y goto L3 else goto L4 :: bool +L3: + b = 0 + goto L5 +L4: + bb = 0 +L5: + if is_error(b) goto L6 else goto L7 +L6: + r1 = raise UnboundLocalError('local variable "b" referenced before assignment') + unreachable +L7: + if b goto L8 else goto L9 :: bool +L8: + return 1 +L9: + return 0 diff --git a/mypyc/test/test_copy_propagation.py b/mypyc/test/test_optimizations.py similarity index 62% rename from mypyc/test/test_copy_propagation.py rename to mypyc/test/test_optimizations.py index c729e3d186c3..3f1f46ac1dd7 100644 --- a/mypyc/test/test_copy_propagation.py +++ b/mypyc/test/test_optimizations.py @@ -1,4 +1,4 @@ -"""Runner for copy propagation optimization tests.""" +"""Runner for IR optimization tests.""" from __future__ import annotations @@ -8,6 +8,7 @@ from mypy.test.config import test_temp_dir from mypy.test.data import DataDrivenTestCase from mypyc.common import TOP_LEVEL_NAME +from mypyc.ir.func_ir import FuncIR from mypyc.ir.pprint import format_func from mypyc.options import CompilerOptions from mypyc.test.testutil import ( @@ -19,13 +20,16 @@ use_custom_builtins, ) from mypyc.transform.copy_propagation import do_copy_propagation +from mypyc.transform.flag_elimination import do_flag_elimination from mypyc.transform.uninit import insert_uninit_checks -files = ["opt-copy-propagation.test"] +class OptimizationSuite(MypycDataSuite): + """Base class for IR optimization test suites. + + To use this, add a base class and define "files" and "do_optimizations". + """ -class TestCopyPropagation(MypycDataSuite): - files = files base_path = test_temp_dir def run_case(self, testcase: DataDrivenTestCase) -> None: @@ -41,7 +45,24 @@ def run_case(self, testcase: DataDrivenTestCase) -> None: if fn.name == TOP_LEVEL_NAME and not testcase.name.endswith("_toplevel"): continue insert_uninit_checks(fn) - do_copy_propagation(fn, CompilerOptions()) + self.do_optimizations(fn) actual.extend(format_func(fn)) assert_test_output(testcase, actual, "Invalid source code output", expected_output) + + def do_optimizations(self, fn: FuncIR) -> None: + raise NotImplementedError + + +class TestCopyPropagation(OptimizationSuite): + files = ["opt-copy-propagation.test"] + + def do_optimizations(self, fn: FuncIR) -> None: + do_copy_propagation(fn, CompilerOptions()) + + +class TestFlagElimination(OptimizationSuite): + files = ["opt-flag-elimination.test"] + + def do_optimizations(self, fn: FuncIR) -> None: + do_flag_elimination(fn, CompilerOptions()) diff --git a/mypyc/transform/flag_elimination.py b/mypyc/transform/flag_elimination.py new file mode 100644 index 000000000000..605e5bc46ae4 --- /dev/null +++ b/mypyc/transform/flag_elimination.py @@ -0,0 +1,108 @@ +"""Bool register elimination optimization. + +Example input: + + L1: + r0 = f() + b = r0 + goto L3 + L2: + r1 = g() + b = r1 + goto L3 + L3: + if b goto L4 else goto L5 + +The register b is redundant and we replace the assignments with two copies of +the branch in L3: + + L1: + r0 = f() + if r0 goto L4 else goto L5 + L2: + r1 = g() + if r1 goto L4 else goto L5 + +This helps generate simpler IR for tagged integers comparisons, for example. +""" + +from __future__ import annotations + +from mypyc.ir.func_ir import FuncIR +from mypyc.ir.ops import Assign, BasicBlock, Branch, Goto, Register, Unreachable +from mypyc.irbuild.ll_builder import LowLevelIRBuilder +from mypyc.options import CompilerOptions +from mypyc.transform.ir_transform import IRTransform + + +def do_flag_elimination(fn: FuncIR, options: CompilerOptions) -> None: + # Find registers that are used exactly once as source, and in a branch. + counts: dict[Register, int] = {} + branches: dict[Register, Branch] = {} + labels: dict[Register, BasicBlock] = {} + for block in fn.blocks: + for i, op in enumerate(block.ops): + for src in op.sources(): + if isinstance(src, Register): + counts[src] = counts.get(src, 0) + 1 + if i == 0 and isinstance(op, Branch) and isinstance(op.value, Register): + branches[op.value] = op + labels[op.value] = block + + # Based on these we can find the candidate registers. + candidates: set[Register] = { + r for r in branches if counts.get(r, 0) == 1 and r not in fn.arg_regs + } + + # Remove candidates with invalid assignments. + for block in fn.blocks: + for i, op in enumerate(block.ops): + if isinstance(op, Assign) and op.dest in candidates: + next_op = block.ops[i + 1] + if not (isinstance(next_op, Goto) and next_op.label is labels[op.dest]): + # Not right + candidates.remove(op.dest) + + builder = LowLevelIRBuilder(None, options) + transform = FlagEliminationTransform( + builder, {x: y for x, y in branches.items() if x in candidates} + ) + transform.transform_blocks(fn.blocks) + fn.blocks = builder.blocks + + +class FlagEliminationTransform(IRTransform): + def __init__(self, builder: LowLevelIRBuilder, branch_map: dict[Register, Branch]) -> None: + super().__init__(builder) + self.branch_map = branch_map + self.branches = set(branch_map.values()) + + def visit_assign(self, op: Assign) -> None: + old_branch = self.branch_map.get(op.dest) + if old_branch: + # Replace assignment with a copy of the old branch, which is in a + # separate basic block. The old branch will be deletecd in visit_branch. + new_branch = Branch( + op.src, + old_branch.true, + old_branch.false, + old_branch.op, + old_branch.line, + rare=old_branch.rare, + ) + new_branch.negated = old_branch.negated + new_branch.traceback_entry = old_branch.traceback_entry + self.add(new_branch) + else: + self.add(op) + + def visit_goto(self, op: Goto) -> None: + # This is a no-op if basic block already terminated + self.builder.goto(op.label) + + def visit_branch(self, op: Branch) -> None: + if op in self.branches: + # This branch is optimized away + self.add(Unreachable()) + else: + self.add(op) diff --git a/mypyc/transform/ir_transform.py b/mypyc/transform/ir_transform.py index 1bcfc8fb5feb..254fe3f7771d 100644 --- a/mypyc/transform/ir_transform.py +++ b/mypyc/transform/ir_transform.py @@ -101,17 +101,17 @@ def transform_blocks(self, blocks: list[BasicBlock]) -> None: def add(self, op: Op) -> Value: return self.builder.add(op) - def visit_goto(self, op: Goto) -> Value: - return self.add(op) + def visit_goto(self, op: Goto) -> None: + self.add(op) - def visit_branch(self, op: Branch) -> Value: - return self.add(op) + def visit_branch(self, op: Branch) -> None: + self.add(op) - def visit_return(self, op: Return) -> Value: - return self.add(op) + def visit_return(self, op: Return) -> None: + self.add(op) - def visit_unreachable(self, op: Unreachable) -> Value: - return self.add(op) + def visit_unreachable(self, op: Unreachable) -> None: + self.add(op) def visit_assign(self, op: Assign) -> Value | None: return self.add(op) From 1741c16b73bac748e17e6515f65e08afa7b250c3 Mon Sep 17 00:00:00 2001 From: Jukka Lehtosalo Date: Fri, 15 Mar 2024 15:05:34 +0000 Subject: [PATCH 46/54] Use lower-case generics more consistently in error messages (#17035) Suggest `list[x]` instead of `List[x]` on Python 3.9 and later in hints. We already suggest `x | None` instead of `Optional[x]` on 3.10+, so this makes the error messages more consistent. Use lower-case `type[x]` when using `reveal_type` on Python 3.9 and later. --- mypy/messages.py | 2 ++ mypy/types.py | 6 +++++- test-data/unit/check-lowercase.test | 14 ++++++++++++++ 3 files changed, 21 insertions(+), 1 deletion(-) diff --git a/mypy/messages.py b/mypy/messages.py index 92b57ef781a2..199b7c42b11b 100644 --- a/mypy/messages.py +++ b/mypy/messages.py @@ -1779,6 +1779,8 @@ def need_annotation_for_var( alias = alias.split(".")[-1] if alias == "Dict": type_dec = f"{type_dec}, {type_dec}" + if self.options.use_lowercase_names(): + alias = alias.lower() recommended_type = f"{alias}[{type_dec}]" if recommended_type is not None: hint = f' (hint: "{node.name}: {recommended_type} = ...")' diff --git a/mypy/types.py b/mypy/types.py index d3c4df8b3b09..b4209e9debf4 100644 --- a/mypy/types.py +++ b/mypy/types.py @@ -3405,7 +3405,11 @@ def visit_ellipsis_type(self, t: EllipsisType) -> str: return "..." def visit_type_type(self, t: TypeType) -> str: - return f"Type[{t.item.accept(self)}]" + if self.options.use_lowercase_names(): + type_name = "type" + else: + type_name = "Type" + return f"{type_name}[{t.item.accept(self)}]" def visit_placeholder_type(self, t: PlaceholderType) -> str: return f"" diff --git a/test-data/unit/check-lowercase.test b/test-data/unit/check-lowercase.test index d1ebbdd282fa..ab6d68929f8e 100644 --- a/test-data/unit/check-lowercase.test +++ b/test-data/unit/check-lowercase.test @@ -49,3 +49,17 @@ x: type[type] y: int y = x # E: Incompatible types in assignment (expression has type "type[type]", variable has type "int") + +[case testLowercaseSettingOnTypeAnnotationHint] +# flags: --python-version 3.9 --no-force-uppercase-builtins +x = [] # E: Need type annotation for "x" (hint: "x: list[] = ...") +y = {} # E: Need type annotation for "y" (hint: "y: dict[, ] = ...") +z = set() # E: Need type annotation for "z" (hint: "z: set[] = ...") +[builtins fixtures/primitives.pyi] + +[case testLowercaseSettingOnRevealTypeType] +# flags: --python-version 3.9 --no-force-uppercase-builtins +def f(t: type[int]) -> None: + reveal_type(t) # N: Revealed type is "type[builtins.int]" +reveal_type(f) # N: Revealed type is "def (t: type[builtins.int])" +[builtins fixtures/primitives.pyi] From 31dc50371aaa267f258f74275b4bc07f27d70001 Mon Sep 17 00:00:00 2001 From: Hashem Date: Fri, 15 Mar 2024 11:29:48 -0400 Subject: [PATCH 47/54] attrs: Fix emulating hash method logic (#17016) This commit fixes a couple regressions in 1.9.0 from 91be285. Attrs' logic for hashability is slightly complex: * https://www.attrs.org/en/stable/hashing.html * https://github.com/python-attrs/attrs/blob/9e443b18527dc96b194e92805fa751cbf8434ba9/src/attr/_make.py#L1660-L1689 Mypy now properly emulates attrs' logic so that custom `__hash__` implementations are preserved, `@frozen` subclasses are always hashable, and classes are only made unhashable based on the values of `eq` and `unsafe_hash`. Fixes #17015 Fixes https://github.com/python/mypy/pull/16556#issuecomment-1987116488 Based on a patch in #17012 Co-Authored-By: Tin Tvrtkovic Co-authored-by: Hashem Nasarat --- mypy/plugins/attrs.py | 22 ++++- test-data/unit/check-incremental.test | 2 +- test-data/unit/check-plugin-attrs.test | 113 +++++++++++++++++++++-- test-data/unit/fixtures/plugin_attrs.pyi | 2 + 4 files changed, 125 insertions(+), 14 deletions(-) diff --git a/mypy/plugins/attrs.py b/mypy/plugins/attrs.py index 345ea822ed94..83f685f57a16 100644 --- a/mypy/plugins/attrs.py +++ b/mypy/plugins/attrs.py @@ -325,9 +325,6 @@ def attr_class_maker_callback( frozen = _get_frozen(ctx, frozen_default) order = _determine_eq_order(ctx) slots = _get_decorator_bool_argument(ctx, "slots", slots_default) - hashable = _get_decorator_bool_argument(ctx, "hash", False) or _get_decorator_bool_argument( - ctx, "unsafe_hash", False - ) auto_attribs = _get_decorator_optional_bool_argument(ctx, "auto_attribs", auto_attribs_default) kw_only = _get_decorator_bool_argument(ctx, "kw_only", False) @@ -371,7 +368,24 @@ def attr_class_maker_callback( _add_order(ctx, adder) if frozen: _make_frozen(ctx, attributes) - elif not hashable: + # Frozen classes are hashable by default, even if inheriting from non-frozen ones. + hashable: bool | None = _get_decorator_bool_argument( + ctx, "hash", True + ) and _get_decorator_bool_argument(ctx, "unsafe_hash", True) + else: + hashable = _get_decorator_optional_bool_argument(ctx, "unsafe_hash") + if hashable is None: # unspecified + hashable = _get_decorator_optional_bool_argument(ctx, "hash") + + eq = _get_decorator_optional_bool_argument(ctx, "eq") + has_own_hash = "__hash__" in ctx.cls.info.names + + if has_own_hash or (hashable is None and eq is False): + pass # Do nothing. + elif hashable: + # We copy the `__hash__` signature from `object` to make them hashable. + ctx.cls.info.names["__hash__"] = ctx.cls.info.mro[-1].names["__hash__"] + else: _remove_hashability(ctx) return True diff --git a/test-data/unit/check-incremental.test b/test-data/unit/check-incremental.test index 42faa8c627ba..a7f4fafc579e 100644 --- a/test-data/unit/check-incremental.test +++ b/test-data/unit/check-incremental.test @@ -3015,7 +3015,7 @@ class NoInit: class NoCmp: x: int -[builtins fixtures/list.pyi] +[builtins fixtures/plugin_attrs.pyi] [rechecked] [stale] [out1] diff --git a/test-data/unit/check-plugin-attrs.test b/test-data/unit/check-plugin-attrs.test index 0f379724553a..39b266dba50e 100644 --- a/test-data/unit/check-plugin-attrs.test +++ b/test-data/unit/check-plugin-attrs.test @@ -360,7 +360,8 @@ class A: a = A(5) a.a = 16 # E: Property "a" defined in "A" is read-only -[builtins fixtures/bool.pyi] +[builtins fixtures/plugin_attrs.pyi] + [case testAttrsNextGenFrozen] from attr import frozen, field @@ -370,7 +371,7 @@ class A: a = A(5) a.a = 16 # E: Property "a" defined in "A" is read-only -[builtins fixtures/bool.pyi] +[builtins fixtures/plugin_attrs.pyi] [case testAttrsNextGenDetect] from attr import define, field @@ -420,7 +421,7 @@ reveal_type(A) # N: Revealed type is "def (a: builtins.int, b: builtins.bool) - reveal_type(B) # N: Revealed type is "def (a: builtins.bool, b: builtins.int) -> __main__.B" reveal_type(C) # N: Revealed type is "def (a: builtins.int) -> __main__.C" -[builtins fixtures/bool.pyi] +[builtins fixtures/plugin_attrs.pyi] [case testAttrsDataClass] import attr @@ -1155,7 +1156,7 @@ c = NonFrozenFrozen(1, 2) c.a = 17 # E: Property "a" defined in "NonFrozenFrozen" is read-only c.b = 17 # E: Property "b" defined in "NonFrozenFrozen" is read-only -[builtins fixtures/bool.pyi] +[builtins fixtures/plugin_attrs.pyi] [case testAttrsCallableAttributes] from typing import Callable import attr @@ -1178,7 +1179,7 @@ class G: class FFrozen(F): def bar(self) -> bool: return self._cb(5, 6) -[builtins fixtures/callable.pyi] +[builtins fixtures/plugin_attrs.pyi] [case testAttrsWithFactory] from typing import List @@ -1450,7 +1451,7 @@ class C: total = attr.ib(type=Bad) # E: Name "Bad" is not defined C(0).total = 1 # E: Property "total" defined in "C" is read-only -[builtins fixtures/bool.pyi] +[builtins fixtures/plugin_attrs.pyi] [case testTypeInAttrDeferredStar] import lib @@ -1941,7 +1942,7 @@ class C: default=None, converter=default_if_none(factory=dict) \ # E: Unsupported converter, only named functions, types and lambdas are currently supported ) -[builtins fixtures/dict.pyi] +[builtins fixtures/plugin_attrs.pyi] [case testAttrsUnannotatedConverter] import attr @@ -2012,7 +2013,7 @@ class Sub(Base): @property def name(self) -> str: ... -[builtins fixtures/property.pyi] +[builtins fixtures/plugin_attrs.pyi] [case testOverrideWithPropertyInFrozenClassChecked] from attrs import frozen @@ -2035,7 +2036,7 @@ class Sub(Base): # This matches runtime semantics reveal_type(Sub) # N: Revealed type is "def (*, name: builtins.str, first_name: builtins.str, last_name: builtins.str) -> __main__.Sub" -[builtins fixtures/property.pyi] +[builtins fixtures/plugin_attrs.pyi] [case testFinalInstanceAttribute] from attrs import define @@ -2380,3 +2381,97 @@ class B(A): reveal_type(B.__hash__) # N: Revealed type is "None" [builtins fixtures/plugin_attrs.pyi] + +[case testManualOwnHashability] +from attrs import define, frozen + +@define +class A: + a: int + def __hash__(self) -> int: + ... + +reveal_type(A.__hash__) # N: Revealed type is "def (self: __main__.A) -> builtins.int" + +[builtins fixtures/plugin_attrs.pyi] + +[case testSubclassDefaultLosesHashability] +from attrs import define, frozen + +@define +class A: + a: int + def __hash__(self) -> int: + ... + +@define +class B(A): + pass + +reveal_type(B.__hash__) # N: Revealed type is "None" + +[builtins fixtures/plugin_attrs.pyi] + +[case testSubclassEqFalseKeepsHashability] +from attrs import define, frozen + +@define +class A: + a: int + def __hash__(self) -> int: + ... + +@define(eq=False) +class B(A): + pass + +reveal_type(B.__hash__) # N: Revealed type is "def (self: __main__.A) -> builtins.int" + +[builtins fixtures/plugin_attrs.pyi] + +[case testSubclassingFrozenHashability] +from attrs import define, frozen + +@define +class A: + a: int + +@frozen +class B(A): + pass + +reveal_type(B.__hash__) # N: Revealed type is "def (self: builtins.object) -> builtins.int" + +[builtins fixtures/plugin_attrs.pyi] + +[case testSubclassingFrozenHashOffHashability] +from attrs import define, frozen + +@define +class A: + a: int + def __hash__(self) -> int: + ... + +@frozen(unsafe_hash=False) +class B(A): + pass + +reveal_type(B.__hash__) # N: Revealed type is "None" + +[builtins fixtures/plugin_attrs.pyi] + +[case testUnsafeHashPrecedence] +from attrs import define, frozen + +@define(unsafe_hash=True, hash=False) +class A: + pass +reveal_type(A.__hash__) # N: Revealed type is "def (self: builtins.object) -> builtins.int" + +@define(unsafe_hash=False, hash=True) +class B: + pass +reveal_type(B.__hash__) # N: Revealed type is "None" + +[builtins fixtures/plugin_attrs.pyi] diff --git a/test-data/unit/fixtures/plugin_attrs.pyi b/test-data/unit/fixtures/plugin_attrs.pyi index 5b87c47b5bc8..7fd641727253 100644 --- a/test-data/unit/fixtures/plugin_attrs.pyi +++ b/test-data/unit/fixtures/plugin_attrs.pyi @@ -35,3 +35,5 @@ class tuple(Sequence[Tco], Generic[Tco]): def __iter__(self) -> Iterator[Tco]: pass def __contains__(self, item: object) -> bool: pass def __getitem__(self, x: int) -> Tco: pass + +property = object() # Dummy definition From c591c891f7c5c35c3546ae6b4709ee97ef9e1136 Mon Sep 17 00:00:00 2001 From: Jukka Lehtosalo Date: Sat, 16 Mar 2024 12:54:54 +0000 Subject: [PATCH 48/54] [mypyc] Implement lowering pass and add primitives for int (in)equality (#17027) Add a new `PrimitiveOp` op which can be transformed into lower-level ops in a lowering pass after reference counting op insertion pass. Higher-level ops in IR make it easier to implement various optimizations, and the output of irbuild test cases will be more compact and readable. Implement the lowering pass. Currently it's pretty minimal, and I will add additional primitives and the direct transformation of various primitives to `CallC` ops in follow-up PRs. Currently primitives that map to C calls generate `CallC` ops in the main irbuild pass, but the long-term goal is to only/mostly generate `PrimitiveOp`s instead of `CallC` ops during the main irbuild pass. Also implement primitives for tagged integer equality and inequality as examples. Lowering of primitives is implemented using decorated handler functions in `mypyc.lower` that are found based on the name of the primitive. The name has no other significance, though it's also used in pretty-printed IR output. Work on mypyc/mypyc#854. The issue describes the motivation in more detail. --- mypyc/analysis/dataflow.py | 4 + mypyc/analysis/ircheck.py | 4 + mypyc/analysis/selfleaks.py | 4 + mypyc/codegen/emitfunc.py | 6 + mypyc/codegen/emitmodule.py | 10 +- mypyc/ir/ops.py | 79 ++++++++- mypyc/ir/pprint.py | 17 ++ mypyc/irbuild/ast_helpers.py | 7 +- mypyc/irbuild/expression.py | 4 +- mypyc/irbuild/ll_builder.py | 126 +++++++++++-- mypyc/lower/__init__.py | 0 mypyc/lower/int_ops.py | 15 ++ mypyc/lower/registry.py | 26 +++ mypyc/primitives/int_ops.py | 25 ++- mypyc/primitives/registry.py | 40 +++-- mypyc/test-data/analysis.test | 70 +++----- mypyc/test-data/irbuild-basic.test | 206 +++++++--------------- mypyc/test-data/irbuild-bool.test | 6 +- mypyc/test-data/irbuild-classes.test | 2 +- mypyc/test-data/irbuild-int.test | 28 +-- mypyc/test-data/irbuild-match.test | 45 +++-- mypyc/test-data/irbuild-nested.test | 4 +- mypyc/test-data/irbuild-optional.test | 2 +- mypyc/test-data/irbuild-tuple.test | 87 ++------- mypyc/test-data/lowering-int.test | 126 +++++++++++++ mypyc/test-data/opt-flag-elimination.test | 18 +- mypyc/test-data/refcount.test | 172 ++++++------------ mypyc/test/test_cheader.py | 16 +- mypyc/test/test_emitfunc.py | 2 + mypyc/test/test_lowering.py | 54 ++++++ mypyc/transform/ir_transform.py | 17 +- mypyc/transform/lower.py | 33 ++++ 32 files changed, 772 insertions(+), 483 deletions(-) create mode 100644 mypyc/lower/__init__.py create mode 100644 mypyc/lower/int_ops.py create mode 100644 mypyc/lower/registry.py create mode 100644 mypyc/test-data/lowering-int.test create mode 100644 mypyc/test/test_lowering.py create mode 100644 mypyc/transform/lower.py diff --git a/mypyc/analysis/dataflow.py b/mypyc/analysis/dataflow.py index 57ad2b17fcc5..9babf860fb31 100644 --- a/mypyc/analysis/dataflow.py +++ b/mypyc/analysis/dataflow.py @@ -38,6 +38,7 @@ MethodCall, Op, OpVisitor, + PrimitiveOp, RaiseStandardError, RegisterOp, Return, @@ -234,6 +235,9 @@ def visit_raise_standard_error(self, op: RaiseStandardError) -> GenAndKill[T]: def visit_call_c(self, op: CallC) -> GenAndKill[T]: return self.visit_register_op(op) + def visit_primitive_op(self, op: PrimitiveOp) -> GenAndKill[T]: + return self.visit_register_op(op) + def visit_truncate(self, op: Truncate) -> GenAndKill[T]: return self.visit_register_op(op) diff --git a/mypyc/analysis/ircheck.py b/mypyc/analysis/ircheck.py index 127047e02ff5..88737ac208de 100644 --- a/mypyc/analysis/ircheck.py +++ b/mypyc/analysis/ircheck.py @@ -37,6 +37,7 @@ MethodCall, Op, OpVisitor, + PrimitiveOp, RaiseStandardError, Register, Return, @@ -381,6 +382,9 @@ def visit_raise_standard_error(self, op: RaiseStandardError) -> None: def visit_call_c(self, op: CallC) -> None: pass + def visit_primitive_op(self, op: PrimitiveOp) -> None: + pass + def visit_truncate(self, op: Truncate) -> None: pass diff --git a/mypyc/analysis/selfleaks.py b/mypyc/analysis/selfleaks.py index 80c2bc348bc2..5d89a9bfc7c6 100644 --- a/mypyc/analysis/selfleaks.py +++ b/mypyc/analysis/selfleaks.py @@ -31,6 +31,7 @@ LoadStatic, MethodCall, OpVisitor, + PrimitiveOp, RaiseStandardError, Register, RegisterOp, @@ -149,6 +150,9 @@ def visit_raise_standard_error(self, op: RaiseStandardError) -> GenAndKill: def visit_call_c(self, op: CallC) -> GenAndKill: return self.check_register_op(op) + def visit_primitive_op(self, op: PrimitiveOp) -> GenAndKill: + return self.check_register_op(op) + def visit_truncate(self, op: Truncate) -> GenAndKill: return CLEAN diff --git a/mypyc/codegen/emitfunc.py b/mypyc/codegen/emitfunc.py index c08f1f840fa4..12f57b9cee6f 100644 --- a/mypyc/codegen/emitfunc.py +++ b/mypyc/codegen/emitfunc.py @@ -47,6 +47,7 @@ MethodCall, Op, OpVisitor, + PrimitiveOp, RaiseStandardError, Register, Return, @@ -629,6 +630,11 @@ def visit_call_c(self, op: CallC) -> None: args = ", ".join(self.reg(arg) for arg in op.args) self.emitter.emit_line(f"{dest}{op.function_name}({args});") + def visit_primitive_op(self, op: PrimitiveOp) -> None: + raise RuntimeError( + f"unexpected PrimitiveOp {op.desc.name}: they must be lowered before codegen" + ) + def visit_truncate(self, op: Truncate) -> None: dest = self.reg(op) value = self.reg(op.src) diff --git a/mypyc/codegen/emitmodule.py b/mypyc/codegen/emitmodule.py index 9466bc2cea79..6c8f5ac91335 100644 --- a/mypyc/codegen/emitmodule.py +++ b/mypyc/codegen/emitmodule.py @@ -59,6 +59,7 @@ from mypyc.transform.copy_propagation import do_copy_propagation from mypyc.transform.exceptions import insert_exception_handling from mypyc.transform.flag_elimination import do_flag_elimination +from mypyc.transform.lower import lower_ir from mypyc.transform.refcount import insert_ref_count_opcodes from mypyc.transform.uninit import insert_uninit_checks @@ -235,6 +236,8 @@ def compile_scc_to_ir( insert_exception_handling(fn) # Insert refcount handling. insert_ref_count_opcodes(fn) + # Switch to lower abstraction level IR. + lower_ir(fn, compiler_options) # Perform optimizations. do_copy_propagation(fn, compiler_options) do_flag_elimination(fn, compiler_options) @@ -423,10 +426,11 @@ def compile_modules_to_c( ) modules = compile_modules_to_ir(result, mapper, compiler_options, errors) - ctext = compile_ir_to_c(groups, modules, result, mapper, compiler_options) + if errors.num_errors > 0: + return {}, [] - if errors.num_errors == 0: - write_cache(modules, result, group_map, ctext) + ctext = compile_ir_to_c(groups, modules, result, mapper, compiler_options) + write_cache(modules, result, group_map, ctext) return modules, [ctext[name] for _, name in groups] diff --git a/mypyc/ir/ops.py b/mypyc/ir/ops.py index 04c50d1e2841..3acfb0933e5a 100644 --- a/mypyc/ir/ops.py +++ b/mypyc/ir/ops.py @@ -576,6 +576,78 @@ def accept(self, visitor: OpVisitor[T]) -> T: return visitor.visit_method_call(self) +class PrimitiveDescription: + """Description of a primitive op. + + Primitives get lowered into lower-level ops before code generation. + + If c_function_name is provided, a primitive will be lowered into a CallC op. + Otherwise custom logic will need to be implemented to transform the + primitive into lower-level ops. + """ + + def __init__( + self, + name: str, + arg_types: list[RType], + return_type: RType, # TODO: What about generic? + var_arg_type: RType | None, + truncated_type: RType | None, + c_function_name: str | None, + error_kind: int, + steals: StealsDescription, + is_borrowed: bool, + ordering: list[int] | None, + extra_int_constants: list[tuple[int, RType]], + priority: int, + ) -> None: + # Each primitive much have a distinct name, but otherwise they are arbitrary. + self.name: Final = name + self.arg_types: Final = arg_types + self.return_type: Final = return_type + self.var_arg_type: Final = var_arg_type + self.truncated_type: Final = truncated_type + # If non-None, this will map to a call of a C helper function; if None, + # there must be a custom handler function that gets invoked during the lowering + # pass to generate low-level IR for the primitive (in the mypyc.lower package) + self.c_function_name: Final = c_function_name + self.error_kind: Final = error_kind + self.steals: Final = steals + self.is_borrowed: Final = is_borrowed + self.ordering: Final = ordering + self.extra_int_constants: Final = extra_int_constants + self.priority: Final = priority + + def __repr__(self) -> str: + return f"" + + +class PrimitiveOp(RegisterOp): + """A higher-level primitive operation. + + Some of these have special compiler support. These will be lowered + (transformed) into lower-level IR ops before code generation, and after + reference counting op insertion. Others will be transformed into CallC + ops. + + Tagged integer equality is a typical primitive op with non-trivial + lowering. It gets transformed into a tag check, followed by different + code paths for short and long representations. + """ + + def __init__(self, args: list[Value], desc: PrimitiveDescription, line: int = -1) -> None: + self.args = args + self.type = desc.return_type + self.error_kind = desc.error_kind + self.desc = desc + + def sources(self) -> list[Value]: + return self.args + + def accept(self, visitor: OpVisitor[T]) -> T: + return visitor.visit_primitive_op(self) + + class LoadErrorValue(RegisterOp): """Load an error value. @@ -1446,7 +1518,8 @@ class Unborrow(RegisterOp): error_kind = ERR_NEVER - def __init__(self, src: Value) -> None: + def __init__(self, src: Value, line: int = -1) -> None: + super().__init__(line) assert src.is_borrowed self.src = src self.type = src.type @@ -1555,6 +1628,10 @@ def visit_raise_standard_error(self, op: RaiseStandardError) -> T: def visit_call_c(self, op: CallC) -> T: raise NotImplementedError + @abstractmethod + def visit_primitive_op(self, op: PrimitiveOp) -> T: + raise NotImplementedError + @abstractmethod def visit_truncate(self, op: Truncate) -> T: raise NotImplementedError diff --git a/mypyc/ir/pprint.py b/mypyc/ir/pprint.py index 5578049256f1..8d6723917ea0 100644 --- a/mypyc/ir/pprint.py +++ b/mypyc/ir/pprint.py @@ -43,6 +43,7 @@ MethodCall, Op, OpVisitor, + PrimitiveOp, RaiseStandardError, Register, Return, @@ -217,6 +218,22 @@ def visit_call_c(self, op: CallC) -> str: else: return self.format("%r = %s(%s)", op, op.function_name, args_str) + def visit_primitive_op(self, op: PrimitiveOp) -> str: + args = [] + arg_index = 0 + type_arg_index = 0 + for arg_type in zip(op.desc.arg_types): + if arg_type: + args.append(self.format("%r", op.args[arg_index])) + arg_index += 1 + else: + assert op.type_args + args.append(self.format("%r", op.type_args[type_arg_index])) + type_arg_index += 1 + + args_str = ", ".join(args) + return self.format("%r = %s %s ", op, op.desc.name, args_str) + def visit_truncate(self, op: Truncate) -> str: return self.format("%r = truncate %r: %t to %t", op, op.src, op.src_type, op.type) diff --git a/mypyc/irbuild/ast_helpers.py b/mypyc/irbuild/ast_helpers.py index 1af1ad611a89..8490eaa03477 100644 --- a/mypyc/irbuild/ast_helpers.py +++ b/mypyc/irbuild/ast_helpers.py @@ -93,7 +93,12 @@ def maybe_process_conditional_comparison( self.add_bool_branch(reg, true, false) else: # "left op right" for two tagged integers - self.builder.compare_tagged_condition(left, right, op, true, false, e.line) + if op in ("==", "!="): + reg = self.builder.binary_op(left, right, op, e.line) + self.flush_keep_alives() + self.add_bool_branch(reg, true, false) + else: + self.builder.compare_tagged_condition(left, right, op, true, false, e.line) return True diff --git a/mypyc/irbuild/expression.py b/mypyc/irbuild/expression.py index 81e37953809f..021b7a1dbe90 100644 --- a/mypyc/irbuild/expression.py +++ b/mypyc/irbuild/expression.py @@ -756,7 +756,7 @@ def transform_comparison_expr(builder: IRBuilder, e: ComparisonExpr) -> Value: set_literal = precompute_set_literal(builder, e.operands[1]) if set_literal is not None: lhs = e.operands[0] - result = builder.builder.call_c( + result = builder.builder.primitive_op( set_in_op, [builder.accept(lhs), set_literal], e.line, bool_rprimitive ) if first_op == "not in": @@ -778,7 +778,7 @@ def transform_comparison_expr(builder: IRBuilder, e: ComparisonExpr) -> Value: borrow_left = is_borrow_friendly_expr(builder, right_expr) left = builder.accept(left_expr, can_borrow=borrow_left) right = builder.accept(right_expr, can_borrow=True) - return builder.compare_tagged(left, right, first_op, e.line) + return builder.binary_op(left, right, first_op, e.line) # TODO: Don't produce an expression when used in conditional context # All of the trickiness here is due to support for chained conditionals diff --git a/mypyc/irbuild/ll_builder.py b/mypyc/irbuild/ll_builder.py index 45c06e11befd..f9bacb43bc3e 100644 --- a/mypyc/irbuild/ll_builder.py +++ b/mypyc/irbuild/ll_builder.py @@ -63,6 +63,8 @@ LoadStatic, MethodCall, Op, + PrimitiveDescription, + PrimitiveOp, RaiseStandardError, Register, SetMem, @@ -1313,7 +1315,12 @@ def binary_op(self, lreg: Value, rreg: Value, op: str, line: int) -> Value: return self.compare_strings(lreg, rreg, op, line) if is_bytes_rprimitive(ltype) and is_bytes_rprimitive(rtype) and op in ("==", "!="): return self.compare_bytes(lreg, rreg, op, line) - if is_tagged(ltype) and is_tagged(rtype) and op in int_comparison_op_mapping: + if ( + is_tagged(ltype) + and is_tagged(rtype) + and op in int_comparison_op_mapping + and op not in ("==", "!=") + ): return self.compare_tagged(lreg, rreg, op, line) if is_bool_rprimitive(ltype) and is_bool_rprimitive(rtype) and op in BOOL_BINARY_OPS: if op in ComparisonOp.signed_ops: @@ -1379,13 +1386,7 @@ def binary_op(self, lreg: Value, rreg: Value, op: str, line: int) -> Value: # Mixed int comparisons if op in ("==", "!="): - op_id = ComparisonOp.signed_ops[op] - if is_tagged(ltype) and is_subtype(rtype, ltype): - rreg = self.coerce(rreg, int_rprimitive, line) - return self.comparison_op(lreg, rreg, op_id, line) - if is_tagged(rtype) and is_subtype(ltype, rtype): - lreg = self.coerce(lreg, int_rprimitive, line) - return self.comparison_op(lreg, rreg, op_id, line) + pass # TODO: Do we need anything here? elif op in op in int_comparison_op_mapping: if is_tagged(ltype) and is_subtype(rtype, ltype): rreg = self.coerce(rreg, short_int_rprimitive, line) @@ -1412,8 +1413,8 @@ def binary_op(self, lreg: Value, rreg: Value, op: str, line: int) -> Value: if base_op in float_op_to_id: return self.float_op(lreg, rreg, base_op, line) - call_c_ops_candidates = binary_ops.get(op, []) - target = self.matching_call_c(call_c_ops_candidates, [lreg, rreg], line) + primitive_ops_candidates = binary_ops.get(op, []) + target = self.matching_primitive_op(primitive_ops_candidates, [lreg, rreg], line) assert target, "Unsupported binary operation: %s" % op return target @@ -1432,7 +1433,14 @@ def check_tagged_short_int(self, val: Value, line: int, negated: bool = False) - def compare_tagged(self, lhs: Value, rhs: Value, op: str, line: int) -> Value: """Compare two tagged integers using given operator (value context).""" # generate fast binary logic ops on short ints - if is_short_int_rprimitive(lhs.type) and is_short_int_rprimitive(rhs.type): + if (is_short_int_rprimitive(lhs.type) or is_short_int_rprimitive(rhs.type)) and op in ( + "==", + "!=", + ): + quick = True + else: + quick = is_short_int_rprimitive(lhs.type) and is_short_int_rprimitive(rhs.type) + if quick: return self.comparison_op(lhs, rhs, int_comparison_op_mapping[op][0], line) op_type, c_func_desc, negate_result, swap_op = int_comparison_op_mapping[op] result = Register(bool_rprimitive) @@ -1986,6 +1994,102 @@ def matching_call_c( return target return None + def primitive_op( + self, + desc: PrimitiveDescription, + args: list[Value], + line: int, + result_type: RType | None = None, + ) -> Value: + """Add a primitive op.""" + # Does this primitive map into calling a Python C API + # or an internal mypyc C API function? + if desc.c_function_name: + # TODO: Generate PrimitiOps here and transform them into CallC + # ops only later in the lowering pass + c_desc = CFunctionDescription( + desc.name, + desc.arg_types, + desc.return_type, + desc.var_arg_type, + desc.truncated_type, + desc.c_function_name, + desc.error_kind, + desc.steals, + desc.is_borrowed, + desc.ordering, + desc.extra_int_constants, + desc.priority, + ) + return self.call_c(c_desc, args, line, result_type) + + # This primitve gets transformed in a lowering pass to + # lower-level IR ops using a custom transform function. + + coerced = [] + # Coerce fixed number arguments + for i in range(min(len(args), len(desc.arg_types))): + formal_type = desc.arg_types[i] + arg = args[i] + assert formal_type is not None # TODO + arg = self.coerce(arg, formal_type, line) + coerced.append(arg) + assert desc.ordering is None + assert desc.var_arg_type is None + assert not desc.extra_int_constants + target = self.add(PrimitiveOp(coerced, desc, line=line)) + if desc.is_borrowed: + # If the result is borrowed, force the arguments to be + # kept alive afterwards, as otherwise the result might be + # immediately freed, at the risk of a dangling pointer. + for arg in coerced: + if not isinstance(arg, (Integer, LoadLiteral)): + self.keep_alives.append(arg) + if desc.error_kind == ERR_NEG_INT: + comp = ComparisonOp(target, Integer(0, desc.return_type, line), ComparisonOp.SGE, line) + comp.error_kind = ERR_FALSE + self.add(comp) + + assert desc.truncated_type is None + result = target + if result_type and not is_runtime_subtype(result.type, result_type): + if is_none_rprimitive(result_type): + # Special case None return. The actual result may actually be a bool + # and so we can't just coerce it. + result = self.none() + else: + result = self.coerce(result, result_type, line, can_borrow=desc.is_borrowed) + return result + + def matching_primitive_op( + self, + candidates: list[PrimitiveDescription], + args: list[Value], + line: int, + result_type: RType | None = None, + can_borrow: bool = False, + ) -> Value | None: + matching: PrimitiveDescription | None = None + for desc in candidates: + if len(desc.arg_types) != len(args): + continue + if all( + # formal is not None and # TODO + is_subtype(actual.type, formal) + for actual, formal in zip(args, desc.arg_types) + ) and (not desc.is_borrowed or can_borrow): + if matching: + assert matching.priority != desc.priority, "Ambiguous:\n1) {}\n2) {}".format( + matching, desc + ) + if desc.priority > matching.priority: + matching = desc + else: + matching = desc + if matching: + return self.primitive_op(matching, args, line=line) + return None + def int_op(self, type: RType, lhs: Value, rhs: Value, op: int, line: int = -1) -> Value: """Generate a native integer binary op. diff --git a/mypyc/lower/__init__.py b/mypyc/lower/__init__.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/mypyc/lower/int_ops.py b/mypyc/lower/int_ops.py new file mode 100644 index 000000000000..40fba7af4f4d --- /dev/null +++ b/mypyc/lower/int_ops.py @@ -0,0 +1,15 @@ +from __future__ import annotations + +from mypyc.ir.ops import Value +from mypyc.irbuild.ll_builder import LowLevelIRBuilder +from mypyc.lower.registry import lower_binary_op + + +@lower_binary_op("int_eq") +def lower_int_eq(builder: LowLevelIRBuilder, args: list[Value], line: int) -> Value: + return builder.compare_tagged(args[0], args[1], "==", line) + + +@lower_binary_op("int_ne") +def lower_int_ne(builder: LowLevelIRBuilder, args: list[Value], line: int) -> Value: + return builder.compare_tagged(args[0], args[1], "!=", line) diff --git a/mypyc/lower/registry.py b/mypyc/lower/registry.py new file mode 100644 index 000000000000..cc53eb93f4dd --- /dev/null +++ b/mypyc/lower/registry.py @@ -0,0 +1,26 @@ +from __future__ import annotations + +from typing import Callable, Final, List + +from mypyc.ir.ops import Value +from mypyc.irbuild.ll_builder import LowLevelIRBuilder + +LowerFunc = Callable[[LowLevelIRBuilder, List[Value], int], Value] + + +lowering_registry: Final[dict[str, LowerFunc]] = {} + + +def lower_binary_op(name: str) -> Callable[[LowerFunc], LowerFunc]: + """Register a handler that generates low-level IR for a primitive binary op.""" + + def wrapper(f: LowerFunc) -> LowerFunc: + assert name not in lowering_registry + lowering_registry[name] = f + return f + + return wrapper + + +# Import various modules that set up global state. +import mypyc.lower.int_ops # noqa: F401 diff --git a/mypyc/primitives/int_ops.py b/mypyc/primitives/int_ops.py index 95f9cc5ff43f..4103fe349a74 100644 --- a/mypyc/primitives/int_ops.py +++ b/mypyc/primitives/int_ops.py @@ -12,7 +12,14 @@ from typing import NamedTuple -from mypyc.ir.ops import ERR_ALWAYS, ERR_MAGIC, ERR_MAGIC_OVERLAPPING, ERR_NEVER, ComparisonOp +from mypyc.ir.ops import ( + ERR_ALWAYS, + ERR_MAGIC, + ERR_MAGIC_OVERLAPPING, + ERR_NEVER, + ComparisonOp, + PrimitiveDescription, +) from mypyc.ir.rtypes import ( RType, bit_rprimitive, @@ -101,6 +108,22 @@ ) +def int_binary_primitive( + op: str, primitive_name: str, return_type: RType = int_rprimitive, error_kind: int = ERR_NEVER +) -> PrimitiveDescription: + return binary_op( + name=op, + arg_types=[int_rprimitive, int_rprimitive], + return_type=return_type, + primitive_name=primitive_name, + error_kind=error_kind, + ) + + +int_eq = int_binary_primitive(op="==", primitive_name="int_eq", return_type=bit_rprimitive) +int_ne = int_binary_primitive(op="!=", primitive_name="int_ne", return_type=bit_rprimitive) + + def int_binary_op( name: str, c_function_name: str, diff --git a/mypyc/primitives/registry.py b/mypyc/primitives/registry.py index 11fca7dc2c70..d4768b4df532 100644 --- a/mypyc/primitives/registry.py +++ b/mypyc/primitives/registry.py @@ -39,7 +39,7 @@ from typing import Final, NamedTuple -from mypyc.ir.ops import StealsDescription +from mypyc.ir.ops import PrimitiveDescription, StealsDescription from mypyc.ir.rtypes import RType # Error kind for functions that return negative integer on exception. This @@ -76,7 +76,7 @@ class LoadAddressDescription(NamedTuple): function_ops: dict[str, list[CFunctionDescription]] = {} # CallC op for binary ops -binary_ops: dict[str, list[CFunctionDescription]] = {} +binary_ops: dict[str, list[PrimitiveDescription]] = {} # CallC op for unary ops unary_ops: dict[str, list[CFunctionDescription]] = {} @@ -192,8 +192,9 @@ def binary_op( name: str, arg_types: list[RType], return_type: RType, - c_function_name: str, error_kind: int, + c_function_name: str | None = None, + primitive_name: str | None = None, var_arg_type: RType | None = None, truncated_type: RType | None = None, ordering: list[int] | None = None, @@ -201,7 +202,7 @@ def binary_op( steals: StealsDescription = False, is_borrowed: bool = False, priority: int = 1, -) -> CFunctionDescription: +) -> PrimitiveDescription: """Define a c function call op for a binary operation. This will be automatically generated by matching against the AST. @@ -209,22 +210,24 @@ def binary_op( Most arguments are similar to method_op(), but exactly two argument types are expected. """ + assert c_function_name is not None or primitive_name is not None + assert not (c_function_name is not None and primitive_name is not None) if extra_int_constants is None: extra_int_constants = [] ops = binary_ops.setdefault(name, []) - desc = CFunctionDescription( - name, - arg_types, - return_type, - var_arg_type, - truncated_type, - c_function_name, - error_kind, - steals, - is_borrowed, - ordering, - extra_int_constants, - priority, + desc = PrimitiveDescription( + name=primitive_name or name, + arg_types=arg_types, + return_type=return_type, + var_arg_type=var_arg_type, + truncated_type=truncated_type, + c_function_name=c_function_name, + error_kind=error_kind, + steals=steals, + is_borrowed=is_borrowed, + ordering=ordering, + extra_int_constants=extra_int_constants, + priority=priority, ) ops.append(desc) return desc @@ -311,11 +314,10 @@ def load_address_op(name: str, type: RType, src: str) -> LoadAddressDescription: return LoadAddressDescription(name, type, src) +# Import various modules that set up global state. import mypyc.primitives.bytes_ops import mypyc.primitives.dict_ops import mypyc.primitives.float_ops - -# Import various modules that set up global state. import mypyc.primitives.int_ops import mypyc.primitives.list_ops import mypyc.primitives.misc_ops diff --git a/mypyc/test-data/analysis.test b/mypyc/test-data/analysis.test index efd219cc222a..8e067aed4d79 100644 --- a/mypyc/test-data/analysis.test +++ b/mypyc/test-data/analysis.test @@ -10,40 +10,27 @@ def f(a: int) -> None: [out] def f(a): a, x :: int - r0 :: native_int - r1, r2, r3 :: bit + r0 :: bit y, z :: int L0: x = 2 - r0 = x & 1 - r1 = r0 != 0 - if r1 goto L1 else goto L2 :: bool + r0 = int_eq x, a + if r0 goto L1 else goto L2 :: bool L1: - r2 = CPyTagged_IsEq_(x, a) - if r2 goto L3 else goto L4 :: bool -L2: - r3 = x == a - if r3 goto L3 else goto L4 :: bool -L3: y = 2 - goto L5 -L4: + goto L3 +L2: z = 2 -L5: +L3: return 1 (0, 0) {a} {a, x} (0, 1) {a, x} {a, x} (0, 2) {a, x} {a, x} -(0, 3) {a, x} {a, x} -(1, 0) {a, x} {a, x} -(1, 1) {a, x} {a, x} -(2, 0) {a, x} {a, x} -(2, 1) {a, x} {a, x} -(3, 0) {a, x} {a, x, y} -(3, 1) {a, x, y} {a, x, y} -(4, 0) {a, x} {a, x, z} -(4, 1) {a, x, z} {a, x, z} -(5, 0) {a, x, y, z} {a, x, y, z} +(1, 0) {a, x} {a, x, y} +(1, 1) {a, x, y} {a, x, y} +(2, 0) {a, x} {a, x, z} +(2, 1) {a, x, z} {a, x, z} +(3, 0) {a, x, y, z} {a, x, y, z} [case testSimple_Liveness] def f(a: int) -> int: @@ -58,7 +45,7 @@ def f(a): r0 :: bit L0: x = 2 - r0 = x == 2 + r0 = int_eq x, 2 if r0 goto L1 else goto L2 :: bool L1: return a @@ -124,7 +111,7 @@ def f(a): r0 :: bit y, x :: int L0: - r0 = a == 2 + r0 = int_eq a, 2 if r0 goto L1 else goto L2 :: bool L1: y = 2 @@ -421,40 +408,27 @@ def f(a: int) -> int: [out] def f(a): a :: int - r0 :: native_int - r1, r2, r3 :: bit + r0 :: bit x :: int L0: - r0 = a & 1 - r1 = r0 != 0 - if r1 goto L1 else goto L2 :: bool + r0 = int_eq a, a + if r0 goto L1 else goto L2 :: bool L1: - r2 = CPyTagged_IsEq_(a, a) - if r2 goto L3 else goto L4 :: bool -L2: - r3 = a == a - if r3 goto L3 else goto L4 :: bool -L3: x = 4 a = 2 - goto L5 -L4: + goto L3 +L2: x = 2 -L5: +L3: return x (0, 0) {a} {a} (0, 1) {a} {a} -(0, 2) {a} {a} (1, 0) {a} {a} -(1, 1) {a} {a} +(1, 1) {a} {} +(1, 2) {} {} (2, 0) {a} {a} (2, 1) {a} {a} -(3, 0) {a} {a} -(3, 1) {a} {} -(3, 2) {} {} -(4, 0) {a} {a} -(4, 1) {a} {a} -(5, 0) {} {} +(3, 0) {} {} [case testLoop_BorrowedArgument] def f(a: int) -> int: diff --git a/mypyc/test-data/irbuild-basic.test b/mypyc/test-data/irbuild-basic.test index cd952ef2ebfd..981460dae371 100644 --- a/mypyc/test-data/irbuild-basic.test +++ b/mypyc/test-data/irbuild-basic.test @@ -568,7 +568,7 @@ L3: x = 2 goto L8 L4: - r4 = n == 0 + r4 = int_eq n, 0 if r4 goto L5 else goto L6 :: bool L5: x = 2 @@ -598,7 +598,7 @@ def f(n): r0 :: bit r1 :: int L0: - r0 = n == 0 + r0 = int_eq n, 0 if r0 goto L1 else goto L2 :: bool L1: r1 = 0 @@ -1462,7 +1462,7 @@ L0: r1 = load_mem r0 :: native_int* keep_alive x r2 = r1 << 1 - r3 = r2 != 0 + r3 = int_ne r2, 0 if r3 goto L1 else goto L2 :: bool L1: return 2 @@ -2052,19 +2052,12 @@ def f(): r13 :: bit r14 :: object r15, x :: int - r16 :: native_int - r17, r18 :: bit - r19 :: bool - r20, r21 :: bit - r22 :: native_int - r23, r24 :: bit - r25 :: bool - r26, r27 :: bit - r28 :: int - r29 :: object - r30 :: i32 - r31 :: bit - r32 :: short_int + r16, r17 :: bit + r18 :: int + r19 :: object + r20 :: i32 + r21 :: bit + r22 :: short_int L0: r0 = PyList_New(0) r1 = PyList_New(3) @@ -2086,52 +2079,30 @@ L1: keep_alive r1 r12 = r11 << 1 r13 = r9 < r12 :: signed - if r13 goto L2 else goto L14 :: bool + if r13 goto L2 else goto L8 :: bool L2: r14 = CPyList_GetItemUnsafe(r1, r9) r15 = unbox(int, r14) x = r15 - r16 = x & 1 - r17 = r16 == 0 - if r17 goto L3 else goto L4 :: bool + r16 = int_ne x, 4 + if r16 goto L4 else goto L3 :: bool L3: - r18 = x != 4 - r19 = r18 - goto L5 + goto L7 L4: - r20 = CPyTagged_IsEq_(x, 4) - r21 = r20 ^ 1 - r19 = r21 + r17 = int_ne x, 6 + if r17 goto L6 else goto L5 :: bool L5: - if r19 goto L7 else goto L6 :: bool + goto L7 L6: - goto L13 + r18 = CPyTagged_Multiply(x, x) + r19 = box(int, r18) + r20 = PyList_Append(r0, r19) + r21 = r20 >= 0 :: signed L7: - r22 = x & 1 - r23 = r22 == 0 - if r23 goto L8 else goto L9 :: bool -L8: - r24 = x != 6 - r25 = r24 - goto L10 -L9: - r26 = CPyTagged_IsEq_(x, 6) - r27 = r26 ^ 1 - r25 = r27 -L10: - if r25 goto L12 else goto L11 :: bool -L11: - goto L13 -L12: - r28 = CPyTagged_Multiply(x, x) - r29 = box(int, r28) - r30 = PyList_Append(r0, r29) - r31 = r30 >= 0 :: signed -L13: - r32 = r9 + 2 - r9 = r32 + r22 = r9 + 2 + r9 = r22 goto L1 -L14: +L8: return r0 [case testDictComprehension] @@ -2151,19 +2122,12 @@ def f(): r13 :: bit r14 :: object r15, x :: int - r16 :: native_int - r17, r18 :: bit - r19 :: bool - r20, r21 :: bit - r22 :: native_int - r23, r24 :: bit - r25 :: bool - r26, r27 :: bit - r28 :: int - r29, r30 :: object - r31 :: i32 - r32 :: bit - r33 :: short_int + r16, r17 :: bit + r18 :: int + r19, r20 :: object + r21 :: i32 + r22 :: bit + r23 :: short_int L0: r0 = PyDict_New() r1 = PyList_New(3) @@ -2185,53 +2149,31 @@ L1: keep_alive r1 r12 = r11 << 1 r13 = r9 < r12 :: signed - if r13 goto L2 else goto L14 :: bool + if r13 goto L2 else goto L8 :: bool L2: r14 = CPyList_GetItemUnsafe(r1, r9) r15 = unbox(int, r14) x = r15 - r16 = x & 1 - r17 = r16 == 0 - if r17 goto L3 else goto L4 :: bool + r16 = int_ne x, 4 + if r16 goto L4 else goto L3 :: bool L3: - r18 = x != 4 - r19 = r18 - goto L5 + goto L7 L4: - r20 = CPyTagged_IsEq_(x, 4) - r21 = r20 ^ 1 - r19 = r21 + r17 = int_ne x, 6 + if r17 goto L6 else goto L5 :: bool L5: - if r19 goto L7 else goto L6 :: bool + goto L7 L6: - goto L13 + r18 = CPyTagged_Multiply(x, x) + r19 = box(int, x) + r20 = box(int, r18) + r21 = CPyDict_SetItem(r0, r19, r20) + r22 = r21 >= 0 :: signed L7: - r22 = x & 1 - r23 = r22 == 0 - if r23 goto L8 else goto L9 :: bool -L8: - r24 = x != 6 - r25 = r24 - goto L10 -L9: - r26 = CPyTagged_IsEq_(x, 6) - r27 = r26 ^ 1 - r25 = r27 -L10: - if r25 goto L12 else goto L11 :: bool -L11: - goto L13 -L12: - r28 = CPyTagged_Multiply(x, x) - r29 = box(int, x) - r30 = box(int, r28) - r31 = CPyDict_SetItem(r0, r29, r30) - r32 = r31 >= 0 :: signed -L13: - r33 = r9 + 2 - r9 = r33 + r23 = r9 + 2 + r9 = r23 goto L1 -L14: +L8: return r0 [case testLoopsMultipleAssign] @@ -3011,85 +2953,57 @@ def call_any(l): r0 :: bool r1, r2 :: object r3, i :: int - r4 :: native_int - r5, r6 :: bit - r7 :: bool - r8, r9 :: bit + r4, r5 :: bit L0: r0 = 0 r1 = PyObject_GetIter(l) L1: r2 = PyIter_Next(r1) - if is_error(r2) goto L9 else goto L2 + if is_error(r2) goto L6 else goto L2 L2: r3 = unbox(int, r2) i = r3 - r4 = i & 1 - r5 = r4 == 0 - if r5 goto L3 else goto L4 :: bool + r4 = int_eq i, 0 + if r4 goto L3 else goto L4 :: bool L3: - r6 = i == 0 - r7 = r6 - goto L5 + r0 = 1 + goto L8 L4: - r8 = CPyTagged_IsEq_(i, 0) - r7 = r8 L5: - if r7 goto L6 else goto L7 :: bool + goto L1 L6: - r0 = 1 - goto L11 + r5 = CPy_NoErrOccured() L7: L8: - goto L1 -L9: - r9 = CPy_NoErrOccured() -L10: -L11: return r0 def call_all(l): l :: object r0 :: bool r1, r2 :: object r3, i :: int - r4 :: native_int - r5, r6 :: bit - r7 :: bool - r8 :: bit - r9 :: bool - r10 :: bit + r4, r5, r6 :: bit L0: r0 = 1 r1 = PyObject_GetIter(l) L1: r2 = PyIter_Next(r1) - if is_error(r2) goto L9 else goto L2 + if is_error(r2) goto L6 else goto L2 L2: r3 = unbox(int, r2) i = r3 - r4 = i & 1 - r5 = r4 == 0 + r4 = int_eq i, 0 + r5 = r4 ^ 1 if r5 goto L3 else goto L4 :: bool L3: - r6 = i == 0 - r7 = r6 - goto L5 + r0 = 0 + goto L8 L4: - r8 = CPyTagged_IsEq_(i, 0) - r7 = r8 L5: - r9 = r7 ^ 1 - if r9 goto L6 else goto L7 :: bool + goto L1 L6: - r0 = 0 - goto L11 + r6 = CPy_NoErrOccured() L7: L8: - goto L1 -L9: - r10 = CPy_NoErrOccured() -L10: -L11: return r0 [case testSum] diff --git a/mypyc/test-data/irbuild-bool.test b/mypyc/test-data/irbuild-bool.test index 731d393d69ab..f0b0b480bc0d 100644 --- a/mypyc/test-data/irbuild-bool.test +++ b/mypyc/test-data/irbuild-bool.test @@ -96,7 +96,7 @@ L0: r1 = load_mem r0 :: native_int* keep_alive l r2 = r1 << 1 - r3 = r2 != 0 + r3 = int_ne r2, 0 return r3 def always_truthy_instance_to_bool(o): o :: __main__.C @@ -222,7 +222,7 @@ def eq1(x, y): L0: r0 = y << 1 r1 = extend r0: builtins.bool to builtins.int - r2 = x == r1 + r2 = int_eq x, r1 return r2 def eq2(x, y): x :: bool @@ -233,7 +233,7 @@ def eq2(x, y): L0: r0 = x << 1 r1 = extend r0: builtins.bool to builtins.int - r2 = r1 == y + r2 = int_eq r1, y return r2 def neq1(x, y): x :: i64 diff --git a/mypyc/test-data/irbuild-classes.test b/mypyc/test-data/irbuild-classes.test index 55e55dbf3286..8c4743c6a47f 100644 --- a/mypyc/test-data/irbuild-classes.test +++ b/mypyc/test-data/irbuild-classes.test @@ -1249,7 +1249,7 @@ L0: r0 = x.__getitem__(2) r1 = CPyList_GetItemShortBorrow(r0, 0) r2 = unbox(int, r1) - r3 = r2 == 4 + r3 = int_eq r2, 4 keep_alive r0 if r3 goto L1 else goto L2 :: bool L1: diff --git a/mypyc/test-data/irbuild-int.test b/mypyc/test-data/irbuild-int.test index fbe00aff4040..1489f2f470dd 100644 --- a/mypyc/test-data/irbuild-int.test +++ b/mypyc/test-data/irbuild-int.test @@ -4,24 +4,10 @@ def f(x: int, y: int) -> bool: [out] def f(x, y): x, y :: int - r0 :: native_int - r1, r2 :: bit - r3 :: bool - r4, r5 :: bit + r0 :: bit L0: - r0 = x & 1 - r1 = r0 == 0 - if r1 goto L1 else goto L2 :: bool -L1: - r2 = x != y - r3 = r2 - goto L3 -L2: - r4 = CPyTagged_IsEq_(x, y) - r5 = r4 ^ 1 - r3 = r5 -L3: - return r3 + r0 = int_ne x, y + return r0 [case testShortIntComparisons] def f(x: int) -> int: @@ -43,22 +29,22 @@ def f(x): r4 :: native_int r5, r6, r7 :: bit L0: - r0 = x == 6 + r0 = int_eq x, 6 if r0 goto L1 else goto L2 :: bool L1: return 2 L2: - r1 = x != 8 + r1 = int_ne x, 8 if r1 goto L3 else goto L4 :: bool L3: return 4 L4: - r2 = 10 == x + r2 = int_eq 10, x if r2 goto L5 else goto L6 :: bool L5: return 6 L6: - r3 = 12 != x + r3 = int_ne 12, x if r3 goto L7 else goto L8 :: bool L7: return 8 diff --git a/mypyc/test-data/irbuild-match.test b/mypyc/test-data/irbuild-match.test index a078ae0defdb..ab5a19624ba6 100644 --- a/mypyc/test-data/irbuild-match.test +++ b/mypyc/test-data/irbuild-match.test @@ -14,7 +14,7 @@ def f(): r6 :: object_ptr r7, r8 :: object L0: - r0 = 246 == 246 + r0 = int_eq 246, 246 if r0 goto L1 else goto L2 :: bool L1: r1 = 'matched' @@ -30,6 +30,7 @@ L2: L3: r8 = box(None, 1) return r8 + [case testMatchOrPattern_python3_10] def f(): match 123: @@ -46,10 +47,10 @@ def f(): r7 :: object_ptr r8, r9 :: object L0: - r0 = 246 == 246 + r0 = int_eq 246, 246 if r0 goto L3 else goto L1 :: bool L1: - r1 = 246 == 912 + r1 = int_eq 246, 912 if r1 goto L3 else goto L2 :: bool L2: goto L4 @@ -67,6 +68,7 @@ L4: L5: r9 = box(None, 1) return r9 + [case testMatchOrPatternManyPatterns_python3_10] def f(): match 1: @@ -83,16 +85,16 @@ def f(): r9 :: object_ptr r10, r11 :: object L0: - r0 = 2 == 2 + r0 = int_eq 2, 2 if r0 goto L5 else goto L1 :: bool L1: - r1 = 2 == 4 + r1 = int_eq 2, 4 if r1 goto L5 else goto L2 :: bool L2: - r2 = 2 == 6 + r2 = int_eq 2, 6 if r2 goto L5 else goto L3 :: bool L3: - r3 = 2 == 8 + r3 = int_eq 2, 8 if r3 goto L5 else goto L4 :: bool L4: goto L6 @@ -110,6 +112,7 @@ L6: L7: r11 = box(None, 1) return r11 + [case testMatchClassPattern_python3_10] def f(): match 123: @@ -200,7 +203,7 @@ def f(): r14 :: object_ptr r15, r16 :: object L0: - r0 = 246 == 246 + r0 = int_eq 246, 246 if r0 goto L1 else goto L2 :: bool L1: r1 = 'matched' @@ -213,7 +216,7 @@ L1: keep_alive r1 goto L5 L2: - r8 = 246 == 912 + r8 = int_eq 246, 912 if r8 goto L3 else goto L4 :: bool L3: r9 = 'no match' @@ -229,6 +232,7 @@ L4: L5: r16 = box(None, 1) return r16 + [case testMatchMultiBodyAndComplexOr_python3_10] def f(): match 123: @@ -265,7 +269,7 @@ def f(): r23 :: object_ptr r24, r25 :: object L0: - r0 = 246 == 2 + r0 = int_eq 246, 2 if r0 goto L1 else goto L2 :: bool L1: r1 = 'here 1' @@ -278,10 +282,10 @@ L1: keep_alive r1 goto L9 L2: - r8 = 246 == 4 + r8 = int_eq 246, 4 if r8 goto L5 else goto L3 :: bool L3: - r9 = 246 == 6 + r9 = int_eq 246, 6 if r9 goto L5 else goto L4 :: bool L4: goto L6 @@ -296,7 +300,7 @@ L5: keep_alive r10 goto L9 L6: - r17 = 246 == 246 + r17 = int_eq 246, 246 if r17 goto L7 else goto L8 :: bool L7: r18 = 'here 123' @@ -312,6 +316,7 @@ L8: L9: r25 = box(None, 1) return r25 + [case testMatchWithGuard_python3_10] def f(): match 123: @@ -328,7 +333,7 @@ def f(): r6 :: object_ptr r7, r8 :: object L0: - r0 = 246 == 246 + r0 = int_eq 246, 246 if r0 goto L1 else goto L3 :: bool L1: if 1 goto L2 else goto L3 :: bool @@ -346,6 +351,7 @@ L3: L4: r8 = box(None, 1) return r8 + [case testMatchSingleton_python3_10] def f(): match 123: @@ -449,7 +455,7 @@ def f(): r9 :: object_ptr r10, r11 :: object L0: - r0 = 2 == 2 + r0 = int_eq 2, 2 if r0 goto L3 else goto L1 :: bool L1: r1 = load_address PyLong_Type @@ -472,6 +478,7 @@ L4: L5: r11 = box(None, 1) return r11 + [case testMatchAsPattern_python3_10] def f(): match 123: @@ -487,7 +494,7 @@ def f(): r6 :: object_ptr r7, r8 :: object L0: - r0 = 246 == 246 + r0 = int_eq 246, 246 r1 = object 123 x = r1 if r0 goto L1 else goto L2 :: bool @@ -504,6 +511,7 @@ L2: L3: r8 = box(None, 1) return r8 + [case testMatchAsPatternOnOrPattern_python3_10] def f(): match 1: @@ -521,12 +529,12 @@ def f(): r8 :: object_ptr r9, r10 :: object L0: - r0 = 2 == 2 + r0 = int_eq 2, 2 r1 = object 1 x = r1 if r0 goto L3 else goto L1 :: bool L1: - r2 = 2 == 4 + r2 = int_eq 2, 4 r3 = object 2 x = r3 if r2 goto L3 else goto L2 :: bool @@ -545,6 +553,7 @@ L4: L5: r10 = box(None, 1) return r10 + [case testMatchAsPatternOnClassPattern_python3_10] def f(): match 123: diff --git a/mypyc/test-data/irbuild-nested.test b/mypyc/test-data/irbuild-nested.test index b2b884705366..62ae6eb9ee35 100644 --- a/mypyc/test-data/irbuild-nested.test +++ b/mypyc/test-data/irbuild-nested.test @@ -658,7 +658,7 @@ def baz_f_obj.__call__(__mypyc_self__, n): r6, r7 :: int L0: r0 = __mypyc_self__.__mypyc_env__ - r1 = n == 0 + r1 = int_eq n, 0 if r1 goto L1 else goto L2 :: bool L1: return 0 @@ -796,7 +796,7 @@ def baz(n): r0 :: bit r1, r2, r3 :: int L0: - r0 = n == 0 + r0 = int_eq n, 0 if r0 goto L1 else goto L2 :: bool L1: return 0 diff --git a/mypyc/test-data/irbuild-optional.test b/mypyc/test-data/irbuild-optional.test index e89018a727da..75c008586999 100644 --- a/mypyc/test-data/irbuild-optional.test +++ b/mypyc/test-data/irbuild-optional.test @@ -222,7 +222,7 @@ def f(y): L0: r0 = box(None, 1) x = r0 - r1 = y == 2 + r1 = int_eq y, 2 if r1 goto L1 else goto L2 :: bool L1: r2 = box(int, y) diff --git a/mypyc/test-data/irbuild-tuple.test b/mypyc/test-data/irbuild-tuple.test index a47f3db6a725..ab0e2fa09a9d 100644 --- a/mypyc/test-data/irbuild-tuple.test +++ b/mypyc/test-data/irbuild-tuple.test @@ -195,70 +195,30 @@ def f(i: int) -> bool: [out] def f(i): i :: int - r0 :: native_int - r1, r2 :: bit + r0 :: bit + r1 :: bool + r2 :: bit r3 :: bool r4 :: bit - r5 :: bool - r6 :: native_int - r7, r8 :: bit - r9 :: bool - r10 :: bit - r11 :: bool - r12 :: native_int - r13, r14 :: bit - r15 :: bool - r16 :: bit L0: - r0 = i & 1 - r1 = r0 == 0 - if r1 goto L1 else goto L2 :: bool + r0 = int_eq i, 2 + if r0 goto L1 else goto L2 :: bool L1: - r2 = i == 2 - r3 = r2 + r1 = r0 goto L3 L2: - r4 = CPyTagged_IsEq_(i, 2) - r3 = r4 + r2 = int_eq i, 4 + r1 = r2 L3: - if r3 goto L4 else goto L5 :: bool + if r1 goto L4 else goto L5 :: bool L4: - r5 = r3 - goto L9 + r3 = r1 + goto L6 L5: - r6 = i & 1 - r7 = r6 == 0 - if r7 goto L6 else goto L7 :: bool + r4 = int_eq i, 6 + r3 = r4 L6: - r8 = i == 4 - r9 = r8 - goto L8 -L7: - r10 = CPyTagged_IsEq_(i, 4) - r9 = r10 -L8: - r5 = r9 -L9: - if r5 goto L10 else goto L11 :: bool -L10: - r11 = r5 - goto L15 -L11: - r12 = i & 1 - r13 = r12 == 0 - if r13 goto L12 else goto L13 :: bool -L12: - r14 = i == 6 - r15 = r14 - goto L14 -L13: - r16 = CPyTagged_IsEq_(i, 6) - r15 = r16 -L14: - r11 = r15 -L15: - return r11 - + return r3 [case testTupleBuiltFromList] def f(val: int) -> bool: @@ -270,24 +230,11 @@ def test() -> None: [out] def f(val): val, r0 :: int - r1 :: native_int - r2, r3 :: bit - r4 :: bool - r5 :: bit + r1 :: bit L0: r0 = CPyTagged_Remainder(val, 4) - r1 = r0 & 1 - r2 = r1 == 0 - if r2 goto L1 else goto L2 :: bool -L1: - r3 = r0 == 0 - r4 = r3 - goto L3 -L2: - r5 = CPyTagged_IsEq_(r0, 0) - r4 = r5 -L3: - return r4 + r1 = int_eq r0, 0 + return r1 def test(): r0 :: list r1, r2, r3 :: object diff --git a/mypyc/test-data/lowering-int.test b/mypyc/test-data/lowering-int.test new file mode 100644 index 000000000000..8c813563d0e6 --- /dev/null +++ b/mypyc/test-data/lowering-int.test @@ -0,0 +1,126 @@ +-- Test cases for converting high-level IR to lower-level IR (lowering). + +[case testLowerIntEq] +def f(x: int, y: int) -> int: + if x == y: + return 1 + else: + return 2 +[out] +def f(x, y): + x, y :: int + r0 :: native_int + r1, r2, r3 :: bit +L0: + r0 = x & 1 + r1 = r0 == 0 + if r1 goto L1 else goto L2 :: bool +L1: + r2 = x == y + if r2 goto L3 else goto L4 :: bool +L2: + r3 = CPyTagged_IsEq_(x, y) + if r3 goto L3 else goto L4 :: bool +L3: + return 2 +L4: + return 4 + +[case testLowerIntNe] +def f(x: int, y: int) -> int: + if x != y: + return 1 + else: + return 2 +[out] +def f(x, y): + x, y :: int + r0 :: native_int + r1, r2, r3, r4 :: bit +L0: + r0 = x & 1 + r1 = r0 == 0 + if r1 goto L1 else goto L2 :: bool +L1: + r2 = x != y + if r2 goto L3 else goto L4 :: bool +L2: + r3 = CPyTagged_IsEq_(x, y) + r4 = r3 ^ 1 + if r4 goto L3 else goto L4 :: bool +L3: + return 2 +L4: + return 4 + +[case testLowerIntEqWithConstant] +def f(x: int, y: int) -> int: + if x == 2: + return 1 + elif -1 == x: + return 2 + return 3 +[out] +def f(x, y): + x, y :: int + r0, r1 :: bit +L0: + r0 = x == 4 + if r0 goto L1 else goto L2 :: bool +L1: + return 2 +L2: + r1 = -2 == x + if r1 goto L3 else goto L4 :: bool +L3: + return 4 +L4: + return 6 + +[case testLowerIntNeWithConstant] +def f(x: int, y: int) -> int: + if x != 2: + return 1 + elif -1 != x: + return 2 + return 3 +[out] +def f(x, y): + x, y :: int + r0, r1 :: bit +L0: + r0 = x != 4 + if r0 goto L1 else goto L2 :: bool +L1: + return 2 +L2: + r1 = -2 != x + if r1 goto L3 else goto L4 :: bool +L3: + return 4 +L4: + return 6 + +[case testLowerIntEqValueContext] +def f(x: int, y: int) -> bool: + return x == y +[out] +def f(x, y): + x, y :: int + r0 :: native_int + r1, r2 :: bit + r3 :: bool + r4 :: bit +L0: + r0 = x & 1 + r1 = r0 == 0 + if r1 goto L1 else goto L2 :: bool +L1: + r2 = x == y + r3 = r2 + goto L3 +L2: + r4 = CPyTagged_IsEq_(x, y) + r3 = r4 +L3: + return r3 diff --git a/mypyc/test-data/opt-flag-elimination.test b/mypyc/test-data/opt-flag-elimination.test index f047a87dc3fa..337ced70a355 100644 --- a/mypyc/test-data/opt-flag-elimination.test +++ b/mypyc/test-data/opt-flag-elimination.test @@ -29,15 +29,13 @@ L0: if x goto L1 else goto L2 :: bool L1: r0 = c() - if r0 goto L4 else goto L5 :: bool + if r0 goto L3 else goto L4 :: bool L2: r1 = d() - if r1 goto L4 else goto L5 :: bool + if r1 goto L3 else goto L4 :: bool L3: - unreachable -L4: return 2 -L5: +L4: return 4 [case testFlagEliminationOneAssignment] @@ -92,20 +90,18 @@ L0: if x goto L1 else goto L2 :: bool L1: r0 = c(2) - if r0 goto L6 else goto L7 :: bool + if r0 goto L5 else goto L6 :: bool L2: if y goto L3 else goto L4 :: bool L3: r1 = c(4) - if r1 goto L6 else goto L7 :: bool + if r1 goto L5 else goto L6 :: bool L4: r2 = c(6) - if r2 goto L6 else goto L7 :: bool + if r2 goto L5 else goto L6 :: bool L5: - unreachable -L6: return 2 -L7: +L6: return 4 [case testFlagEliminationAssignmentNotLastOp] diff --git a/mypyc/test-data/refcount.test b/mypyc/test-data/refcount.test index 0f2c134ae21e..df980af8a7c7 100644 --- a/mypyc/test-data/refcount.test +++ b/mypyc/test-data/refcount.test @@ -67,7 +67,7 @@ def f(): L0: x = 2 y = 4 - r0 = x == 2 + r0 = int_eq x, 2 if r0 goto L3 else goto L4 :: bool L1: return x @@ -185,34 +185,26 @@ def f(a: int) -> int: [out] def f(a): a :: int - r0 :: native_int - r1, r2, r3 :: bit - x, r4, y :: int + r0 :: bit + x, r1, y :: int L0: - r0 = a & 1 - r1 = r0 != 0 - if r1 goto L1 else goto L2 :: bool + r0 = int_eq a, a + if r0 goto L1 else goto L2 :: bool L1: - r2 = CPyTagged_IsEq_(a, a) - if r2 goto L3 else goto L4 :: bool -L2: - r3 = a == a - if r3 goto L3 else goto L4 :: bool -L3: a = 2 - goto L5 -L4: + goto L3 +L2: x = 4 dec_ref x :: int - goto L6 -L5: - r4 = CPyTagged_Add(a, 2) + goto L4 +L3: + r1 = CPyTagged_Add(a, 2) dec_ref a :: int - y = r4 + y = r1 return y -L6: +L4: inc_ref a :: int - goto L5 + goto L3 [case testConditionalAssignToArgument2] def f(a: int) -> int: @@ -225,33 +217,25 @@ def f(a: int) -> int: [out] def f(a): a :: int - r0 :: native_int - r1, r2, r3 :: bit - x, r4, y :: int + r0 :: bit + x, r1, y :: int L0: - r0 = a & 1 - r1 = r0 != 0 - if r1 goto L1 else goto L2 :: bool + r0 = int_eq a, a + if r0 goto L1 else goto L2 :: bool L1: - r2 = CPyTagged_IsEq_(a, a) - if r2 goto L3 else goto L4 :: bool -L2: - r3 = a == a - if r3 goto L3 else goto L4 :: bool -L3: x = 4 dec_ref x :: int - goto L6 -L4: + goto L4 +L2: a = 2 -L5: - r4 = CPyTagged_Add(a, 2) +L3: + r1 = CPyTagged_Add(a, 2) dec_ref a :: int - y = r4 + y = r1 return y -L6: +L4: inc_ref a :: int - goto L5 + goto L3 [case testConditionalAssignToArgument3] def f(a: int) -> int: @@ -261,25 +245,17 @@ def f(a: int) -> int: [out] def f(a): a :: int - r0 :: native_int - r1, r2, r3 :: bit + r0 :: bit L0: - r0 = a & 1 - r1 = r0 != 0 - if r1 goto L1 else goto L2 :: bool + r0 = int_eq a, a + if r0 goto L1 else goto L3 :: bool L1: - r2 = CPyTagged_IsEq_(a, a) - if r2 goto L3 else goto L5 :: bool -L2: - r3 = a == a - if r3 goto L3 else goto L5 :: bool -L3: a = 2 -L4: +L2: return a -L5: +L3: inc_ref a :: int - goto L4 + goto L2 [case testAssignRegisterToItself] def f(a: int) -> int: @@ -438,40 +414,32 @@ def f() -> int: [out] def f(): x, y, z :: int - r0 :: native_int - r1, r2, r3 :: bit - a, r4, r5 :: int + r0 :: bit + a, r1, r2 :: int L0: x = 2 y = 4 z = 6 - r0 = z & 1 - r1 = r0 != 0 - if r1 goto L1 else goto L2 :: bool + r0 = int_eq z, z + if r0 goto L3 else goto L4 :: bool L1: - r2 = CPyTagged_IsEq_(z, z) - if r2 goto L5 else goto L6 :: bool -L2: - r3 = z == z - if r3 goto L5 else goto L6 :: bool -L3: return z -L4: +L2: a = 2 - r4 = CPyTagged_Add(x, y) + r1 = CPyTagged_Add(x, y) dec_ref x :: int dec_ref y :: int - r5 = CPyTagged_Subtract(r4, a) - dec_ref r4 :: int + r2 = CPyTagged_Subtract(r1, a) + dec_ref r1 :: int dec_ref a :: int - return r5 -L5: + return r2 +L3: dec_ref x :: int dec_ref y :: int - goto L3 -L6: + goto L1 +L4: dec_ref z :: int - goto L4 + goto L2 [case testLoop] def f(a: int) -> int: @@ -1371,25 +1339,12 @@ class C: def add(c): c :: __main__.C r0, r1 :: int - r2 :: native_int - r3, r4 :: bit - r5 :: bool - r6 :: bit + r2 :: bit L0: r0 = borrow c.x r1 = borrow c.y - r2 = r0 & 1 - r3 = r2 == 0 - if r3 goto L1 else goto L2 :: bool -L1: - r4 = r0 == r1 - r5 = r4 - goto L3 -L2: - r6 = CPyTagged_IsEq_(r0, r1) - r5 = r6 -L3: - return r5 + r2 = int_eq r0, r1 + return r2 [case testBorrowIntLessThan] def add(c: C) -> bool: @@ -1441,24 +1396,11 @@ class C: def add(c): c :: __main__.C r0 :: int - r1 :: native_int - r2, r3 :: bit - r4 :: bool - r5 :: bit + r1 :: bit L0: r0 = borrow c.x - r1 = r0 & 1 - r2 = r1 == 0 - if r2 goto L1 else goto L2 :: bool -L1: - r3 = r0 == 20 - r4 = r3 - goto L3 -L2: - r5 = CPyTagged_IsEq_(r0, 20) - r4 = r5 -L3: - return r4 + r1 = int_eq r0, 20 + return r1 [case testBorrowIntArithmetic] def add(c: C) -> int: @@ -1501,23 +1443,15 @@ class C: def add(c, n): c :: __main__.C n, r0, r1 :: int - r2 :: native_int - r3, r4, r5 :: bit + r2 :: bit L0: r0 = borrow c.x r1 = borrow c.y - r2 = r0 & 1 - r3 = r2 != 0 - if r3 goto L1 else goto L2 :: bool + r2 = int_eq r0, r1 + if r2 goto L1 else goto L2 :: bool L1: - r4 = CPyTagged_IsEq_(r0, r1) - if r4 goto L3 else goto L4 :: bool -L2: - r5 = r0 == r1 - if r5 goto L3 else goto L4 :: bool -L3: return 1 -L4: +L2: return 0 [case testBorrowIntInPlaceOp] diff --git a/mypyc/test/test_cheader.py b/mypyc/test/test_cheader.py index cc0fd9df2b34..f2af41c22ea9 100644 --- a/mypyc/test/test_cheader.py +++ b/mypyc/test/test_cheader.py @@ -7,6 +7,7 @@ import re import unittest +from mypyc.ir.ops import PrimitiveDescription from mypyc.primitives import registry from mypyc.primitives.registry import CFunctionDescription @@ -25,17 +26,24 @@ def check_name(name: str) -> None: rf"\b{name}\b", header ), f'"{name}" is used in mypyc.primitives but not declared in CPy.h' - for values in [ + for old_values in [ registry.method_call_ops.values(), registry.function_ops.values(), - registry.binary_ops.values(), registry.unary_ops.values(), ]: + for old_ops in old_values: + if isinstance(old_ops, CFunctionDescription): + old_ops = [old_ops] + for old_op in old_ops: + check_name(old_op.c_function_name) + + for values in [registry.binary_ops.values()]: for ops in values: - if isinstance(ops, CFunctionDescription): + if isinstance(ops, PrimitiveDescription): ops = [ops] for op in ops: - check_name(op.c_function_name) + if op.c_function_name is not None: + check_name(op.c_function_name) primitives_path = os.path.join(os.path.dirname(__file__), "..", "primitives") for fnam in glob.glob(f"{primitives_path}/*.py"): diff --git a/mypyc/test/test_emitfunc.py b/mypyc/test/test_emitfunc.py index ab1586bb22a8..b16387aa40af 100644 --- a/mypyc/test/test_emitfunc.py +++ b/mypyc/test/test_emitfunc.py @@ -859,6 +859,8 @@ def assert_emit_binary_op( args = [left, right] if desc.ordering is not None: args = [args[i] for i in desc.ordering] + # This only supports primitives that map to C calls + assert desc.c_function_name is not None self.assert_emit( CallC( desc.c_function_name, diff --git a/mypyc/test/test_lowering.py b/mypyc/test/test_lowering.py new file mode 100644 index 000000000000..e32dba2e1021 --- /dev/null +++ b/mypyc/test/test_lowering.py @@ -0,0 +1,54 @@ +"""Runner for lowering transform tests.""" + +from __future__ import annotations + +import os.path + +from mypy.errors import CompileError +from mypy.test.config import test_temp_dir +from mypy.test.data import DataDrivenTestCase +from mypyc.common import TOP_LEVEL_NAME +from mypyc.ir.pprint import format_func +from mypyc.options import CompilerOptions +from mypyc.test.testutil import ( + ICODE_GEN_BUILTINS, + MypycDataSuite, + assert_test_output, + build_ir_for_single_file, + remove_comment_lines, + use_custom_builtins, +) +from mypyc.transform.exceptions import insert_exception_handling +from mypyc.transform.flag_elimination import do_flag_elimination +from mypyc.transform.lower import lower_ir +from mypyc.transform.refcount import insert_ref_count_opcodes +from mypyc.transform.uninit import insert_uninit_checks + + +class TestLowering(MypycDataSuite): + files = ["lowering-int.test"] + base_path = test_temp_dir + + def run_case(self, testcase: DataDrivenTestCase) -> None: + with use_custom_builtins(os.path.join(self.data_prefix, ICODE_GEN_BUILTINS), testcase): + expected_output = remove_comment_lines(testcase.output) + try: + ir = build_ir_for_single_file(testcase.input) + except CompileError as e: + actual = e.messages + else: + actual = [] + for fn in ir: + if fn.name == TOP_LEVEL_NAME and not testcase.name.endswith("_toplevel"): + continue + options = CompilerOptions() + # Lowering happens after exception handling and ref count opcodes have + # been added. Any changes must maintain reference counting semantics. + insert_uninit_checks(fn) + insert_exception_handling(fn) + insert_ref_count_opcodes(fn) + lower_ir(fn, options) + do_flag_elimination(fn, options) + actual.extend(format_func(fn)) + + assert_test_output(testcase, actual, "Invalid source code output", expected_output) diff --git a/mypyc/transform/ir_transform.py b/mypyc/transform/ir_transform.py index 254fe3f7771d..a631bd7352b5 100644 --- a/mypyc/transform/ir_transform.py +++ b/mypyc/transform/ir_transform.py @@ -35,6 +35,7 @@ MethodCall, Op, OpVisitor, + PrimitiveOp, RaiseStandardError, Return, SetAttr, @@ -80,6 +81,7 @@ def transform_blocks(self, blocks: list[BasicBlock]) -> None: """ block_map: dict[BasicBlock, BasicBlock] = {} op_map = self.op_map + empties = set() for block in blocks: new_block = BasicBlock() block_map[block] = new_block @@ -89,7 +91,10 @@ def transform_blocks(self, blocks: list[BasicBlock]) -> None: new_op = op.accept(self) if new_op is not op: op_map[op] = new_op - + # A transform can produce empty blocks which can be removed. + if is_empty_block(new_block) and not is_empty_block(block): + empties.add(new_block) + self.builder.blocks = [block for block in self.builder.blocks if block not in empties] # Update all op/block references to point to the transformed ones. patcher = PatchVisitor(op_map, block_map) for block in self.builder.blocks: @@ -170,6 +175,9 @@ def visit_raise_standard_error(self, op: RaiseStandardError) -> Value | None: def visit_call_c(self, op: CallC) -> Value | None: return self.add(op) + def visit_primitive_op(self, op: PrimitiveOp) -> Value | None: + return self.add(op) + def visit_truncate(self, op: Truncate) -> Value | None: return self.add(op) @@ -302,6 +310,9 @@ def visit_raise_standard_error(self, op: RaiseStandardError) -> None: def visit_call_c(self, op: CallC) -> None: op.args = [self.fix_op(arg) for arg in op.args] + def visit_primitive_op(self, op: PrimitiveOp) -> None: + op.args = [self.fix_op(arg) for arg in op.args] + def visit_truncate(self, op: Truncate) -> None: op.src = self.fix_op(op.src) @@ -351,3 +362,7 @@ def visit_keep_alive(self, op: KeepAlive) -> None: def visit_unborrow(self, op: Unborrow) -> None: op.src = self.fix_op(op.src) + + +def is_empty_block(block: BasicBlock) -> bool: + return len(block.ops) == 1 and isinstance(block.ops[0], Unreachable) diff --git a/mypyc/transform/lower.py b/mypyc/transform/lower.py new file mode 100644 index 000000000000..b717657095f9 --- /dev/null +++ b/mypyc/transform/lower.py @@ -0,0 +1,33 @@ +"""Transform IR to lower-level ops. + +Higher-level ops are used in earlier compiler passes, as they make +various analyses, optimizations and transforms easier to implement. +Later passes use lower-level ops, as they are easier to generate code +from, and they help with lower-level optimizations. + +Lowering of various primitive ops is implemented in the mypyc.lower +package. +""" + +from mypyc.ir.func_ir import FuncIR +from mypyc.ir.ops import PrimitiveOp, Value +from mypyc.irbuild.ll_builder import LowLevelIRBuilder +from mypyc.lower.registry import lowering_registry +from mypyc.options import CompilerOptions +from mypyc.transform.ir_transform import IRTransform + + +def lower_ir(ir: FuncIR, options: CompilerOptions) -> None: + builder = LowLevelIRBuilder(None, options) + visitor = LoweringVisitor(builder) + visitor.transform_blocks(ir.blocks) + ir.blocks = builder.blocks + + +class LoweringVisitor(IRTransform): + def visit_primitive_op(self, op: PrimitiveOp) -> Value: + # The lowering implementation functions of various primitive ops are stored + # in a registry, which is populated using function decorators. The name + # of op (such as "int_eq") is used as the key. + lower_fn = lowering_registry[op.desc.name] + return lower_fn(self.builder, op.args, op.line) From cf221bdc2cefc539a0b278c10ed6bde0350f370e Mon Sep 17 00:00:00 2001 From: Alex Waygood Date: Sat, 16 Mar 2024 12:40:30 +0000 Subject: [PATCH 49/54] Sync typeshed Source commit: https://github.com/python/typeshed/commit/ff7caa30e29d9c9467b1ba0007764c65c0b44a5c --- mypy/typeshed/stdlib/_codecs.pyi | 90 +- mypy/typeshed/stdlib/_collections_abc.pyi | 6 +- mypy/typeshed/stdlib/_compression.pyi | 4 +- mypy/typeshed/stdlib/_ctypes.pyi | 44 +- mypy/typeshed/stdlib/_curses.pyi | 123 +- mypy/typeshed/stdlib/_decimal.pyi | 176 +-- mypy/typeshed/stdlib/_heapq.pyi | 10 +- mypy/typeshed/stdlib/_imp.pyi | 22 +- mypy/typeshed/stdlib/_locale.pyi | 20 +- mypy/typeshed/stdlib/_msi.pyi | 6 +- mypy/typeshed/stdlib/_operator.pyi | 130 +- mypy/typeshed/stdlib/_posixsubprocess.pyi | 47 +- mypy/typeshed/stdlib/_py_abc.pyi | 2 +- mypy/typeshed/stdlib/_random.pyi | 6 +- mypy/typeshed/stdlib/_socket.pyi | 99 +- mypy/typeshed/stdlib/_thread.pyi | 6 +- mypy/typeshed/stdlib/_tkinter.pyi | 73 +- mypy/typeshed/stdlib/_tracemalloc.pyi | 4 +- mypy/typeshed/stdlib/_typeshed/__init__.pyi | 50 +- mypy/typeshed/stdlib/_typeshed/dbapi.pyi | 12 +- mypy/typeshed/stdlib/_typeshed/wsgi.pyi | 16 +- mypy/typeshed/stdlib/_typeshed/xml.pyi | 6 +- mypy/typeshed/stdlib/_weakref.pyi | 16 +- mypy/typeshed/stdlib/_winapi.pyi | 98 +- mypy/typeshed/stdlib/abc.pyi | 2 +- mypy/typeshed/stdlib/argparse.pyi | 2 +- mypy/typeshed/stdlib/array.pyi | 74 +- mypy/typeshed/stdlib/asyncio/events.pyi | 6 +- mypy/typeshed/stdlib/asyncio/futures.pyi | 8 +- mypy/typeshed/stdlib/asyncio/tasks.pyi | 176 +-- mypy/typeshed/stdlib/asyncio/threads.pyi | 2 +- mypy/typeshed/stdlib/asyncio/trsock.pyi | 12 +- mypy/typeshed/stdlib/asyncio/unix_events.pyi | 40 +- mypy/typeshed/stdlib/audioop.pyi | 67 +- mypy/typeshed/stdlib/bdb.pyi | 2 +- mypy/typeshed/stdlib/binascii.pyi | 26 +- mypy/typeshed/stdlib/builtins.pyi | 1192 +++++++++-------- mypy/typeshed/stdlib/bz2.pyi | 4 +- mypy/typeshed/stdlib/cProfile.pyi | 2 +- mypy/typeshed/stdlib/cgi.pyi | 2 +- mypy/typeshed/stdlib/cmath.pyi | 44 +- mypy/typeshed/stdlib/codecs.pyi | 16 +- mypy/typeshed/stdlib/collections/__init__.pyi | 138 +- mypy/typeshed/stdlib/compileall.pyi | 2 +- .../stdlib/concurrent/futures/_base.pyi | 16 +- mypy/typeshed/stdlib/contextlib.pyi | 14 +- mypy/typeshed/stdlib/contextvars.pyi | 18 +- mypy/typeshed/stdlib/curses/__init__.pyi | 2 +- mypy/typeshed/stdlib/curses/panel.pyi | 2 +- mypy/typeshed/stdlib/dataclasses.pyi | 14 +- mypy/typeshed/stdlib/datetime.pyi | 116 +- mypy/typeshed/stdlib/dbm/gnu.pyi | 2 +- mypy/typeshed/stdlib/dbm/ndbm.pyi | 2 +- mypy/typeshed/stdlib/distutils/core.pyi | 2 +- mypy/typeshed/stdlib/email/charset.pyi | 2 +- mypy/typeshed/stdlib/email/header.pyi | 2 +- mypy/typeshed/stdlib/email/headerregistry.pyi | 4 +- mypy/typeshed/stdlib/email/message.pyi | 12 +- mypy/typeshed/stdlib/encodings/utf_8.pyi | 8 +- mypy/typeshed/stdlib/fcntl.pyi | 16 +- mypy/typeshed/stdlib/fractions.pyi | 2 +- mypy/typeshed/stdlib/functools.pyi | 18 +- mypy/typeshed/stdlib/gc.pyi | 6 +- mypy/typeshed/stdlib/gzip.pyi | 6 +- mypy/typeshed/stdlib/hashlib.pyi | 18 +- mypy/typeshed/stdlib/heapq.pyi | 2 +- mypy/typeshed/stdlib/hmac.pyi | 4 +- mypy/typeshed/stdlib/imghdr.pyi | 4 +- mypy/typeshed/stdlib/imp.pyi | 2 +- mypy/typeshed/stdlib/importlib/abc.pyi | 14 +- mypy/typeshed/stdlib/inspect.pyi | 6 +- mypy/typeshed/stdlib/io.pyi | 64 +- mypy/typeshed/stdlib/itertools.pyi | 108 +- mypy/typeshed/stdlib/json/encoder.pyi | 2 + mypy/typeshed/stdlib/lib2to3/fixer_base.pyi | 2 +- mypy/typeshed/stdlib/logging/__init__.pyi | 9 +- mypy/typeshed/stdlib/logging/handlers.pyi | 2 +- mypy/typeshed/stdlib/lzma.pyi | 4 +- mypy/typeshed/stdlib/marshal.pyi | 8 +- mypy/typeshed/stdlib/math.pyi | 112 +- mypy/typeshed/stdlib/mmap.pyi | 16 +- mypy/typeshed/stdlib/msvcrt.pyi | 18 +- .../stdlib/multiprocessing/context.pyi | 12 +- .../stdlib/multiprocessing/dummy/__init__.pyi | 4 +- .../stdlib/multiprocessing/managers.pyi | 70 +- .../stdlib/multiprocessing/queues.pyi | 2 +- .../stdlib/multiprocessing/sharedctypes.pyi | 10 +- .../stdlib/multiprocessing/synchronize.pyi | 4 +- mypy/typeshed/stdlib/ntpath.pyi | 6 +- mypy/typeshed/stdlib/opcode.pyi | 2 +- mypy/typeshed/stdlib/optparse.pyi | 113 +- mypy/typeshed/stdlib/os/__init__.pyi | 160 +-- mypy/typeshed/stdlib/pathlib.pyi | 4 +- mypy/typeshed/stdlib/pickle.pyi | 13 +- mypy/typeshed/stdlib/posixpath.pyi | 6 +- mypy/typeshed/stdlib/profile.pyi | 2 +- mypy/typeshed/stdlib/pstats.pyi | 3 +- mypy/typeshed/stdlib/pwd.pyi | 4 +- mypy/typeshed/stdlib/pyexpat/__init__.pyi | 14 +- mypy/typeshed/stdlib/re.pyi | 22 +- mypy/typeshed/stdlib/readline.pyi | 34 +- mypy/typeshed/stdlib/resource.pyi | 10 +- mypy/typeshed/stdlib/select.pyi | 15 +- mypy/typeshed/stdlib/signal.pyi | 30 +- mypy/typeshed/stdlib/smtplib.pyi | 4 +- mypy/typeshed/stdlib/socket.pyi | 8 +- mypy/typeshed/stdlib/spwd.pyi | 2 +- mypy/typeshed/stdlib/sqlite3/dbapi2.pyi | 175 ++- mypy/typeshed/stdlib/ssl.pyi | 20 +- mypy/typeshed/stdlib/statistics.pyi | 10 +- mypy/typeshed/stdlib/string.pyi | 8 +- mypy/typeshed/stdlib/struct.pyi | 16 +- mypy/typeshed/stdlib/sys/__init__.pyi | 34 +- mypy/typeshed/stdlib/sys/_monitoring.pyi | 16 +- mypy/typeshed/stdlib/syslog.pyi | 6 +- mypy/typeshed/stdlib/tarfile.pyi | 6 +- mypy/typeshed/stdlib/tempfile.pyi | 8 +- mypy/typeshed/stdlib/termios.pyi | 16 +- mypy/typeshed/stdlib/tkinter/__init__.pyi | 152 ++- mypy/typeshed/stdlib/tkinter/dnd.pyi | 2 +- mypy/typeshed/stdlib/tkinter/font.pyi | 4 +- mypy/typeshed/stdlib/tkinter/ttk.pyi | 8 +- mypy/typeshed/stdlib/tomllib.pyi | 4 +- mypy/typeshed/stdlib/trace.pyi | 2 +- mypy/typeshed/stdlib/traceback.pyi | 14 +- mypy/typeshed/stdlib/types.pyi | 191 +-- mypy/typeshed/stdlib/typing.pyi | 109 +- mypy/typeshed/stdlib/typing_extensions.pyi | 36 +- mypy/typeshed/stdlib/unicodedata.pyi | 68 +- mypy/typeshed/stdlib/unittest/async_case.pyi | 2 +- mypy/typeshed/stdlib/unittest/case.pyi | 6 +- mypy/typeshed/stdlib/unittest/main.pyi | 2 +- mypy/typeshed/stdlib/unittest/mock.pyi | 6 +- mypy/typeshed/stdlib/urllib/request.pyi | 3 +- mypy/typeshed/stdlib/weakref.pyi | 7 +- mypy/typeshed/stdlib/winreg.pyi | 38 +- mypy/typeshed/stdlib/wsgiref/types.pyi | 16 +- .../typeshed/stdlib/xml/etree/ElementTree.pyi | 36 +- mypy/typeshed/stdlib/xmlrpc/server.pyi | 8 +- mypy/typeshed/stdlib/xxlimited.pyi | 4 +- mypy/typeshed/stdlib/zipfile/__init__.pyi | 10 +- mypy/typeshed/stdlib/zlib.pyi | 10 +- mypy/typeshed/stdlib/zoneinfo/__init__.pyi | 12 +- 143 files changed, 2703 insertions(+), 2458 deletions(-) diff --git a/mypy/typeshed/stdlib/_codecs.pyi b/mypy/typeshed/stdlib/_codecs.pyi index 6de4666e0776..ecf874d33ddd 100644 --- a/mypy/typeshed/stdlib/_codecs.pyi +++ b/mypy/typeshed/stdlib/_codecs.pyi @@ -13,13 +13,13 @@ _CharMap: TypeAlias = dict[int, int] | _EncodingMap _Handler: TypeAlias = Callable[[UnicodeError], tuple[str | bytes, int]] _SearchFunction: TypeAlias = Callable[[str], codecs.CodecInfo | None] -def register(__search_function: _SearchFunction) -> None: ... +def register(search_function: _SearchFunction, /) -> None: ... if sys.version_info >= (3, 10): - def unregister(__search_function: _SearchFunction) -> None: ... + def unregister(search_function: _SearchFunction, /) -> None: ... -def register_error(__errors: str, __handler: _Handler) -> None: ... -def lookup_error(__name: str) -> _Handler: ... +def register_error(errors: str, handler: _Handler, /) -> None: ... +def lookup_error(name: str, /) -> _Handler: ... # The type ignore on `encode` and `decode` is to avoid issues with overlapping overloads, for more details, see #300 # https://docs.python.org/3/library/codecs.html#binary-transforms @@ -68,66 +68,66 @@ def decode( def decode(obj: str, encoding: Literal["hex", "hex_codec"], errors: str = "strict") -> bytes: ... @overload def decode(obj: ReadableBuffer, encoding: str = "utf-8", errors: str = "strict") -> str: ... -def lookup(__encoding: str) -> codecs.CodecInfo: ... -def charmap_build(__map: str) -> _CharMap: ... -def ascii_decode(__data: ReadableBuffer, __errors: str | None = None) -> tuple[str, int]: ... -def ascii_encode(__str: str, __errors: str | None = None) -> tuple[bytes, int]: ... -def charmap_decode(__data: ReadableBuffer, __errors: str | None = None, __mapping: _CharMap | None = None) -> tuple[str, int]: ... -def charmap_encode(__str: str, __errors: str | None = None, __mapping: _CharMap | None = None) -> tuple[bytes, int]: ... -def escape_decode(__data: str | ReadableBuffer, __errors: str | None = None) -> tuple[str, int]: ... -def escape_encode(__data: bytes, __errors: str | None = None) -> tuple[bytes, int]: ... -def latin_1_decode(__data: ReadableBuffer, __errors: str | None = None) -> tuple[str, int]: ... -def latin_1_encode(__str: str, __errors: str | None = None) -> tuple[bytes, int]: ... +def lookup(encoding: str, /) -> codecs.CodecInfo: ... +def charmap_build(map: str, /) -> _CharMap: ... +def ascii_decode(data: ReadableBuffer, errors: str | None = None, /) -> tuple[str, int]: ... +def ascii_encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ... +def charmap_decode(data: ReadableBuffer, errors: str | None = None, mapping: _CharMap | None = None, /) -> tuple[str, int]: ... +def charmap_encode(str: str, errors: str | None = None, mapping: _CharMap | None = None, /) -> tuple[bytes, int]: ... +def escape_decode(data: str | ReadableBuffer, errors: str | None = None, /) -> tuple[str, int]: ... +def escape_encode(data: bytes, errors: str | None = None, /) -> tuple[bytes, int]: ... +def latin_1_decode(data: ReadableBuffer, errors: str | None = None, /) -> tuple[str, int]: ... +def latin_1_encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ... if sys.version_info >= (3, 9): def raw_unicode_escape_decode( - __data: str | ReadableBuffer, __errors: str | None = None, __final: bool = True + data: str | ReadableBuffer, errors: str | None = None, final: bool = True, / ) -> tuple[str, int]: ... else: - def raw_unicode_escape_decode(__data: str | ReadableBuffer, __errors: str | None = None) -> tuple[str, int]: ... + def raw_unicode_escape_decode(data: str | ReadableBuffer, errors: str | None = None, /) -> tuple[str, int]: ... -def raw_unicode_escape_encode(__str: str, __errors: str | None = None) -> tuple[bytes, int]: ... -def readbuffer_encode(__data: str | ReadableBuffer, __errors: str | None = None) -> tuple[bytes, int]: ... +def raw_unicode_escape_encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ... +def readbuffer_encode(data: str | ReadableBuffer, errors: str | None = None, /) -> tuple[bytes, int]: ... if sys.version_info >= (3, 9): def unicode_escape_decode( - __data: str | ReadableBuffer, __errors: str | None = None, __final: bool = True + data: str | ReadableBuffer, errors: str | None = None, final: bool = True, / ) -> tuple[str, int]: ... else: - def unicode_escape_decode(__data: str | ReadableBuffer, __errors: str | None = None) -> tuple[str, int]: ... + def unicode_escape_decode(data: str | ReadableBuffer, errors: str | None = None, /) -> tuple[str, int]: ... -def unicode_escape_encode(__str: str, __errors: str | None = None) -> tuple[bytes, int]: ... -def utf_16_be_decode(__data: ReadableBuffer, __errors: str | None = None, __final: bool = False) -> tuple[str, int]: ... -def utf_16_be_encode(__str: str, __errors: str | None = None) -> tuple[bytes, int]: ... -def utf_16_decode(__data: ReadableBuffer, __errors: str | None = None, __final: bool = False) -> tuple[str, int]: ... -def utf_16_encode(__str: str, __errors: str | None = None, __byteorder: int = 0) -> tuple[bytes, int]: ... +def unicode_escape_encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ... +def utf_16_be_decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ... +def utf_16_be_encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ... +def utf_16_decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ... +def utf_16_encode(str: str, errors: str | None = None, byteorder: int = 0, /) -> tuple[bytes, int]: ... def utf_16_ex_decode( - __data: ReadableBuffer, __errors: str | None = None, __byteorder: int = 0, __final: bool = False + data: ReadableBuffer, errors: str | None = None, byteorder: int = 0, final: bool = False, / ) -> tuple[str, int, int]: ... -def utf_16_le_decode(__data: ReadableBuffer, __errors: str | None = None, __final: bool = False) -> tuple[str, int]: ... -def utf_16_le_encode(__str: str, __errors: str | None = None) -> tuple[bytes, int]: ... -def utf_32_be_decode(__data: ReadableBuffer, __errors: str | None = None, __final: bool = False) -> tuple[str, int]: ... -def utf_32_be_encode(__str: str, __errors: str | None = None) -> tuple[bytes, int]: ... -def utf_32_decode(__data: ReadableBuffer, __errors: str | None = None, __final: bool = False) -> tuple[str, int]: ... -def utf_32_encode(__str: str, __errors: str | None = None, __byteorder: int = 0) -> tuple[bytes, int]: ... +def utf_16_le_decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ... +def utf_16_le_encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ... +def utf_32_be_decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ... +def utf_32_be_encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ... +def utf_32_decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ... +def utf_32_encode(str: str, errors: str | None = None, byteorder: int = 0, /) -> tuple[bytes, int]: ... def utf_32_ex_decode( - __data: ReadableBuffer, __errors: str | None = None, __byteorder: int = 0, __final: bool = False + data: ReadableBuffer, errors: str | None = None, byteorder: int = 0, final: bool = False, / ) -> tuple[str, int, int]: ... -def utf_32_le_decode(__data: ReadableBuffer, __errors: str | None = None, __final: bool = False) -> tuple[str, int]: ... -def utf_32_le_encode(__str: str, __errors: str | None = None) -> tuple[bytes, int]: ... -def utf_7_decode(__data: ReadableBuffer, __errors: str | None = None, __final: bool = False) -> tuple[str, int]: ... -def utf_7_encode(__str: str, __errors: str | None = None) -> tuple[bytes, int]: ... -def utf_8_decode(__data: ReadableBuffer, __errors: str | None = None, __final: bool = False) -> tuple[str, int]: ... -def utf_8_encode(__str: str, __errors: str | None = None) -> tuple[bytes, int]: ... +def utf_32_le_decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ... +def utf_32_le_encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ... +def utf_7_decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ... +def utf_7_encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ... +def utf_8_decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ... +def utf_8_encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ... if sys.platform == "win32": - def mbcs_decode(__data: ReadableBuffer, __errors: str | None = None, __final: bool = False) -> tuple[str, int]: ... - def mbcs_encode(__str: str, __errors: str | None = None) -> tuple[bytes, int]: ... + def mbcs_decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ... + def mbcs_encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ... def code_page_decode( - __codepage: int, __data: ReadableBuffer, __errors: str | None = None, __final: bool = False + codepage: int, data: ReadableBuffer, errors: str | None = None, final: bool = False, / ) -> tuple[str, int]: ... - def code_page_encode(__code_page: int, __str: str, __errors: str | None = None) -> tuple[bytes, int]: ... - def oem_decode(__data: ReadableBuffer, __errors: str | None = None, __final: bool = False) -> tuple[str, int]: ... - def oem_encode(__str: str, __errors: str | None = None) -> tuple[bytes, int]: ... + def code_page_encode(code_page: int, str: str, errors: str | None = None, /) -> tuple[bytes, int]: ... + def oem_decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ... + def oem_encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ... diff --git a/mypy/typeshed/stdlib/_collections_abc.pyi b/mypy/typeshed/stdlib/_collections_abc.pyi index 0aa09967a895..e467d626e8a8 100644 --- a/mypy/typeshed/stdlib/_collections_abc.pyi +++ b/mypy/typeshed/stdlib/_collections_abc.pyi @@ -69,7 +69,7 @@ _VT_co = TypeVar("_VT_co", covariant=True) # Value type covariant containers. @final class dict_keys(KeysView[_KT_co], Generic[_KT_co, _VT_co]): # undocumented - def __eq__(self, __value: object) -> bool: ... + def __eq__(self, value: object, /) -> bool: ... if sys.version_info >= (3, 10): @property def mapping(self) -> MappingProxyType[_KT_co, _VT_co]: ... @@ -82,7 +82,7 @@ class dict_values(ValuesView[_VT_co], Generic[_KT_co, _VT_co]): # undocumented @final class dict_items(ItemsView[_KT_co, _VT_co]): # undocumented - def __eq__(self, __value: object) -> bool: ... + def __eq__(self, value: object, /) -> bool: ... if sys.version_info >= (3, 10): @property def mapping(self) -> MappingProxyType[_KT_co, _VT_co]: ... @@ -91,4 +91,4 @@ if sys.version_info >= (3, 12): @runtime_checkable class Buffer(Protocol): @abstractmethod - def __buffer__(self, __flags: int) -> memoryview: ... + def __buffer__(self, flags: int, /) -> memoryview: ... diff --git a/mypy/typeshed/stdlib/_compression.pyi b/mypy/typeshed/stdlib/_compression.pyi index 24e11261140b..a41a8142cc3a 100644 --- a/mypy/typeshed/stdlib/_compression.pyi +++ b/mypy/typeshed/stdlib/_compression.pyi @@ -6,9 +6,9 @@ from typing import Any, Protocol BUFFER_SIZE = DEFAULT_BUFFER_SIZE class _Reader(Protocol): - def read(self, __n: int) -> bytes: ... + def read(self, n: int, /) -> bytes: ... def seekable(self) -> bool: ... - def seek(self, __n: int) -> Any: ... + def seek(self, n: int, /) -> Any: ... class BaseStream(BufferedIOBase): ... diff --git a/mypy/typeshed/stdlib/_ctypes.pyi b/mypy/typeshed/stdlib/_ctypes.pyi index e0cc87814609..60bbc51d9411 100644 --- a/mypy/typeshed/stdlib/_ctypes.pyi +++ b/mypy/typeshed/stdlib/_ctypes.pyi @@ -44,8 +44,8 @@ if sys.platform == "win32": def FormatError(code: int = ...) -> str: ... def get_last_error() -> int: ... def set_last_error(value: int) -> int: ... - def LoadLibrary(__name: str, __load_flags: int = 0) -> int: ... - def FreeLibrary(__handle: int) -> None: ... + def LoadLibrary(name: str, load_flags: int = 0, /) -> int: ... + def FreeLibrary(handle: int, /) -> None: ... class _CDataMeta(type): # By default mypy complains about the following two methods, because strictly speaking cls @@ -75,8 +75,8 @@ class _CData(metaclass=_CDataMeta): def from_param(cls, obj: Any) -> Self | _CArgObject: ... @classmethod def in_dll(cls, library: CDLL, name: str) -> Self: ... - def __buffer__(self, __flags: int) -> memoryview: ... - def __release_buffer__(self, __buffer: memoryview) -> None: ... + def __buffer__(self, flags: int, /) -> memoryview: ... + def __release_buffer__(self, buffer: memoryview, /) -> None: ... class _SimpleCData(_CData, Generic[_T]): value: _T @@ -95,13 +95,13 @@ class _Pointer(_PointerLike, _CData, Generic[_CT]): @overload def __init__(self, arg: _CT) -> None: ... @overload - def __getitem__(self, __key: int) -> Any: ... + def __getitem__(self, key: int, /) -> Any: ... @overload - def __getitem__(self, __key: slice) -> list[Any]: ... - def __setitem__(self, __key: int, __value: Any) -> None: ... + def __getitem__(self, key: slice, /) -> list[Any]: ... + def __setitem__(self, key: int, value: Any, /) -> None: ... def POINTER(type: type[_CT]) -> type[_Pointer[_CT]]: ... -def pointer(__arg: _CT) -> _Pointer[_CT]: ... +def pointer(arg: _CT, /) -> _Pointer[_CT]: ... class _CArgObject: ... @@ -119,15 +119,15 @@ class CFuncPtr(_PointerLike, _CData): @overload def __init__(self) -> None: ... @overload - def __init__(self, __address: int) -> None: ... + def __init__(self, address: int, /) -> None: ... @overload - def __init__(self, __callable: Callable[..., Any]) -> None: ... + def __init__(self, callable: Callable[..., Any], /) -> None: ... @overload - def __init__(self, __func_spec: tuple[str | int, CDLL], __paramflags: tuple[_PF, ...] | None = ...) -> None: ... + def __init__(self, func_spec: tuple[str | int, CDLL], paramflags: tuple[_PF, ...] | None = ..., /) -> None: ... if sys.platform == "win32": @overload def __init__( - self, __vtbl_index: int, __name: str, __paramflags: tuple[_PF, ...] | None = ..., __iid: _CData | None = ... + self, vtbl_index: int, name: str, paramflags: tuple[_PF, ...] | None = ..., iid: _CData | None = ..., / ) -> None: ... def __call__(self, *args: Any, **kwargs: Any) -> Any: ... @@ -139,10 +139,10 @@ class _CField(Generic[_CT, _GetT, _SetT]): offset: int size: int @overload - def __get__(self, __instance: None, __owner: type[Any] | None) -> Self: ... + def __get__(self, instance: None, owner: type[Any] | None, /) -> Self: ... @overload - def __get__(self, __instance: Any, __owner: type[Any] | None) -> _GetT: ... - def __set__(self, __instance: Any, __value: _SetT) -> None: ... + def __get__(self, instance: Any, owner: type[Any] | None, /) -> _GetT: ... + def __set__(self, instance: Any, value: _SetT, /) -> None: ... class _StructUnionMeta(_CDataMeta): _fields_: Sequence[tuple[str, type[_CData]] | tuple[str, type[_CData], int]] @@ -169,7 +169,11 @@ class Array(_CData, Generic[_CT]): def _type_(self) -> type[_CT]: ... @_type_.setter def _type_(self, value: type[_CT]) -> None: ... - raw: bytes # Note: only available if _CT == c_char + # Note: only available if _CT == c_char + @property + def raw(self) -> bytes: ... + @raw.setter + def raw(self, value: ReadableBuffer) -> None: ... value: Any # Note: bytes if _CT == c_char, str if _CT == c_wchar, unavailable otherwise # TODO These methods cannot be annotated correctly at the moment. # All of these "Any"s stand for the array's element type, but it's not possible to use _CT @@ -185,13 +189,13 @@ class Array(_CData, Generic[_CT]): # the array element type would belong are annotated with Any instead. def __init__(self, *args: Any) -> None: ... @overload - def __getitem__(self, __key: int) -> Any: ... + def __getitem__(self, key: int, /) -> Any: ... @overload - def __getitem__(self, __key: slice) -> list[Any]: ... + def __getitem__(self, key: slice, /) -> list[Any]: ... @overload - def __setitem__(self, __key: int, __value: Any) -> None: ... + def __setitem__(self, key: int, value: Any, /) -> None: ... @overload - def __setitem__(self, __key: slice, __value: Iterable[Any]) -> None: ... + def __setitem__(self, key: slice, value: Iterable[Any], /) -> None: ... def __iter__(self) -> Iterator[Any]: ... # Can't inherit from Sized because the metaclass conflict between # Sized and _CData prevents using _CDataMeta. diff --git a/mypy/typeshed/stdlib/_curses.pyi b/mypy/typeshed/stdlib/_curses.pyi index 20189cb285c5..929c6f8f3bc8 100644 --- a/mypy/typeshed/stdlib/_curses.pyi +++ b/mypy/typeshed/stdlib/_curses.pyi @@ -275,15 +275,15 @@ if sys.platform != "win32": def baudrate() -> int: ... def beep() -> None: ... def can_change_color() -> bool: ... - def cbreak(__flag: bool = True) -> None: ... - def color_content(__color_number: int) -> tuple[int, int, int]: ... - def color_pair(__pair_number: int) -> int: ... - def curs_set(__visibility: int) -> int: ... + def cbreak(flag: bool = True, /) -> None: ... + def color_content(color_number: int, /) -> tuple[int, int, int]: ... + def color_pair(pair_number: int, /) -> int: ... + def curs_set(visibility: int, /) -> int: ... def def_prog_mode() -> None: ... def def_shell_mode() -> None: ... - def delay_output(__ms: int) -> None: ... + def delay_output(ms: int, /) -> None: ... def doupdate() -> None: ... - def echo(__flag: bool = True) -> None: ... + def echo(flag: bool = True, /) -> None: ... def endwin() -> None: ... def erasechar() -> bytes: ... def filter() -> None: ... @@ -295,82 +295,83 @@ if sys.platform != "win32": def getmouse() -> tuple[int, int, int, int, int]: ... def getsyx() -> tuple[int, int]: ... - def getwin(__file: SupportsRead[bytes]) -> _CursesWindow: ... - def halfdelay(__tenths: int) -> None: ... + def getwin(file: SupportsRead[bytes], /) -> _CursesWindow: ... + def halfdelay(tenths: int, /) -> None: ... def has_colors() -> bool: ... if sys.version_info >= (3, 10): def has_extended_color_support() -> bool: ... def has_ic() -> bool: ... def has_il() -> bool: ... - def has_key(__key: int) -> bool: ... - def init_color(__color_number: int, __r: int, __g: int, __b: int) -> None: ... - def init_pair(__pair_number: int, __fg: int, __bg: int) -> None: ... + def has_key(key: int, /) -> bool: ... + def init_color(color_number: int, r: int, g: int, b: int, /) -> None: ... + def init_pair(pair_number: int, fg: int, bg: int, /) -> None: ... def initscr() -> _CursesWindow: ... - def intrflush(__flag: bool) -> None: ... - def is_term_resized(__nlines: int, __ncols: int) -> bool: ... + def intrflush(flag: bool, /) -> None: ... + def is_term_resized(nlines: int, ncols: int, /) -> bool: ... def isendwin() -> bool: ... - def keyname(__key: int) -> bytes: ... + def keyname(key: int, /) -> bytes: ... def killchar() -> bytes: ... def longname() -> bytes: ... - def meta(__yes: bool) -> None: ... - def mouseinterval(__interval: int) -> None: ... - def mousemask(__newmask: int) -> tuple[int, int]: ... - def napms(__ms: int) -> int: ... - def newpad(__nlines: int, __ncols: int) -> _CursesWindow: ... - def newwin(__nlines: int, __ncols: int, __begin_y: int = ..., __begin_x: int = ...) -> _CursesWindow: ... - def nl(__flag: bool = True) -> None: ... + def meta(yes: bool, /) -> None: ... + def mouseinterval(interval: int, /) -> None: ... + def mousemask(newmask: int, /) -> tuple[int, int]: ... + def napms(ms: int, /) -> int: ... + def newpad(nlines: int, ncols: int, /) -> _CursesWindow: ... + def newwin(nlines: int, ncols: int, begin_y: int = ..., begin_x: int = ..., /) -> _CursesWindow: ... + def nl(flag: bool = True, /) -> None: ... def nocbreak() -> None: ... def noecho() -> None: ... def nonl() -> None: ... def noqiflush() -> None: ... def noraw() -> None: ... - def pair_content(__pair_number: int) -> tuple[int, int]: ... - def pair_number(__attr: int) -> int: ... - def putp(__string: ReadOnlyBuffer) -> None: ... - def qiflush(__flag: bool = True) -> None: ... - def raw(__flag: bool = True) -> None: ... + def pair_content(pair_number: int, /) -> tuple[int, int]: ... + def pair_number(attr: int, /) -> int: ... + def putp(string: ReadOnlyBuffer, /) -> None: ... + def qiflush(flag: bool = True, /) -> None: ... + def raw(flag: bool = True, /) -> None: ... def reset_prog_mode() -> None: ... def reset_shell_mode() -> None: ... def resetty() -> None: ... - def resize_term(__nlines: int, __ncols: int) -> None: ... - def resizeterm(__nlines: int, __ncols: int) -> None: ... + def resize_term(nlines: int, ncols: int, /) -> None: ... + def resizeterm(nlines: int, ncols: int, /) -> None: ... def savetty() -> None: ... if sys.version_info >= (3, 9): - def set_escdelay(__ms: int) -> None: ... - def set_tabsize(__size: int) -> None: ... + def set_escdelay(ms: int, /) -> None: ... + def set_tabsize(size: int, /) -> None: ... - def setsyx(__y: int, __x: int) -> None: ... + def setsyx(y: int, x: int, /) -> None: ... def setupterm(term: str | None = None, fd: int = -1) -> None: ... def start_color() -> None: ... def termattrs() -> int: ... def termname() -> bytes: ... - def tigetflag(__capname: str) -> int: ... - def tigetnum(__capname: str) -> int: ... - def tigetstr(__capname: str) -> bytes | None: ... + def tigetflag(capname: str, /) -> int: ... + def tigetnum(capname: str, /) -> int: ... + def tigetstr(capname: str, /) -> bytes | None: ... def tparm( - __str: ReadOnlyBuffer, - __i1: int = 0, - __i2: int = 0, - __i3: int = 0, - __i4: int = 0, - __i5: int = 0, - __i6: int = 0, - __i7: int = 0, - __i8: int = 0, - __i9: int = 0, + str: ReadOnlyBuffer, + i1: int = 0, + i2: int = 0, + i3: int = 0, + i4: int = 0, + i5: int = 0, + i6: int = 0, + i7: int = 0, + i8: int = 0, + i9: int = 0, + /, ) -> bytes: ... - def typeahead(__fd: int) -> None: ... - def unctrl(__ch: _ChType) -> bytes: ... + def typeahead(fd: int, /) -> None: ... + def unctrl(ch: _ChType, /) -> bytes: ... if sys.version_info < (3, 12) or sys.platform != "darwin": # The support for macos was dropped in 3.12 - def unget_wch(__ch: int | str) -> None: ... + def unget_wch(ch: int | str, /) -> None: ... - def ungetch(__ch: _ChType) -> None: ... - def ungetmouse(__id: int, __x: int, __y: int, __z: int, __bstate: int) -> None: ... + def ungetch(ch: _ChType, /) -> None: ... + def ungetmouse(id: int, x: int, y: int, z: int, bstate: int, /) -> None: ... def update_lines_cols() -> None: ... def use_default_colors() -> None: ... - def use_env(__flag: bool) -> None: ... + def use_env(flag: bool, /) -> None: ... class error(Exception): ... @@ -389,11 +390,11 @@ if sys.platform != "win32": def addstr(self, str: str, attr: int = ...) -> None: ... @overload def addstr(self, y: int, x: int, str: str, attr: int = ...) -> None: ... - 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 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 border( self, ls: _ChType = ..., @@ -431,8 +432,8 @@ if sys.platform != "win32": def derwin(self, begin_y: int, begin_x: int) -> _CursesWindow: ... @overload def derwin(self, nlines: int, ncols: int, begin_y: int, begin_x: int) -> _CursesWindow: ... - def echochar(self, __ch: _ChType, __attr: int = ...) -> None: ... - def enclose(self, __y: int, __x: int) -> bool: ... + def echochar(self, ch: _ChType, attr: int = ..., /) -> None: ... + def enclose(self, y: int, x: int, /) -> bool: ... def erase(self) -> None: ... def getbegyx(self) -> tuple[int, int]: ... def getbkgd(self) -> tuple[int, int]: ... @@ -491,7 +492,7 @@ if sys.platform != "win32": def instr(self, n: int = ...) -> bytes: ... @overload def instr(self, y: int, x: int, n: int = ...) -> bytes: ... - def is_linetouched(self, __line: int) -> bool: ... + def is_linetouched(self, line: int, /) -> bool: ... def is_wintouched(self) -> bool: ... def keypad(self, yes: bool) -> None: ... def leaveok(self, yes: bool) -> None: ... @@ -516,8 +517,8 @@ if sys.platform != "win32": def overwrite( self, destwin: _CursesWindow, sminrow: int, smincol: int, dminrow: int, dmincol: int, dmaxrow: int, dmaxcol: int ) -> None: ... - def putwin(self, __file: IO[Any]) -> None: ... - def redrawln(self, __beg: int, __num: int) -> None: ... + def putwin(self, file: IO[Any], /) -> None: ... + def redrawln(self, beg: int, num: int, /) -> None: ... def redrawwin(self) -> None: ... @overload def refresh(self) -> None: ... @@ -526,7 +527,7 @@ if sys.platform != "win32": def resize(self, nlines: int, ncols: int) -> None: ... def scroll(self, lines: int = ...) -> None: ... def scrollok(self, flag: bool) -> None: ... - def setscrreg(self, __top: int, __bottom: int) -> None: ... + def setscrreg(self, top: int, bottom: int, /) -> None: ... def standend(self) -> None: ... def standout(self) -> None: ... @overload diff --git a/mypy/typeshed/stdlib/_decimal.pyi b/mypy/typeshed/stdlib/_decimal.pyi index 369d04cd2d5d..90d16215c280 100644 --- a/mypy/typeshed/stdlib/_decimal.pyi +++ b/mypy/typeshed/stdlib/_decimal.pyi @@ -47,7 +47,7 @@ class Overflow(Inexact, Rounded): ... class Underflow(Inexact, Rounded, Subnormal): ... class FloatOperation(DecimalException, TypeError): ... -def setcontext(__context: Context) -> None: ... +def setcontext(context: Context, /) -> None: ... def getcontext() -> Context: ... if sys.version_info >= (3, 11): @@ -70,7 +70,7 @@ else: class Decimal: def __new__(cls, value: _DecimalNew = ..., context: Context | None = ...) -> Self: ... @classmethod - def from_float(cls, __f: float) -> Self: ... + def from_float(cls, f: float, /) -> Self: ... def __bool__(self) -> bool: ... def compare(self, other: _Decimal, context: Context | None = None) -> Decimal: ... def __hash__(self) -> int: ... @@ -78,28 +78,28 @@ class Decimal: def as_integer_ratio(self) -> tuple[int, int]: ... def to_eng_string(self, context: Context | None = None) -> str: ... def __abs__(self) -> Decimal: ... - def __add__(self, __value: _Decimal) -> Decimal: ... - def __divmod__(self, __value: _Decimal) -> tuple[Decimal, Decimal]: ... - def __eq__(self, __value: object) -> bool: ... - def __floordiv__(self, __value: _Decimal) -> Decimal: ... - def __ge__(self, __value: _ComparableNum) -> bool: ... - def __gt__(self, __value: _ComparableNum) -> bool: ... - def __le__(self, __value: _ComparableNum) -> bool: ... - def __lt__(self, __value: _ComparableNum) -> bool: ... - def __mod__(self, __value: _Decimal) -> Decimal: ... - def __mul__(self, __value: _Decimal) -> Decimal: ... + def __add__(self, value: _Decimal, /) -> Decimal: ... + def __divmod__(self, value: _Decimal, /) -> tuple[Decimal, Decimal]: ... + def __eq__(self, value: object, /) -> bool: ... + def __floordiv__(self, value: _Decimal, /) -> Decimal: ... + def __ge__(self, value: _ComparableNum, /) -> bool: ... + def __gt__(self, value: _ComparableNum, /) -> bool: ... + def __le__(self, value: _ComparableNum, /) -> bool: ... + def __lt__(self, value: _ComparableNum, /) -> bool: ... + def __mod__(self, value: _Decimal, /) -> Decimal: ... + def __mul__(self, value: _Decimal, /) -> Decimal: ... def __neg__(self) -> Decimal: ... def __pos__(self) -> Decimal: ... - def __pow__(self, __value: _Decimal, __mod: _Decimal | None = None) -> Decimal: ... - def __radd__(self, __value: _Decimal) -> Decimal: ... - def __rdivmod__(self, __value: _Decimal) -> tuple[Decimal, Decimal]: ... - def __rfloordiv__(self, __value: _Decimal) -> Decimal: ... - def __rmod__(self, __value: _Decimal) -> Decimal: ... - def __rmul__(self, __value: _Decimal) -> Decimal: ... - def __rsub__(self, __value: _Decimal) -> Decimal: ... - def __rtruediv__(self, __value: _Decimal) -> Decimal: ... - def __sub__(self, __value: _Decimal) -> Decimal: ... - def __truediv__(self, __value: _Decimal) -> Decimal: ... + def __pow__(self, value: _Decimal, mod: _Decimal | None = None, /) -> Decimal: ... + def __radd__(self, value: _Decimal, /) -> Decimal: ... + def __rdivmod__(self, value: _Decimal, /) -> tuple[Decimal, Decimal]: ... + def __rfloordiv__(self, value: _Decimal, /) -> Decimal: ... + def __rmod__(self, value: _Decimal, /) -> Decimal: ... + def __rmul__(self, value: _Decimal, /) -> Decimal: ... + def __rsub__(self, value: _Decimal, /) -> Decimal: ... + def __rtruediv__(self, value: _Decimal, /) -> Decimal: ... + def __sub__(self, value: _Decimal, /) -> Decimal: ... + def __truediv__(self, value: _Decimal, /) -> Decimal: ... def remainder_near(self, other: _Decimal, context: Context | None = None) -> Decimal: ... def __float__(self) -> float: ... def __int__(self) -> int: ... @@ -113,11 +113,11 @@ class Decimal: @overload def __round__(self) -> int: ... @overload - def __round__(self, __ndigits: int) -> Decimal: ... + def __round__(self, ndigits: int, /) -> Decimal: ... def __floor__(self) -> int: ... def __ceil__(self) -> int: ... def fma(self, other: _Decimal, third: _Decimal, context: Context | None = None) -> Decimal: ... - def __rpow__(self, __value: _Decimal, __mod: Context | None = None) -> Decimal: ... + def __rpow__(self, value: _Decimal, mod: Context | None = None, /) -> Decimal: ... def normalize(self, context: Context | None = None) -> Decimal: ... def quantize(self, exp: _Decimal, rounding: str | None = None, context: Context | None = None) -> Decimal: ... def same_quantum(self, other: _Decimal, context: Context | None = None) -> bool: ... @@ -165,8 +165,8 @@ class Decimal: def shift(self, other: _Decimal, context: Context | None = None) -> Decimal: ... def __reduce__(self) -> tuple[type[Self], tuple[str]]: ... def __copy__(self) -> Self: ... - def __deepcopy__(self, __memo: Any) -> Self: ... - def __format__(self, __specifier: str, __context: Context | None = ...) -> str: ... + def __deepcopy__(self, memo: Any, /) -> Self: ... + def __format__(self, specifier: str, context: Context | None = ..., /) -> str: ... class _ContextManager: new_context: Context @@ -182,7 +182,7 @@ class Context: # even settable attributes like `prec` and `rounding`, # but that's inexpressable in the stub. # Type checkers either ignore it or misinterpret it - # if you add a `def __delattr__(self, __name: str) -> NoReturn` method to the stub + # if you add a `def __delattr__(self, name: str, /) -> NoReturn` method to the stub prec: int rounding: str Emin: int @@ -212,69 +212,69 @@ class Context: __hash__: ClassVar[None] # type: ignore[assignment] def Etiny(self) -> int: ... def Etop(self) -> int: ... - def create_decimal(self, __num: _DecimalNew = "0") -> Decimal: ... - def create_decimal_from_float(self, __f: float) -> Decimal: ... - def abs(self, __x: _Decimal) -> Decimal: ... - def add(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def canonical(self, __x: Decimal) -> Decimal: ... - def compare(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def compare_signal(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def compare_total(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def compare_total_mag(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def copy_abs(self, __x: _Decimal) -> Decimal: ... - def copy_decimal(self, __x: _Decimal) -> Decimal: ... - def copy_negate(self, __x: _Decimal) -> Decimal: ... - def copy_sign(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def divide(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def divide_int(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def divmod(self, __x: _Decimal, __y: _Decimal) -> tuple[Decimal, Decimal]: ... - def exp(self, __x: _Decimal) -> Decimal: ... - def fma(self, __x: _Decimal, __y: _Decimal, __z: _Decimal) -> Decimal: ... - def is_canonical(self, __x: _Decimal) -> bool: ... - def is_finite(self, __x: _Decimal) -> bool: ... - def is_infinite(self, __x: _Decimal) -> bool: ... - def is_nan(self, __x: _Decimal) -> bool: ... - def is_normal(self, __x: _Decimal) -> bool: ... - def is_qnan(self, __x: _Decimal) -> bool: ... - def is_signed(self, __x: _Decimal) -> bool: ... - def is_snan(self, __x: _Decimal) -> bool: ... - def is_subnormal(self, __x: _Decimal) -> bool: ... - def is_zero(self, __x: _Decimal) -> bool: ... - def ln(self, __x: _Decimal) -> Decimal: ... - def log10(self, __x: _Decimal) -> Decimal: ... - def logb(self, __x: _Decimal) -> Decimal: ... - def logical_and(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def logical_invert(self, __x: _Decimal) -> Decimal: ... - def logical_or(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def logical_xor(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def max(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def max_mag(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def min(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def min_mag(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def minus(self, __x: _Decimal) -> Decimal: ... - def multiply(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def next_minus(self, __x: _Decimal) -> Decimal: ... - def next_plus(self, __x: _Decimal) -> Decimal: ... - def next_toward(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def normalize(self, __x: _Decimal) -> Decimal: ... - def number_class(self, __x: _Decimal) -> str: ... - def plus(self, __x: _Decimal) -> Decimal: ... + def create_decimal(self, num: _DecimalNew = "0", /) -> Decimal: ... + def create_decimal_from_float(self, f: float, /) -> Decimal: ... + def abs(self, x: _Decimal, /) -> Decimal: ... + def add(self, x: _Decimal, y: _Decimal, /) -> Decimal: ... + def canonical(self, x: Decimal, /) -> Decimal: ... + def compare(self, x: _Decimal, y: _Decimal, /) -> Decimal: ... + def compare_signal(self, x: _Decimal, y: _Decimal, /) -> Decimal: ... + def compare_total(self, x: _Decimal, y: _Decimal, /) -> Decimal: ... + def compare_total_mag(self, x: _Decimal, y: _Decimal, /) -> Decimal: ... + def copy_abs(self, x: _Decimal, /) -> Decimal: ... + def copy_decimal(self, x: _Decimal, /) -> Decimal: ... + def copy_negate(self, x: _Decimal, /) -> Decimal: ... + def copy_sign(self, x: _Decimal, y: _Decimal, /) -> Decimal: ... + def divide(self, x: _Decimal, y: _Decimal, /) -> Decimal: ... + def divide_int(self, x: _Decimal, y: _Decimal, /) -> Decimal: ... + def divmod(self, x: _Decimal, y: _Decimal, /) -> tuple[Decimal, Decimal]: ... + def exp(self, x: _Decimal, /) -> Decimal: ... + def fma(self, x: _Decimal, y: _Decimal, z: _Decimal, /) -> Decimal: ... + def is_canonical(self, x: _Decimal, /) -> bool: ... + def is_finite(self, x: _Decimal, /) -> bool: ... + def is_infinite(self, x: _Decimal, /) -> bool: ... + def is_nan(self, x: _Decimal, /) -> bool: ... + def is_normal(self, x: _Decimal, /) -> bool: ... + def is_qnan(self, x: _Decimal, /) -> bool: ... + def is_signed(self, x: _Decimal, /) -> bool: ... + def is_snan(self, x: _Decimal, /) -> bool: ... + def is_subnormal(self, x: _Decimal, /) -> bool: ... + def is_zero(self, x: _Decimal, /) -> bool: ... + def ln(self, x: _Decimal, /) -> Decimal: ... + def log10(self, x: _Decimal, /) -> Decimal: ... + def logb(self, x: _Decimal, /) -> Decimal: ... + def logical_and(self, x: _Decimal, y: _Decimal, /) -> Decimal: ... + def logical_invert(self, x: _Decimal, /) -> Decimal: ... + def logical_or(self, x: _Decimal, y: _Decimal, /) -> Decimal: ... + def logical_xor(self, x: _Decimal, y: _Decimal, /) -> Decimal: ... + def max(self, x: _Decimal, y: _Decimal, /) -> Decimal: ... + def max_mag(self, x: _Decimal, y: _Decimal, /) -> Decimal: ... + def min(self, x: _Decimal, y: _Decimal, /) -> Decimal: ... + def min_mag(self, x: _Decimal, y: _Decimal, /) -> Decimal: ... + def minus(self, x: _Decimal, /) -> Decimal: ... + def multiply(self, x: _Decimal, y: _Decimal, /) -> Decimal: ... + def next_minus(self, x: _Decimal, /) -> Decimal: ... + def next_plus(self, x: _Decimal, /) -> Decimal: ... + def next_toward(self, x: _Decimal, y: _Decimal, /) -> Decimal: ... + def normalize(self, x: _Decimal, /) -> Decimal: ... + def number_class(self, x: _Decimal, /) -> str: ... + def plus(self, x: _Decimal, /) -> Decimal: ... def power(self, a: _Decimal, b: _Decimal, modulo: _Decimal | None = None) -> Decimal: ... - def quantize(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... + def quantize(self, x: _Decimal, y: _Decimal, /) -> Decimal: ... def radix(self) -> Decimal: ... - def remainder(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def remainder_near(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def rotate(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def same_quantum(self, __x: _Decimal, __y: _Decimal) -> bool: ... - def scaleb(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def shift(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def sqrt(self, __x: _Decimal) -> Decimal: ... - def subtract(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def to_eng_string(self, __x: _Decimal) -> str: ... - def to_sci_string(self, __x: _Decimal) -> str: ... - def to_integral_exact(self, __x: _Decimal) -> Decimal: ... - def to_integral_value(self, __x: _Decimal) -> Decimal: ... - def to_integral(self, __x: _Decimal) -> Decimal: ... + def remainder(self, x: _Decimal, y: _Decimal, /) -> Decimal: ... + def remainder_near(self, x: _Decimal, y: _Decimal, /) -> Decimal: ... + def rotate(self, x: _Decimal, y: _Decimal, /) -> Decimal: ... + def same_quantum(self, x: _Decimal, y: _Decimal, /) -> bool: ... + def scaleb(self, x: _Decimal, y: _Decimal, /) -> Decimal: ... + def shift(self, x: _Decimal, y: _Decimal, /) -> Decimal: ... + def sqrt(self, x: _Decimal, /) -> Decimal: ... + def subtract(self, x: _Decimal, y: _Decimal, /) -> Decimal: ... + def to_eng_string(self, x: _Decimal, /) -> str: ... + def to_sci_string(self, x: _Decimal, /) -> str: ... + def to_integral_exact(self, x: _Decimal, /) -> Decimal: ... + def to_integral_value(self, x: _Decimal, /) -> Decimal: ... + def to_integral(self, x: _Decimal, /) -> Decimal: ... DefaultContext: Context BasicContext: Context diff --git a/mypy/typeshed/stdlib/_heapq.pyi b/mypy/typeshed/stdlib/_heapq.pyi index 28b03a75d4c7..9f731bf91eef 100644 --- a/mypy/typeshed/stdlib/_heapq.pyi +++ b/mypy/typeshed/stdlib/_heapq.pyi @@ -4,8 +4,8 @@ _T = TypeVar("_T") __about__: Final[str] -def heapify(__heap: list[Any]) -> 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: ... +def heapify(heap: list[Any], /) -> 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: ... diff --git a/mypy/typeshed/stdlib/_imp.pyi b/mypy/typeshed/stdlib/_imp.pyi index adab2e803efe..de3549a91da5 100644 --- a/mypy/typeshed/stdlib/_imp.pyi +++ b/mypy/typeshed/stdlib/_imp.pyi @@ -7,22 +7,22 @@ from typing import Any check_hash_based_pycs: str def source_hash(key: int, source: ReadableBuffer) -> bytes: ... -def create_builtin(__spec: ModuleSpec) -> types.ModuleType: ... -def create_dynamic(__spec: ModuleSpec, __file: Any = None) -> types.ModuleType: ... +def create_builtin(spec: ModuleSpec, /) -> types.ModuleType: ... +def create_dynamic(spec: ModuleSpec, file: Any = None, /) -> types.ModuleType: ... def acquire_lock() -> None: ... -def exec_builtin(__mod: types.ModuleType) -> int: ... -def exec_dynamic(__mod: types.ModuleType) -> int: ... +def exec_builtin(mod: types.ModuleType, /) -> int: ... +def exec_dynamic(mod: types.ModuleType, /) -> int: ... def extension_suffixes() -> list[str]: ... -def init_frozen(__name: str) -> types.ModuleType: ... -def is_builtin(__name: str) -> int: ... -def is_frozen(__name: str) -> bool: ... -def is_frozen_package(__name: str) -> bool: ... +def init_frozen(name: str, /) -> types.ModuleType: ... +def is_builtin(name: str, /) -> int: ... +def is_frozen(name: str, /) -> bool: ... +def is_frozen_package(name: str, /) -> bool: ... def lock_held() -> bool: ... def release_lock() -> None: ... if sys.version_info >= (3, 11): - def find_frozen(__name: str, *, withdata: bool = False) -> tuple[memoryview | None, bool, str | None] | None: ... - def get_frozen_object(__name: str, __data: ReadableBuffer | None = None) -> types.CodeType: ... + def find_frozen(name: str, /, *, withdata: bool = False) -> tuple[memoryview | None, bool, str | None] | None: ... + def get_frozen_object(name: str, data: ReadableBuffer | None = None, /) -> types.CodeType: ... else: - def get_frozen_object(__name: str) -> types.CodeType: ... + def get_frozen_object(name: str, /) -> types.CodeType: ... diff --git a/mypy/typeshed/stdlib/_locale.pyi b/mypy/typeshed/stdlib/_locale.pyi index d7399f15e1a3..0825e12034f4 100644 --- a/mypy/typeshed/stdlib/_locale.pyi +++ b/mypy/typeshed/stdlib/_locale.pyi @@ -10,14 +10,14 @@ LC_NUMERIC: int LC_ALL: int CHAR_MAX: int -def setlocale(__category: int, __locale: str | None = None) -> str: ... +def setlocale(category: int, locale: str | None = None, /) -> str: ... def localeconv() -> Mapping[str, int | str | list[int]]: ... if sys.version_info >= (3, 11): def getencoding() -> str: ... -def strcoll(__os1: str, __os2: str) -> int: ... -def strxfrm(__string: str) -> str: ... +def strcoll(os1: str, os2: str, /) -> int: ... +def strxfrm(string: str, /) -> str: ... # native gettext functions # https://docs.python.org/3/library/locale.html#access-to-message-catalogs @@ -87,14 +87,14 @@ if sys.platform != "win32": CRNCYSTR: int ALT_DIGITS: int - def nl_langinfo(__key: int) -> str: ... + def nl_langinfo(key: int, /) -> str: ... # This is dependent on `libintl.h` which is a part of `gettext` # system dependency. These functions might be missing. # But, we always say that they are present. - def gettext(__msg: str) -> str: ... - def dgettext(__domain: str | None, __msg: str) -> str: ... - def dcgettext(__domain: str | None, __msg: str, __category: int) -> str: ... - def textdomain(__domain: str | None) -> str: ... - def bindtextdomain(__domain: str, __dir: StrPath | None) -> str: ... - def bind_textdomain_codeset(__domain: str, __codeset: str | None) -> str | None: ... + def gettext(msg: str, /) -> str: ... + def dgettext(domain: str | None, msg: str, /) -> str: ... + def dcgettext(domain: str | None, msg: str, category: int, /) -> str: ... + def textdomain(domain: str | None, /) -> str: ... + def bindtextdomain(domain: str, dir: StrPath | None, /) -> str: ... + def bind_textdomain_codeset(domain: str, codeset: str | None, /) -> str | None: ... diff --git a/mypy/typeshed/stdlib/_msi.pyi b/mypy/typeshed/stdlib/_msi.pyi index 22239cbfff04..779fda3b67fe 100644 --- a/mypy/typeshed/stdlib/_msi.pyi +++ b/mypy/typeshed/stdlib/_msi.pyi @@ -47,9 +47,9 @@ if sys.platform == "win32": __init__: None # type: ignore[assignment] def UuidCreate() -> str: ... - def FCICreate(__cabname: str, __files: list[str]) -> None: ... - def OpenDatabase(__path: str, __persist: int) -> _Database: ... - def CreateRecord(__count: int) -> _Record: ... + def FCICreate(cabname: str, files: list[str], /) -> None: ... + def OpenDatabase(path: str, persist: int, /) -> _Database: ... + def CreateRecord(count: int, /) -> _Record: ... MSICOLINFO_NAMES: int MSICOLINFO_TYPES: int diff --git a/mypy/typeshed/stdlib/_operator.pyi b/mypy/typeshed/stdlib/_operator.pyi index 9b24e086adff..69ee563b5cf4 100644 --- a/mypy/typeshed/stdlib/_operator.pyi +++ b/mypy/typeshed/stdlib/_operator.pyi @@ -19,16 +19,16 @@ _Ts = TypeVarTuple("_Ts") # the numpy.array comparison dunders return another numpy.array. class _SupportsDunderLT(Protocol): - def __lt__(self, __other: Any) -> Any: ... + def __lt__(self, other: Any, /) -> Any: ... class _SupportsDunderGT(Protocol): - def __gt__(self, __other: Any) -> Any: ... + def __gt__(self, other: Any, /) -> Any: ... class _SupportsDunderLE(Protocol): - def __le__(self, __other: Any) -> Any: ... + def __le__(self, other: Any, /) -> Any: ... class _SupportsDunderGE(Protocol): - def __ge__(self, __other: Any) -> Any: ... + def __ge__(self, other: Any, /) -> Any: ... _SupportsComparison: TypeAlias = _SupportsDunderLE | _SupportsDunderGE | _SupportsDunderGT | _SupportsDunderLT @@ -42,56 +42,56 @@ class _SupportsPos(Protocol[_T_co]): def __pos__(self) -> _T_co: ... # All four comparison functions must have the same signature, or we get false-positive errors -def lt(__a: _SupportsComparison, __b: _SupportsComparison) -> Any: ... -def le(__a: _SupportsComparison, __b: _SupportsComparison) -> Any: ... -def eq(__a: object, __b: object) -> Any: ... -def ne(__a: object, __b: object) -> Any: ... -def ge(__a: _SupportsComparison, __b: _SupportsComparison) -> Any: ... -def gt(__a: _SupportsComparison, __b: _SupportsComparison) -> Any: ... -def not_(__a: object) -> bool: ... -def truth(__a: object) -> bool: ... -def is_(__a: object, __b: object) -> bool: ... -def is_not(__a: object, __b: object) -> bool: ... -def abs(__a: SupportsAbs[_T]) -> _T: ... -def add(__a: Any, __b: Any) -> Any: ... -def and_(__a: Any, __b: Any) -> Any: ... -def floordiv(__a: Any, __b: Any) -> Any: ... -def index(__a: SupportsIndex) -> int: ... -def inv(__a: _SupportsInversion[_T_co]) -> _T_co: ... -def invert(__a: _SupportsInversion[_T_co]) -> _T_co: ... -def lshift(__a: Any, __b: Any) -> Any: ... -def mod(__a: Any, __b: Any) -> Any: ... -def mul(__a: Any, __b: Any) -> Any: ... -def matmul(__a: Any, __b: Any) -> Any: ... -def neg(__a: _SupportsNeg[_T_co]) -> _T_co: ... -def or_(__a: Any, __b: Any) -> Any: ... -def pos(__a: _SupportsPos[_T_co]) -> _T_co: ... -def pow(__a: Any, __b: Any) -> Any: ... -def rshift(__a: Any, __b: Any) -> Any: ... -def sub(__a: Any, __b: Any) -> Any: ... -def truediv(__a: Any, __b: Any) -> Any: ... -def xor(__a: Any, __b: Any) -> Any: ... -def concat(__a: Sequence[_T], __b: Sequence[_T]) -> Sequence[_T]: ... -def contains(__a: Container[object], __b: object) -> bool: ... -def countOf(__a: Iterable[object], __b: object) -> int: ... +def lt(a: _SupportsComparison, b: _SupportsComparison, /) -> Any: ... +def le(a: _SupportsComparison, b: _SupportsComparison, /) -> Any: ... +def eq(a: object, b: object, /) -> Any: ... +def ne(a: object, b: object, /) -> Any: ... +def ge(a: _SupportsComparison, b: _SupportsComparison, /) -> Any: ... +def gt(a: _SupportsComparison, b: _SupportsComparison, /) -> Any: ... +def not_(a: object, /) -> bool: ... +def truth(a: object, /) -> bool: ... +def is_(a: object, b: object, /) -> bool: ... +def is_not(a: object, b: object, /) -> bool: ... +def abs(a: SupportsAbs[_T], /) -> _T: ... +def add(a: Any, b: Any, /) -> Any: ... +def and_(a: Any, b: Any, /) -> Any: ... +def floordiv(a: Any, b: Any, /) -> Any: ... +def index(a: SupportsIndex, /) -> int: ... +def inv(a: _SupportsInversion[_T_co], /) -> _T_co: ... +def invert(a: _SupportsInversion[_T_co], /) -> _T_co: ... +def lshift(a: Any, b: Any, /) -> Any: ... +def mod(a: Any, b: Any, /) -> Any: ... +def mul(a: Any, b: Any, /) -> Any: ... +def matmul(a: Any, b: Any, /) -> Any: ... +def neg(a: _SupportsNeg[_T_co], /) -> _T_co: ... +def or_(a: Any, b: Any, /) -> Any: ... +def pos(a: _SupportsPos[_T_co], /) -> _T_co: ... +def pow(a: Any, b: Any, /) -> Any: ... +def rshift(a: Any, b: Any, /) -> Any: ... +def sub(a: Any, b: Any, /) -> Any: ... +def truediv(a: Any, b: Any, /) -> Any: ... +def xor(a: Any, b: Any, /) -> Any: ... +def concat(a: Sequence[_T], b: Sequence[_T], /) -> Sequence[_T]: ... +def contains(a: Container[object], b: object, /) -> bool: ... +def countOf(a: Iterable[object], b: object, /) -> int: ... @overload -def delitem(__a: MutableSequence[Any], __b: SupportsIndex) -> None: ... +def delitem(a: MutableSequence[Any], b: SupportsIndex, /) -> None: ... @overload -def delitem(__a: MutableSequence[Any], __b: slice) -> None: ... +def delitem(a: MutableSequence[Any], b: slice, /) -> None: ... @overload -def delitem(__a: MutableMapping[_K, Any], __b: _K) -> None: ... +def delitem(a: MutableMapping[_K, Any], b: _K, /) -> None: ... @overload -def getitem(__a: Sequence[_T], __b: slice) -> Sequence[_T]: ... +def getitem(a: Sequence[_T], b: slice, /) -> Sequence[_T]: ... @overload -def getitem(__a: SupportsGetItem[_K, _V], __b: _K) -> _V: ... -def indexOf(__a: Iterable[_T], __b: _T) -> int: ... +def getitem(a: SupportsGetItem[_K, _V], b: _K, /) -> _V: ... +def indexOf(a: Iterable[_T], b: _T, /) -> int: ... @overload -def setitem(__a: MutableSequence[_T], __b: SupportsIndex, __c: _T) -> None: ... +def setitem(a: MutableSequence[_T], b: SupportsIndex, c: _T, /) -> None: ... @overload -def setitem(__a: MutableSequence[_T], __b: slice, __c: Sequence[_T]) -> None: ... +def setitem(a: MutableSequence[_T], b: slice, c: Sequence[_T], /) -> None: ... @overload -def setitem(__a: MutableMapping[_K, _V], __b: _K, __c: _V) -> None: ... -def length_hint(__obj: object, __default: int = 0) -> int: ... +def setitem(a: MutableMapping[_K, _V], b: _K, c: _V, /) -> None: ... +def length_hint(obj: object, default: int = 0, /) -> int: ... @final class attrgetter(Generic[_T_co]): @overload @@ -109,9 +109,9 @@ class attrgetter(Generic[_T_co]): @final class itemgetter(Generic[_T_co]): @overload - def __new__(cls, __item: _T) -> itemgetter[_T]: ... + def __new__(cls, item: _T, /) -> itemgetter[_T]: ... @overload - def __new__(cls, __item1: _T1, __item2: _T2, *items: Unpack[_Ts]) -> itemgetter[tuple[_T1, _T2, Unpack[_Ts]]]: ... + def __new__(cls, item1: _T1, item2: _T2, /, *items: Unpack[_Ts]) -> itemgetter[tuple[_T1, _T2, Unpack[_Ts]]]: ... # __key: _KT_contra in SupportsGetItem seems to be causing variance issues, ie: # TypeVar "_KT_contra@SupportsGetItem" is contravariant # "tuple[int, int]" is incompatible with protocol "SupportsIndex" @@ -123,25 +123,25 @@ class itemgetter(Generic[_T_co]): @final class methodcaller: - def __init__(self, __name: str, *args: Any, **kwargs: Any) -> None: ... + def __init__(self, name: str, /, *args: Any, **kwargs: Any) -> None: ... def __call__(self, obj: Any) -> Any: ... -def iadd(__a: Any, __b: Any) -> Any: ... -def iand(__a: Any, __b: Any) -> Any: ... -def iconcat(__a: Any, __b: Any) -> Any: ... -def ifloordiv(__a: Any, __b: Any) -> Any: ... -def ilshift(__a: Any, __b: Any) -> Any: ... -def imod(__a: Any, __b: Any) -> Any: ... -def imul(__a: Any, __b: Any) -> Any: ... -def imatmul(__a: Any, __b: Any) -> Any: ... -def ior(__a: Any, __b: Any) -> Any: ... -def ipow(__a: Any, __b: Any) -> Any: ... -def irshift(__a: Any, __b: Any) -> Any: ... -def isub(__a: Any, __b: Any) -> Any: ... -def itruediv(__a: Any, __b: Any) -> Any: ... -def ixor(__a: Any, __b: Any) -> Any: ... +def iadd(a: Any, b: Any, /) -> Any: ... +def iand(a: Any, b: Any, /) -> Any: ... +def iconcat(a: Any, b: Any, /) -> Any: ... +def ifloordiv(a: Any, b: Any, /) -> Any: ... +def ilshift(a: Any, b: Any, /) -> Any: ... +def imod(a: Any, b: Any, /) -> Any: ... +def imul(a: Any, b: Any, /) -> Any: ... +def imatmul(a: Any, b: Any, /) -> Any: ... +def ior(a: Any, b: Any, /) -> Any: ... +def ipow(a: Any, b: Any, /) -> Any: ... +def irshift(a: Any, b: Any, /) -> Any: ... +def isub(a: Any, b: Any, /) -> Any: ... +def itruediv(a: Any, b: Any, /) -> Any: ... +def ixor(a: Any, b: Any, /) -> Any: ... if sys.version_info >= (3, 11): - def call(__obj: Callable[_P, _R], *args: _P.args, **kwargs: _P.kwargs) -> _R: ... + def call(obj: Callable[_P, _R], /, *args: _P.args, **kwargs: _P.kwargs) -> _R: ... -def _compare_digest(__a: AnyStr, __b: AnyStr) -> bool: ... +def _compare_digest(a: AnyStr, b: AnyStr, /) -> bool: ... diff --git a/mypy/typeshed/stdlib/_posixsubprocess.pyi b/mypy/typeshed/stdlib/_posixsubprocess.pyi index 6c1782433e45..3df56d9a3d03 100644 --- a/mypy/typeshed/stdlib/_posixsubprocess.pyi +++ b/mypy/typeshed/stdlib/_posixsubprocess.pyi @@ -6,27 +6,28 @@ from typing import SupportsIndex if sys.platform != "win32": def cloexec_pipe() -> tuple[int, int]: ... def fork_exec( - __args: Sequence[StrOrBytesPath] | None, - __executable_list: Sequence[bytes], - __close_fds: bool, - __pass_fds: tuple[int, ...], - __cwd: str, - __env: Sequence[bytes] | None, - __p2cread: int, - __p2cwrite: int, - __c2pread: int, - __c2pwrite: int, - __errread: int, - __errwrite: int, - __errpipe_read: int, - __errpipe_write: int, - __restore_signals: int, - __call_setsid: int, - __pgid_to_set: int, - __gid: SupportsIndex | None, - __extra_groups: list[int] | None, - __uid: SupportsIndex | None, - __child_umask: int, - __preexec_fn: Callable[[], None], - __allow_vfork: bool, + args: Sequence[StrOrBytesPath] | None, + executable_list: Sequence[bytes], + close_fds: bool, + pass_fds: tuple[int, ...], + cwd: str, + env: Sequence[bytes] | None, + p2cread: int, + p2cwrite: int, + c2pread: int, + c2pwrite: int, + errread: int, + errwrite: int, + errpipe_read: int, + errpipe_write: int, + restore_signals: int, + call_setsid: int, + pgid_to_set: int, + gid: SupportsIndex | None, + extra_groups: list[int] | None, + uid: SupportsIndex | None, + child_umask: int, + preexec_fn: Callable[[], None], + allow_vfork: bool, + /, ) -> int: ... diff --git a/mypy/typeshed/stdlib/_py_abc.pyi b/mypy/typeshed/stdlib/_py_abc.pyi index cc45c6ad3814..1260717489e4 100644 --- a/mypy/typeshed/stdlib/_py_abc.pyi +++ b/mypy/typeshed/stdlib/_py_abc.pyi @@ -9,6 +9,6 @@ def get_cache_token() -> _CacheToken: ... class ABCMeta(type): def __new__( - __mcls: type[_typeshed.Self], __name: str, __bases: tuple[type[Any], ...], __namespace: dict[str, Any] + mcls: type[_typeshed.Self], name: str, bases: tuple[type[Any], ...], namespace: dict[str, Any], / ) -> _typeshed.Self: ... def register(cls, subclass: type[_T]) -> type[_T]: ... diff --git a/mypy/typeshed/stdlib/_random.pyi b/mypy/typeshed/stdlib/_random.pyi index 7c5803ede781..4082344ade8e 100644 --- a/mypy/typeshed/stdlib/_random.pyi +++ b/mypy/typeshed/stdlib/_random.pyi @@ -5,8 +5,8 @@ _State: TypeAlias = tuple[int, ...] class Random: def __init__(self, seed: object = ...) -> None: ... - def seed(self, __n: object = None) -> None: ... + def seed(self, n: object = None, /) -> None: ... def getstate(self) -> _State: ... - def setstate(self, __state: _State) -> None: ... + def setstate(self, state: _State, /) -> None: ... def random(self) -> float: ... - def getrandbits(self, __k: int) -> int: ... + def getrandbits(self, k: int, /) -> int: ... diff --git a/mypy/typeshed/stdlib/_socket.pyi b/mypy/typeshed/stdlib/_socket.pyi index 6471cae2e72d..2a48349d4f7d 100644 --- a/mypy/typeshed/stdlib/_socket.pyi +++ b/mypy/typeshed/stdlib/_socket.pyi @@ -696,70 +696,71 @@ class socket: else: def __init__(self, family: int = ..., type: int = ..., proto: int = ..., fileno: SupportsIndex | None = ...) -> None: ... - def bind(self, __address: _Address) -> None: ... + def bind(self, address: _Address, /) -> None: ... def close(self) -> None: ... - def connect(self, __address: _Address) -> None: ... - def connect_ex(self, __address: _Address) -> int: ... + def connect(self, address: _Address, /) -> None: ... + def connect_ex(self, address: _Address, /) -> int: ... def detach(self) -> int: ... def fileno(self) -> int: ... def getpeername(self) -> _RetAddress: ... def getsockname(self) -> _RetAddress: ... @overload - def getsockopt(self, __level: int, __optname: int) -> int: ... + def getsockopt(self, level: int, optname: int, /) -> int: ... @overload - def getsockopt(self, __level: int, __optname: int, __buflen: int) -> bytes: ... + def getsockopt(self, level: int, optname: int, buflen: int, /) -> bytes: ... def getblocking(self) -> bool: ... def gettimeout(self) -> float | None: ... if sys.platform == "win32": - def ioctl(self, __control: int, __option: int | tuple[int, int, int] | bool) -> None: ... + def ioctl(self, control: int, option: int | tuple[int, int, int] | bool, /) -> None: ... - def listen(self, __backlog: int = ...) -> None: ... - def recv(self, __bufsize: int, __flags: int = ...) -> bytes: ... - def recvfrom(self, __bufsize: int, __flags: int = ...) -> tuple[bytes, _RetAddress]: ... + def listen(self, backlog: int = ..., /) -> None: ... + def recv(self, bufsize: int, flags: int = ..., /) -> bytes: ... + def recvfrom(self, bufsize: int, flags: int = ..., /) -> tuple[bytes, _RetAddress]: ... if sys.platform != "win32": - def recvmsg(self, __bufsize: int, __ancbufsize: int = ..., __flags: int = ...) -> tuple[bytes, list[_CMSG], int, Any]: ... + def recvmsg(self, bufsize: int, ancbufsize: int = ..., flags: int = ..., /) -> tuple[bytes, list[_CMSG], int, Any]: ... def recvmsg_into( - self, __buffers: Iterable[WriteableBuffer], __ancbufsize: int = ..., __flags: int = ... + self, buffers: Iterable[WriteableBuffer], ancbufsize: int = ..., flags: int = ..., / ) -> tuple[int, list[_CMSG], int, Any]: ... def recvfrom_into(self, buffer: WriteableBuffer, nbytes: int = ..., flags: int = ...) -> tuple[int, _RetAddress]: ... def recv_into(self, buffer: WriteableBuffer, nbytes: int = ..., flags: int = ...) -> int: ... - def send(self, __data: ReadableBuffer, __flags: int = ...) -> int: ... - def sendall(self, __data: ReadableBuffer, __flags: int = ...) -> None: ... + def send(self, data: ReadableBuffer, flags: int = ..., /) -> int: ... + def sendall(self, data: ReadableBuffer, flags: int = ..., /) -> None: ... @overload - def sendto(self, __data: ReadableBuffer, __address: _Address) -> int: ... + def sendto(self, data: ReadableBuffer, address: _Address, /) -> int: ... @overload - def sendto(self, __data: ReadableBuffer, __flags: int, __address: _Address) -> int: ... + def sendto(self, data: ReadableBuffer, flags: int, address: _Address, /) -> int: ... if sys.platform != "win32": def sendmsg( self, - __buffers: Iterable[ReadableBuffer], - __ancdata: Iterable[_CMSGArg] = ..., - __flags: int = ..., - __address: _Address | None = ..., + buffers: Iterable[ReadableBuffer], + ancdata: Iterable[_CMSGArg] = ..., + flags: int = ..., + address: _Address | None = ..., + /, ) -> int: ... if sys.platform == "linux": def sendmsg_afalg( self, msg: Iterable[ReadableBuffer] = ..., *, op: int, iv: Any = ..., assoclen: int = ..., flags: int = ... ) -> int: ... - def setblocking(self, __flag: bool) -> None: ... - def settimeout(self, __value: float | None) -> None: ... + def setblocking(self, flag: bool, /) -> None: ... + def settimeout(self, value: float | None, /) -> None: ... @overload - def setsockopt(self, __level: int, __optname: int, __value: int | ReadableBuffer) -> None: ... + def setsockopt(self, level: int, optname: int, value: int | ReadableBuffer, /) -> None: ... @overload - def setsockopt(self, __level: int, __optname: int, __value: None, __optlen: int) -> None: ... + def setsockopt(self, level: int, optname: int, value: None, optlen: int, /) -> None: ... if sys.platform == "win32": - def share(self, __process_id: int) -> bytes: ... + def share(self, process_id: int, /) -> bytes: ... - def shutdown(self, __how: int) -> None: ... + def shutdown(self, how: int, /) -> None: ... SocketType = socket # ===== Functions ===== -def close(__fd: SupportsIndex) -> None: ... -def dup(__fd: SupportsIndex) -> int: ... +def close(fd: SupportsIndex, /) -> None: ... +def dup(fd: SupportsIndex, /) -> int: ... # the 5th tuple item is an address def getaddrinfo( @@ -770,33 +771,33 @@ def getaddrinfo( proto: int = ..., flags: int = ..., ) -> list[tuple[int, int, int, str, tuple[str, int] | tuple[str, int, int, int]]]: ... -def gethostbyname(__hostname: str) -> str: ... -def gethostbyname_ex(__hostname: str) -> tuple[str, list[str], list[str]]: ... +def gethostbyname(hostname: str, /) -> str: ... +def gethostbyname_ex(hostname: str, /) -> tuple[str, list[str], list[str]]: ... def gethostname() -> str: ... -def gethostbyaddr(__ip_address: str) -> tuple[str, list[str], list[str]]: ... -def getnameinfo(__sockaddr: tuple[str, int] | tuple[str, int, int, int], __flags: int) -> tuple[str, str]: ... -def getprotobyname(__protocolname: str) -> int: ... -def getservbyname(__servicename: str, __protocolname: str = ...) -> int: ... -def getservbyport(__port: int, __protocolname: str = ...) -> str: ... -def ntohl(__x: int) -> int: ... # param & ret val are 32-bit ints -def ntohs(__x: int) -> int: ... # param & ret val are 16-bit ints -def htonl(__x: int) -> int: ... # param & ret val are 32-bit ints -def htons(__x: int) -> int: ... # param & ret val are 16-bit ints -def inet_aton(__ip_string: str) -> bytes: ... # ret val 4 bytes in length -def inet_ntoa(__packed_ip: ReadableBuffer) -> str: ... -def inet_pton(__address_family: int, __ip_string: str) -> bytes: ... -def inet_ntop(__address_family: int, __packed_ip: ReadableBuffer) -> str: ... +def gethostbyaddr(ip_address: str, /) -> tuple[str, list[str], list[str]]: ... +def getnameinfo(sockaddr: tuple[str, int] | tuple[str, int, int, int], flags: int, /) -> tuple[str, str]: ... +def getprotobyname(protocolname: str, /) -> int: ... +def getservbyname(servicename: str, protocolname: str = ..., /) -> int: ... +def getservbyport(port: int, protocolname: str = ..., /) -> str: ... +def ntohl(x: int, /) -> int: ... # param & ret val are 32-bit ints +def ntohs(x: int, /) -> int: ... # param & ret val are 16-bit ints +def htonl(x: int, /) -> int: ... # param & ret val are 32-bit ints +def htons(x: int, /) -> int: ... # param & ret val are 16-bit ints +def inet_aton(ip_string: str, /) -> bytes: ... # ret val 4 bytes in length +def inet_ntoa(packed_ip: ReadableBuffer, /) -> str: ... +def inet_pton(address_family: int, ip_string: str, /) -> bytes: ... +def inet_ntop(address_family: int, packed_ip: ReadableBuffer, /) -> str: ... def getdefaulttimeout() -> float | None: ... -def setdefaulttimeout(__timeout: float | None) -> None: ... +def setdefaulttimeout(timeout: float | None, /) -> None: ... if sys.platform != "win32": - def sethostname(__name: str) -> None: ... - def CMSG_LEN(__length: int) -> int: ... - def CMSG_SPACE(__length: int) -> int: ... - def socketpair(__family: int = ..., __type: int = ..., __proto: int = ...) -> tuple[socket, socket]: ... + def sethostname(name: str, /) -> None: ... + def CMSG_LEN(length: int, /) -> int: ... + def CMSG_SPACE(length: int, /) -> int: ... + def socketpair(family: int = ..., type: int = ..., proto: int = ..., /) -> tuple[socket, socket]: ... def if_nameindex() -> list[tuple[int, str]]: ... -def if_nametoindex(__name: str) -> int: ... -def if_indextoname(__index: int) -> str: ... +def if_nametoindex(name: str, /) -> int: ... +def if_indextoname(index: int, /) -> str: ... CAPI: object diff --git a/mypy/typeshed/stdlib/_thread.pyi b/mypy/typeshed/stdlib/_thread.pyi index e69f9d2359aa..4ea9aa0609e5 100644 --- a/mypy/typeshed/stdlib/_thread.pyi +++ b/mypy/typeshed/stdlib/_thread.pyi @@ -54,6 +54,6 @@ if sys.version_info >= (3, 12): def daemon_threads_allowed() -> bool: ... class _local: - def __getattribute__(self, __name: str) -> Any: ... - def __setattr__(self, __name: str, __value: Any) -> None: ... - def __delattr__(self, __name: str) -> None: ... + def __getattribute__(self, name: str, /) -> Any: ... + def __setattr__(self, name: str, value: Any, /) -> None: ... + def __delattr__(self, name: str, /) -> None: ... diff --git a/mypy/typeshed/stdlib/_tkinter.pyi b/mypy/typeshed/stdlib/_tkinter.pyi index 67e7e3f696e2..3340df424163 100644 --- a/mypy/typeshed/stdlib/_tkinter.pyi +++ b/mypy/typeshed/stdlib/_tkinter.pyi @@ -21,12 +21,12 @@ class Tcl_Obj: @property def typename(self) -> str: ... __hash__: ClassVar[None] # type: ignore[assignment] - def __eq__(self, __value): ... - def __ge__(self, __value): ... - def __gt__(self, __value): ... - def __le__(self, __value): ... - def __lt__(self, __value): ... - def __ne__(self, __value): ... + def __eq__(self, value, /): ... + def __ge__(self, value, /): ... + def __gt__(self, value, /): ... + def __le__(self, value, /): ... + def __lt__(self, value, /): ... + def __ne__(self, value, /): ... class TclError(Exception): ... @@ -50,39 +50,39 @@ class TclError(Exception): ... @final class TkappType: # Please keep in sync with tkinter.Tk - def adderrorinfo(self, __msg): ... - def call(self, __command: Any, *args: Any) -> Any: ... - def createcommand(self, __name, __func): ... + def adderrorinfo(self, msg, /): ... + def call(self, command: Any, /, *args: Any) -> Any: ... + def createcommand(self, name, func, /): ... if sys.platform != "win32": - def createfilehandler(self, __file, __mask, __func): ... - def deletefilehandler(self, __file): ... + def createfilehandler(self, file, mask, func, /): ... + def deletefilehandler(self, file, /): ... - def createtimerhandler(self, __milliseconds, __func): ... - def deletecommand(self, __name): ... - def dooneevent(self, __flags: int = 0): ... - def eval(self, __script: str) -> str: ... - def evalfile(self, __fileName): ... - def exprboolean(self, __s): ... - def exprdouble(self, __s): ... - def exprlong(self, __s): ... - def exprstring(self, __s): ... - def getboolean(self, __arg): ... - def getdouble(self, __arg): ... - def getint(self, __arg): ... + def createtimerhandler(self, milliseconds, func, /): ... + def deletecommand(self, name, /): ... + def dooneevent(self, flags: int = 0, /): ... + def eval(self, script: str, /) -> str: ... + def evalfile(self, fileName, /): ... + def exprboolean(self, s, /): ... + def exprdouble(self, s, /): ... + def exprlong(self, s, /): ... + def exprstring(self, s, /): ... + def getboolean(self, arg, /): ... + def getdouble(self, arg, /): ... + def getint(self, arg, /): ... def getvar(self, *args, **kwargs): ... def globalgetvar(self, *args, **kwargs): ... def globalsetvar(self, *args, **kwargs): ... def globalunsetvar(self, *args, **kwargs): ... def interpaddr(self): ... def loadtk(self) -> None: ... - def mainloop(self, __threshold: int = 0): ... + def mainloop(self, threshold: int = 0, /): ... def quit(self): ... - def record(self, __script): ... + def record(self, script, /): ... def setvar(self, *ags, **kwargs): ... if sys.version_info < (3, 11): - def split(self, __arg): ... + def split(self, arg, /): ... - def splitlist(self, __arg): ... + def splitlist(self, arg, /): ... def unsetvar(self, *args, **kwargs): ... def wantobjects(self, *args, **kwargs): ... def willdispatch(self): ... @@ -107,14 +107,15 @@ class TkttType: def deletetimerhandler(self): ... def create( - __screenName: str | None = None, - __baseName: str = "", - __className: str = "Tk", - __interactive: bool = False, - __wantobjects: bool = False, - __wantTk: bool = True, - __sync: bool = False, - __use: str | None = None, + screenName: str | None = None, + baseName: str = "", + className: str = "Tk", + interactive: bool = False, + wantobjects: bool = False, + wantTk: bool = True, + sync: bool = False, + use: str | None = None, + /, ): ... def getbusywaitinterval(): ... -def setbusywaitinterval(__new_val): ... +def setbusywaitinterval(new_val, /): ... diff --git a/mypy/typeshed/stdlib/_tracemalloc.pyi b/mypy/typeshed/stdlib/_tracemalloc.pyi index 1b79d9dc5785..b1aeb710233e 100644 --- a/mypy/typeshed/stdlib/_tracemalloc.pyi +++ b/mypy/typeshed/stdlib/_tracemalloc.pyi @@ -2,7 +2,7 @@ import sys from collections.abc import Sequence from tracemalloc import _FrameTuple, _TraceTuple -def _get_object_traceback(__obj: object) -> Sequence[_FrameTuple] | None: ... +def _get_object_traceback(obj: object, /) -> Sequence[_FrameTuple] | None: ... def _get_traces() -> Sequence[_TraceTuple]: ... def clear_traces() -> None: ... def get_traceback_limit() -> int: ... @@ -13,5 +13,5 @@ def is_tracing() -> bool: ... if sys.version_info >= (3, 9): def reset_peak() -> None: ... -def start(__nframe: int = 1) -> None: ... +def start(nframe: int = 1, /) -> None: ... def stop() -> None: ... diff --git a/mypy/typeshed/stdlib/_typeshed/__init__.pyi b/mypy/typeshed/stdlib/_typeshed/__init__.pyi index e9a24bab28a9..9469081ae5d6 100644 --- a/mypy/typeshed/stdlib/_typeshed/__init__.pyi +++ b/mypy/typeshed/stdlib/_typeshed/__init__.pyi @@ -67,7 +67,7 @@ sentinel: Any # stable class IdentityFunction(Protocol): - def __call__(self, __x: _T) -> _T: ... + def __call__(self, x: _T, /) -> _T: ... # stable class SupportsNext(Protocol[_T_co]): @@ -80,16 +80,16 @@ class SupportsAnext(Protocol[_T_co]): # Comparison protocols class SupportsDunderLT(Protocol[_T_contra]): - def __lt__(self, __other: _T_contra) -> bool: ... + def __lt__(self, other: _T_contra, /) -> bool: ... class SupportsDunderGT(Protocol[_T_contra]): - def __gt__(self, __other: _T_contra) -> bool: ... + def __gt__(self, other: _T_contra, /) -> bool: ... class SupportsDunderLE(Protocol[_T_contra]): - def __le__(self, __other: _T_contra) -> bool: ... + def __le__(self, other: _T_contra, /) -> bool: ... class SupportsDunderGE(Protocol[_T_contra]): - def __ge__(self, __other: _T_contra) -> bool: ... + def __ge__(self, other: _T_contra, /) -> bool: ... class SupportsAllComparisons( SupportsDunderLT[Any], SupportsDunderGT[Any], SupportsDunderLE[Any], SupportsDunderGE[Any], Protocol @@ -101,22 +101,22 @@ SupportsRichComparisonT = TypeVar("SupportsRichComparisonT", bound=SupportsRichC # Dunder protocols class SupportsAdd(Protocol[_T_contra, _T_co]): - def __add__(self, __x: _T_contra) -> _T_co: ... + def __add__(self, x: _T_contra, /) -> _T_co: ... class SupportsRAdd(Protocol[_T_contra, _T_co]): - def __radd__(self, __x: _T_contra) -> _T_co: ... + def __radd__(self, x: _T_contra, /) -> _T_co: ... class SupportsSub(Protocol[_T_contra, _T_co]): - def __sub__(self, __x: _T_contra) -> _T_co: ... + def __sub__(self, x: _T_contra, /) -> _T_co: ... class SupportsRSub(Protocol[_T_contra, _T_co]): - def __rsub__(self, __x: _T_contra) -> _T_co: ... + def __rsub__(self, x: _T_contra, /) -> _T_co: ... class SupportsDivMod(Protocol[_T_contra, _T_co]): - def __divmod__(self, __other: _T_contra) -> _T_co: ... + def __divmod__(self, other: _T_contra, /) -> _T_co: ... class SupportsRDivMod(Protocol[_T_contra, _T_co]): - def __rdivmod__(self, __other: _T_contra) -> _T_co: ... + def __rdivmod__(self, other: _T_contra, /) -> _T_co: ... # This protocol is generic over the iterator type, while Iterable is # generic over the type that is iterated over. @@ -130,7 +130,7 @@ class SupportsAiter(Protocol[_T_co]): class SupportsLenAndGetItem(Protocol[_T_co]): def __len__(self) -> int: ... - def __getitem__(self, __k: int) -> _T_co: ... + def __getitem__(self, k: int, /) -> _T_co: ... class SupportsTrunc(Protocol): def __trunc__(self) -> int: ... @@ -144,17 +144,17 @@ class SupportsItems(Protocol[_KT_co, _VT_co]): # stable class SupportsKeysAndGetItem(Protocol[_KT, _VT_co]): def keys(self) -> Iterable[_KT]: ... - def __getitem__(self, __key: _KT) -> _VT_co: ... + def __getitem__(self, key: _KT, /) -> _VT_co: ... # stable class SupportsGetItem(Protocol[_KT_contra, _VT_co]): - def __contains__(self, __x: Any) -> bool: ... - def __getitem__(self, __key: _KT_contra) -> _VT_co: ... + def __contains__(self, x: Any, /) -> bool: ... + def __getitem__(self, key: _KT_contra, /) -> _VT_co: ... # stable class SupportsItemAccess(SupportsGetItem[_KT_contra, _VT], Protocol[_KT_contra, _VT]): - def __setitem__(self, __key: _KT_contra, __value: _VT) -> None: ... - def __delitem__(self, __key: _KT_contra) -> None: ... + def __setitem__(self, key: _KT_contra, value: _VT, /) -> None: ... + def __delitem__(self, key: _KT_contra, /) -> None: ... StrPath: TypeAlias = str | PathLike[str] # stable BytesPath: TypeAlias = bytes | PathLike[bytes] # stable @@ -238,11 +238,11 @@ FileDescriptorOrPath: TypeAlias = int | StrOrBytesPath # stable class SupportsRead(Protocol[_T_co]): - def read(self, __length: int = ...) -> _T_co: ... + def read(self, length: int = ..., /) -> _T_co: ... # stable class SupportsReadline(Protocol[_T_co]): - def readline(self, __length: int = ...) -> _T_co: ... + def readline(self, length: int = ..., /) -> _T_co: ... # stable class SupportsNoArgReadline(Protocol[_T_co]): @@ -250,7 +250,7 @@ class SupportsNoArgReadline(Protocol[_T_co]): # stable class SupportsWrite(Protocol[_T_contra]): - def write(self, __s: _T_contra) -> object: ... + def write(self, s: _T_contra, /) -> object: ... # stable class SupportsFlush(Protocol): @@ -267,17 +267,17 @@ WriteableBuffer: TypeAlias = Buffer ReadableBuffer: TypeAlias = Buffer # stable class SliceableBuffer(Buffer, Protocol): - def __getitem__(self, __slice: slice) -> Sequence[int]: ... + def __getitem__(self, slice: slice, /) -> Sequence[int]: ... class IndexableBuffer(Buffer, Protocol): - def __getitem__(self, __i: int) -> int: ... + def __getitem__(self, i: int, /) -> int: ... class SupportsGetItemBuffer(SliceableBuffer, IndexableBuffer, Protocol): - def __contains__(self, __x: Any) -> bool: ... + def __contains__(self, x: Any, /) -> bool: ... @overload - def __getitem__(self, __slice: slice) -> Sequence[int]: ... + def __getitem__(self, slice: slice, /) -> Sequence[int]: ... @overload - def __getitem__(self, __i: int) -> int: ... + def __getitem__(self, i: int, /) -> int: ... class SizedBuffer(Sized, Buffer, Protocol): ... diff --git a/mypy/typeshed/stdlib/_typeshed/dbapi.pyi b/mypy/typeshed/stdlib/_typeshed/dbapi.pyi index 022e95996bb3..d54fbee57042 100644 --- a/mypy/typeshed/stdlib/_typeshed/dbapi.pyi +++ b/mypy/typeshed/stdlib/_typeshed/dbapi.pyi @@ -23,15 +23,15 @@ class DBAPICursor(Protocol): @property def rowcount(self) -> int: ... # optional: - # def callproc(self, __procname: str, __parameters: Sequence[Any] = ...) -> Sequence[Any]: ... + # def callproc(self, procname: str, parameters: Sequence[Any] = ..., /) -> Sequence[Any]: ... def close(self) -> object: ... - def execute(self, __operation: str, __parameters: Sequence[Any] | Mapping[str, Any] = ...) -> object: ... - def executemany(self, __operation: str, __seq_of_parameters: Sequence[Sequence[Any]]) -> object: ... + def execute(self, operation: str, parameters: Sequence[Any] | Mapping[str, Any] = ..., /) -> object: ... + def executemany(self, operation: str, seq_of_parameters: Sequence[Sequence[Any]], /) -> object: ... def fetchone(self) -> Sequence[Any] | None: ... - def fetchmany(self, __size: int = ...) -> Sequence[Sequence[Any]]: ... + def fetchmany(self, size: int = ..., /) -> Sequence[Sequence[Any]]: ... def fetchall(self) -> Sequence[Sequence[Any]]: ... # optional: # def nextset(self) -> None | Literal[True]: ... arraysize: int - def setinputsizes(self, __sizes: Sequence[DBAPITypeCode | int | None]) -> object: ... - def setoutputsize(self, __size: int, __column: int = ...) -> object: ... + def setinputsizes(self, sizes: Sequence[DBAPITypeCode | int | None], /) -> object: ... + def setoutputsize(self, size: int, column: int = ..., /) -> object: ... diff --git a/mypy/typeshed/stdlib/_typeshed/wsgi.pyi b/mypy/typeshed/stdlib/_typeshed/wsgi.pyi index e8ebf6409e7f..63f204eb889b 100644 --- a/mypy/typeshed/stdlib/_typeshed/wsgi.pyi +++ b/mypy/typeshed/stdlib/_typeshed/wsgi.pyi @@ -11,7 +11,7 @@ from typing import Any, Protocol from typing_extensions import TypeAlias class _Readable(Protocol): - def read(self, __size: int = ...) -> bytes: ... + def read(self, size: int = ..., /) -> bytes: ... # Optional: def close(self) -> object: ... if sys.version_info >= (3, 11): @@ -20,7 +20,7 @@ else: # stable class StartResponse(Protocol): def __call__( - self, __status: str, __headers: list[tuple[str, str]], __exc_info: OptExcInfo | None = ... + self, status: str, headers: list[tuple[str, str]], exc_info: OptExcInfo | None = ..., / ) -> Callable[[bytes], object]: ... WSGIEnvironment: TypeAlias = dict[str, Any] # stable @@ -28,17 +28,17 @@ else: # WSGI input streams per PEP 3333, stable class InputStream(Protocol): - def read(self, __size: int = ...) -> bytes: ... - def readline(self, __size: int = ...) -> bytes: ... - def readlines(self, __hint: int = ...) -> list[bytes]: ... + def read(self, size: int = ..., /) -> bytes: ... + def readline(self, size: int = ..., /) -> bytes: ... + def readlines(self, hint: int = ..., /) -> list[bytes]: ... def __iter__(self) -> Iterator[bytes]: ... # WSGI error streams per PEP 3333, stable class ErrorStream(Protocol): def flush(self) -> object: ... - def write(self, __s: str) -> object: ... - def writelines(self, __seq: list[str]) -> object: ... + def write(self, s: str, /) -> object: ... + def writelines(self, seq: list[str], /) -> object: ... # Optional file wrapper in wsgi.file_wrapper class FileWrapper(Protocol): - def __call__(self, __file: _Readable, __block_size: int = ...) -> Iterable[bytes]: ... + def __call__(self, file: _Readable, block_size: int = ..., /) -> Iterable[bytes]: ... diff --git a/mypy/typeshed/stdlib/_typeshed/xml.pyi b/mypy/typeshed/stdlib/_typeshed/xml.pyi index 46c5fab097c4..6cd1b39af628 100644 --- a/mypy/typeshed/stdlib/_typeshed/xml.pyi +++ b/mypy/typeshed/stdlib/_typeshed/xml.pyi @@ -4,6 +4,6 @@ from typing import Any, Protocol # As defined https://docs.python.org/3/library/xml.dom.html#domimplementation-objects class DOMImplementation(Protocol): - def hasFeature(self, __feature: str, __version: str | None) -> bool: ... - def createDocument(self, __namespaceUri: str, __qualifiedName: str, __doctype: Any | None) -> Any: ... - def createDocumentType(self, __qualifiedName: str, __publicId: str, __systemId: str) -> Any: ... + def hasFeature(self, feature: str, version: str | None, /) -> bool: ... + def createDocument(self, namespaceUri: str, qualifiedName: str, doctype: Any | None, /) -> Any: ... + def createDocumentType(self, qualifiedName: str, publicId: str, systemId: str, /) -> Any: ... diff --git a/mypy/typeshed/stdlib/_weakref.pyi b/mypy/typeshed/stdlib/_weakref.pyi index f939aa815bd2..e395143cc027 100644 --- a/mypy/typeshed/stdlib/_weakref.pyi +++ b/mypy/typeshed/stdlib/_weakref.pyi @@ -11,31 +11,31 @@ _T = TypeVar("_T") @final class CallableProxyType(Generic[_C]): # "weakcallableproxy" - def __eq__(self, __value: object) -> bool: ... + def __eq__(self, value: object, /) -> bool: ... def __getattr__(self, attr: str) -> Any: ... __call__: _C @final class ProxyType(Generic[_T]): # "weakproxy" - def __eq__(self, __value: object) -> bool: ... + def __eq__(self, value: object, /) -> bool: ... def __getattr__(self, attr: str) -> Any: ... class ReferenceType(Generic[_T]): __callback__: Callable[[ReferenceType[_T]], Any] - def __new__(cls, __o: _T, __callback: Callable[[ReferenceType[_T]], Any] | None = ...) -> Self: ... + def __new__(cls, o: _T, callback: Callable[[ReferenceType[_T]], Any] | None = ..., /) -> Self: ... def __call__(self) -> _T | None: ... - def __eq__(self, __value: object) -> bool: ... + def __eq__(self, value: object, /) -> bool: ... def __hash__(self) -> int: ... if sys.version_info >= (3, 9): def __class_getitem__(cls, item: Any) -> GenericAlias: ... ref = ReferenceType -def getweakrefcount(__object: Any) -> int: ... -def getweakrefs(__object: Any) -> list[Any]: ... +def getweakrefcount(object: Any, /) -> int: ... +def getweakrefs(object: Any, /) -> list[Any]: ... # Return CallableProxyType if object is callable, ProxyType otherwise @overload -def proxy(__object: _C, __callback: Callable[[_C], Any] | None = None) -> CallableProxyType[_C]: ... +def proxy(object: _C, callback: Callable[[_C], Any] | None = None, /) -> CallableProxyType[_C]: ... @overload -def proxy(__object: _T, __callback: Callable[[_T], Any] | None = None) -> Any: ... +def proxy(object: _T, callback: Callable[[_T], Any] | None = None, /) -> Any: ... diff --git a/mypy/typeshed/stdlib/_winapi.pyi b/mypy/typeshed/stdlib/_winapi.pyi index 21ae149e186e..c6fb0484df8e 100644 --- a/mypy/typeshed/stdlib/_winapi.pyi +++ b/mypy/typeshed/stdlib/_winapi.pyi @@ -158,7 +158,7 @@ if sys.platform == "win32": ERROR_ACCESS_DENIED: Literal[5] ERROR_PRIVILEGE_NOT_HELD: Literal[1314] - def CloseHandle(__handle: int) -> None: ... + def CloseHandle(handle: int, /) -> None: ... @overload def ConnectNamedPipe(handle: int, overlapped: Literal[True]) -> Overlapped: ... @overload @@ -166,59 +166,63 @@ if sys.platform == "win32": @overload def ConnectNamedPipe(handle: int, overlapped: bool) -> Overlapped | None: ... def CreateFile( - __file_name: str, - __desired_access: int, - __share_mode: int, - __security_attributes: int, - __creation_disposition: int, - __flags_and_attributes: int, - __template_file: int, + file_name: str, + desired_access: int, + share_mode: int, + security_attributes: int, + creation_disposition: int, + flags_and_attributes: int, + template_file: int, + /, ) -> int: ... - def CreateJunction(__src_path: str, __dst_path: str) -> None: ... + def CreateJunction(src_path: str, dst_path: str, /) -> None: ... def CreateNamedPipe( - __name: str, - __open_mode: int, - __pipe_mode: int, - __max_instances: int, - __out_buffer_size: int, - __in_buffer_size: int, - __default_timeout: int, - __security_attributes: int, + name: str, + open_mode: int, + pipe_mode: int, + max_instances: int, + out_buffer_size: int, + in_buffer_size: int, + default_timeout: int, + security_attributes: int, + /, ) -> int: ... - def CreatePipe(__pipe_attrs: Any, __size: int) -> tuple[int, int]: ... + def CreatePipe(pipe_attrs: Any, size: int, /) -> tuple[int, int]: ... def CreateProcess( - __application_name: str | None, - __command_line: str | None, - __proc_attrs: Any, - __thread_attrs: Any, - __inherit_handles: bool, - __creation_flags: int, - __env_mapping: dict[str, str], - __current_directory: str | None, - __startup_info: Any, + application_name: str | None, + command_line: str | None, + proc_attrs: Any, + thread_attrs: Any, + inherit_handles: bool, + creation_flags: int, + env_mapping: dict[str, str], + current_directory: str | None, + startup_info: Any, + /, ) -> tuple[int, int, int, int]: ... def DuplicateHandle( - __source_process_handle: int, - __source_handle: int, - __target_process_handle: int, - __desired_access: int, - __inherit_handle: bool, - __options: int = 0, + source_process_handle: int, + source_handle: int, + target_process_handle: int, + desired_access: int, + inherit_handle: bool, + options: int = 0, + /, ) -> int: ... - def ExitProcess(__ExitCode: int) -> NoReturn: ... + def ExitProcess(ExitCode: int, /) -> NoReturn: ... def GetACP() -> int: ... def GetFileType(handle: int) -> int: ... def GetCurrentProcess() -> int: ... - def GetExitCodeProcess(__process: int) -> int: ... + def GetExitCodeProcess(process: int, /) -> int: ... def GetLastError() -> int: ... - def GetModuleFileName(__module_handle: int) -> str: ... - def GetStdHandle(__std_handle: int) -> int: ... + def GetModuleFileName(module_handle: int, /) -> str: ... + def GetStdHandle(std_handle: int, /) -> int: ... def GetVersion() -> int: ... - def OpenProcess(__desired_access: int, __inherit_handle: bool, __process_id: int) -> int: ... - def PeekNamedPipe(__handle: int, __size: int = 0) -> tuple[int, int] | tuple[bytes, int, int]: ... + def OpenProcess(desired_access: int, inherit_handle: bool, process_id: int, /) -> int: ... + def PeekNamedPipe(handle: int, size: int = 0, /) -> tuple[int, int] | tuple[bytes, int, int]: ... if sys.version_info >= (3, 10): def LCMapStringEx(locale: str, flags: int, src: str) -> str: ... - def UnmapViewOfFile(__address: int) -> None: ... + def UnmapViewOfFile(address: int, /) -> None: ... @overload def ReadFile(handle: int, size: int, overlapped: Literal[True]) -> tuple[Overlapped, int]: ... @@ -227,12 +231,12 @@ if sys.platform == "win32": @overload def ReadFile(handle: int, size: int, overlapped: int | bool) -> tuple[Any, int]: ... def SetNamedPipeHandleState( - __named_pipe: int, __mode: int | None, __max_collection_count: int | None, __collect_data_timeout: int | None + named_pipe: int, mode: int | None, max_collection_count: int | None, collect_data_timeout: int | None, / ) -> None: ... - def TerminateProcess(__handle: int, __exit_code: int) -> None: ... - def WaitForMultipleObjects(__handle_seq: Sequence[int], __wait_flag: bool, __milliseconds: int = 0xFFFFFFFF) -> int: ... - def WaitForSingleObject(__handle: int, __milliseconds: int) -> int: ... - def WaitNamedPipe(__name: str, __timeout: int) -> None: ... + def TerminateProcess(handle: int, exit_code: int, /) -> None: ... + def WaitForMultipleObjects(handle_seq: Sequence[int], wait_flag: bool, milliseconds: int = 0xFFFFFFFF, /) -> int: ... + def WaitForSingleObject(handle: int, milliseconds: int, /) -> int: ... + def WaitNamedPipe(name: str, timeout: int, /) -> None: ... @overload def WriteFile(handle: int, buffer: ReadableBuffer, overlapped: Literal[True]) -> tuple[Overlapped, int]: ... @overload @@ -242,10 +246,10 @@ if sys.platform == "win32": @final class Overlapped: event: int - def GetOverlappedResult(self, __wait: bool) -> tuple[int, int]: ... + def GetOverlappedResult(self, wait: bool, /) -> tuple[int, int]: ... def cancel(self) -> None: ... def getbuffer(self) -> bytes | None: ... if sys.version_info >= (3, 12): def CopyFile2(existing_file_name: str, new_file_name: str, flags: int, progress_routine: int | None = None) -> int: ... - def NeedCurrentDirectoryForExePath(__exe_name: str) -> bool: ... + def NeedCurrentDirectoryForExePath(exe_name: str, /) -> bool: ... diff --git a/mypy/typeshed/stdlib/abc.pyi b/mypy/typeshed/stdlib/abc.pyi index e4e7f59b58ca..6bf7821f1c1b 100644 --- a/mypy/typeshed/stdlib/abc.pyi +++ b/mypy/typeshed/stdlib/abc.pyi @@ -15,7 +15,7 @@ class ABCMeta(type): __abstractmethods__: frozenset[str] if sys.version_info >= (3, 11): def __new__( - __mcls: type[_typeshed.Self], __name: str, __bases: tuple[type, ...], __namespace: dict[str, Any], **kwargs: Any + mcls: type[_typeshed.Self], name: str, bases: tuple[type, ...], namespace: dict[str, Any], /, **kwargs: Any ) -> _typeshed.Self: ... else: def __new__( diff --git a/mypy/typeshed/stdlib/argparse.pyi b/mypy/typeshed/stdlib/argparse.pyi index c34aca1f8c20..0701654734a4 100644 --- a/mypy/typeshed/stdlib/argparse.pyi +++ b/mypy/typeshed/stdlib/argparse.pyi @@ -392,7 +392,7 @@ elif sys.version_info >= (3, 9): class Namespace(_AttributeHolder): def __init__(self, **kwargs: Any) -> None: ... def __getattr__(self, name: str) -> Any: ... - def __setattr__(self, __name: str, __value: Any) -> None: ... + def __setattr__(self, name: str, value: Any, /) -> None: ... def __contains__(self, key: str) -> bool: ... def __eq__(self, other: object) -> bool: ... diff --git a/mypy/typeshed/stdlib/array.pyi b/mypy/typeshed/stdlib/array.pyi index 4b5675d2a76e..1b7de1c7882d 100644 --- a/mypy/typeshed/stdlib/array.pyi +++ b/mypy/typeshed/stdlib/array.pyi @@ -24,68 +24,68 @@ class array(MutableSequence[_T]): @property def itemsize(self) -> int: ... @overload - def __init__(self: array[int], __typecode: _IntTypeCode, __initializer: bytes | bytearray | Iterable[int] = ...) -> None: ... + def __init__(self: array[int], typecode: _IntTypeCode, initializer: bytes | bytearray | Iterable[int] = ..., /) -> None: ... @overload def __init__( - self: array[float], __typecode: _FloatTypeCode, __initializer: bytes | bytearray | Iterable[float] = ... + self: array[float], typecode: _FloatTypeCode, initializer: bytes | bytearray | Iterable[float] = ..., / ) -> None: ... @overload def __init__( - self: array[str], __typecode: _UnicodeTypeCode, __initializer: bytes | bytearray | Iterable[str] = ... + self: array[str], typecode: _UnicodeTypeCode, initializer: bytes | bytearray | Iterable[str] = ..., / ) -> None: ... @overload - def __init__(self, __typecode: str, __initializer: Iterable[_T]) -> None: ... + def __init__(self, typecode: str, initializer: Iterable[_T], /) -> None: ... @overload - def __init__(self, __typecode: str, __initializer: bytes | bytearray = ...) -> None: ... - def append(self, __v: _T) -> None: ... + def __init__(self, typecode: str, initializer: bytes | bytearray = ..., /) -> None: ... + def append(self, v: _T, /) -> None: ... def buffer_info(self) -> tuple[int, int]: ... def byteswap(self) -> None: ... - def count(self, __v: _T) -> int: ... - def extend(self, __bb: Iterable[_T]) -> None: ... - def frombytes(self, __buffer: ReadableBuffer) -> None: ... - def fromfile(self, __f: SupportsRead[bytes], __n: int) -> None: ... - def fromlist(self, __list: list[_T]) -> None: ... - def fromunicode(self, __ustr: str) -> None: ... + def count(self, v: _T, /) -> int: ... + def extend(self, bb: Iterable[_T], /) -> None: ... + def frombytes(self, buffer: ReadableBuffer, /) -> None: ... + def fromfile(self, f: SupportsRead[bytes], n: int, /) -> None: ... + def fromlist(self, list: list[_T], /) -> None: ... + def fromunicode(self, ustr: str, /) -> None: ... if sys.version_info >= (3, 10): - def index(self, __v: _T, __start: int = 0, __stop: int = sys.maxsize) -> int: ... + def index(self, v: _T, start: int = 0, stop: int = sys.maxsize, /) -> int: ... else: - def index(self, __v: _T) -> int: ... # type: ignore[override] + def index(self, v: _T, /) -> int: ... # type: ignore[override] - def insert(self, __i: int, __v: _T) -> None: ... - def pop(self, __i: int = -1) -> _T: ... - def remove(self, __v: _T) -> None: ... + def insert(self, i: int, v: _T, /) -> None: ... + def pop(self, i: int = -1, /) -> _T: ... + def remove(self, v: _T, /) -> None: ... def tobytes(self) -> bytes: ... - def tofile(self, __f: SupportsWrite[bytes]) -> None: ... + def tofile(self, f: SupportsWrite[bytes], /) -> None: ... def tolist(self) -> list[_T]: ... def tounicode(self) -> str: ... if sys.version_info < (3, 9): - def fromstring(self, __buffer: str | ReadableBuffer) -> None: ... + def fromstring(self, buffer: str | ReadableBuffer, /) -> None: ... def tostring(self) -> bytes: ... def __len__(self) -> int: ... @overload - def __getitem__(self, __key: SupportsIndex) -> _T: ... + def __getitem__(self, key: SupportsIndex, /) -> _T: ... @overload - def __getitem__(self, __key: slice) -> array[_T]: ... + def __getitem__(self, key: slice, /) -> array[_T]: ... @overload # type: ignore[override] - def __setitem__(self, __key: SupportsIndex, __value: _T) -> None: ... + def __setitem__(self, key: SupportsIndex, value: _T, /) -> None: ... @overload - def __setitem__(self, __key: slice, __value: array[_T]) -> None: ... - def __delitem__(self, __key: SupportsIndex | slice) -> None: ... - def __add__(self, __value: array[_T]) -> array[_T]: ... - def __eq__(self, __value: object) -> bool: ... - def __ge__(self, __value: array[_T]) -> bool: ... - def __gt__(self, __value: array[_T]) -> bool: ... - def __iadd__(self, __value: array[_T]) -> Self: ... # type: ignore[override] - def __imul__(self, __value: int) -> Self: ... - def __le__(self, __value: array[_T]) -> bool: ... - def __lt__(self, __value: array[_T]) -> bool: ... - def __mul__(self, __value: int) -> array[_T]: ... - def __rmul__(self, __value: int) -> array[_T]: ... + def __setitem__(self, key: slice, value: array[_T], /) -> None: ... + def __delitem__(self, key: SupportsIndex | slice, /) -> None: ... + def __add__(self, value: array[_T], /) -> array[_T]: ... + def __eq__(self, value: object, /) -> bool: ... + def __ge__(self, value: array[_T], /) -> bool: ... + def __gt__(self, value: array[_T], /) -> bool: ... + def __iadd__(self, value: array[_T], /) -> Self: ... # type: ignore[override] + def __imul__(self, value: int, /) -> Self: ... + def __le__(self, value: array[_T], /) -> bool: ... + def __lt__(self, value: array[_T], /) -> bool: ... + def __mul__(self, value: int, /) -> array[_T]: ... + def __rmul__(self, value: int, /) -> array[_T]: ... def __copy__(self) -> array[_T]: ... - def __deepcopy__(self, __unused: Any) -> array[_T]: ... - def __buffer__(self, __flags: int) -> memoryview: ... - def __release_buffer__(self, __buffer: memoryview) -> None: ... + def __deepcopy__(self, unused: Any, /) -> array[_T]: ... + def __buffer__(self, flags: int, /) -> memoryview: ... + def __release_buffer__(self, buffer: memoryview, /) -> None: ... if sys.version_info >= (3, 12): def __class_getitem__(cls, item: Any) -> GenericAlias: ... diff --git a/mypy/typeshed/stdlib/asyncio/events.pyi b/mypy/typeshed/stdlib/asyncio/events.pyi index 16f5296e2125..95de28c5021e 100644 --- a/mypy/typeshed/stdlib/asyncio/events.pyi +++ b/mypy/typeshed/stdlib/asyncio/events.pyi @@ -43,9 +43,7 @@ _ProtocolFactory: TypeAlias = Callable[[], BaseProtocol] _SSLContext: TypeAlias = bool | None | ssl.SSLContext class _TaskFactory(Protocol): - def __call__( - self, __loop: AbstractEventLoop, __factory: Coroutine[Any, Any, _T] | Generator[Any, None, _T] - ) -> Future[_T]: ... + def __call__(self, loop: AbstractEventLoop, factory: Coroutine[Any, Any, _T] | Generator[Any, None, _T], /) -> Future[_T]: ... class Handle: _cancelled: bool @@ -577,6 +575,6 @@ else: def get_child_watcher() -> AbstractChildWatcher: ... def set_child_watcher(watcher: AbstractChildWatcher) -> None: ... -def _set_running_loop(__loop: AbstractEventLoop | None) -> None: ... +def _set_running_loop(loop: AbstractEventLoop | None, /) -> None: ... def _get_running_loop() -> AbstractEventLoop: ... def get_running_loop() -> AbstractEventLoop: ... diff --git a/mypy/typeshed/stdlib/asyncio/futures.pyi b/mypy/typeshed/stdlib/asyncio/futures.pyi index 44b9528705a5..560dcc1d5712 100644 --- a/mypy/typeshed/stdlib/asyncio/futures.pyi +++ b/mypy/typeshed/stdlib/asyncio/futures.pyi @@ -34,7 +34,7 @@ class Future(Awaitable[_T], Iterable[_T]): def get_loop(self) -> AbstractEventLoop: ... @property def _callbacks(self) -> list[tuple[Callable[[Self], Any], Context]]: ... - def add_done_callback(self, __fn: Callable[[Self], object], *, context: Context | None = None) -> None: ... + def add_done_callback(self, fn: Callable[[Self], object], /, *, context: Context | None = None) -> None: ... if sys.version_info >= (3, 9): def cancel(self, msg: Any | None = None) -> bool: ... else: @@ -44,9 +44,9 @@ class Future(Awaitable[_T], Iterable[_T]): def done(self) -> bool: ... def result(self) -> _T: ... def exception(self) -> BaseException | None: ... - def remove_done_callback(self, __fn: Callable[[Self], object]) -> int: ... - def set_result(self, __result: _T) -> None: ... - def set_exception(self, __exception: type | BaseException) -> None: ... + def remove_done_callback(self, fn: Callable[[Self], object], /) -> int: ... + def set_result(self, result: _T, /) -> None: ... + def set_exception(self, exception: type | BaseException, /) -> None: ... def __iter__(self) -> Generator[Any, None, _T]: ... def __await__(self) -> Generator[Any, None, _T]: ... @property diff --git a/mypy/typeshed/stdlib/asyncio/tasks.pyi b/mypy/typeshed/stdlib/asyncio/tasks.pyi index 028a7571bb79..67291071d512 100644 --- a/mypy/typeshed/stdlib/asyncio/tasks.pyi +++ b/mypy/typeshed/stdlib/asyncio/tasks.pyi @@ -98,81 +98,88 @@ def ensure_future(coro_or_future: Awaitable[_T], *, loop: AbstractEventLoop | No # N.B. Having overlapping overloads is the only way to get acceptable type inference in all edge cases. if sys.version_info >= (3, 10): @overload - def gather(__coro_or_future1: _FutureLike[_T1], *, return_exceptions: Literal[False] = False) -> Future[tuple[_T1]]: ... # type: ignore[overload-overlap] + def gather(coro_or_future1: _FutureLike[_T1], /, *, return_exceptions: Literal[False] = False) -> Future[tuple[_T1]]: ... # type: ignore[overload-overlap] @overload def gather( # type: ignore[overload-overlap] - __coro_or_future1: _FutureLike[_T1], __coro_or_future2: _FutureLike[_T2], *, return_exceptions: Literal[False] = False + coro_or_future1: _FutureLike[_T1], coro_or_future2: _FutureLike[_T2], /, *, return_exceptions: Literal[False] = False ) -> Future[tuple[_T1, _T2]]: ... @overload def gather( # type: ignore[overload-overlap] - __coro_or_future1: _FutureLike[_T1], - __coro_or_future2: _FutureLike[_T2], - __coro_or_future3: _FutureLike[_T3], + coro_or_future1: _FutureLike[_T1], + coro_or_future2: _FutureLike[_T2], + coro_or_future3: _FutureLike[_T3], + /, *, return_exceptions: Literal[False] = False, ) -> Future[tuple[_T1, _T2, _T3]]: ... @overload def gather( # type: ignore[overload-overlap] - __coro_or_future1: _FutureLike[_T1], - __coro_or_future2: _FutureLike[_T2], - __coro_or_future3: _FutureLike[_T3], - __coro_or_future4: _FutureLike[_T4], + coro_or_future1: _FutureLike[_T1], + coro_or_future2: _FutureLike[_T2], + coro_or_future3: _FutureLike[_T3], + coro_or_future4: _FutureLike[_T4], + /, *, return_exceptions: Literal[False] = False, ) -> Future[tuple[_T1, _T2, _T3, _T4]]: ... @overload def gather( # type: ignore[overload-overlap] - __coro_or_future1: _FutureLike[_T1], - __coro_or_future2: _FutureLike[_T2], - __coro_or_future3: _FutureLike[_T3], - __coro_or_future4: _FutureLike[_T4], - __coro_or_future5: _FutureLike[_T5], + coro_or_future1: _FutureLike[_T1], + coro_or_future2: _FutureLike[_T2], + coro_or_future3: _FutureLike[_T3], + coro_or_future4: _FutureLike[_T4], + coro_or_future5: _FutureLike[_T5], + /, *, return_exceptions: Literal[False] = False, ) -> Future[tuple[_T1, _T2, _T3, _T4, _T5]]: ... @overload def gather( # type: ignore[overload-overlap] - __coro_or_future1: _FutureLike[_T1], - __coro_or_future2: _FutureLike[_T2], - __coro_or_future3: _FutureLike[_T3], - __coro_or_future4: _FutureLike[_T4], - __coro_or_future5: _FutureLike[_T5], - __coro_or_future6: _FutureLike[_T6], + coro_or_future1: _FutureLike[_T1], + coro_or_future2: _FutureLike[_T2], + coro_or_future3: _FutureLike[_T3], + coro_or_future4: _FutureLike[_T4], + coro_or_future5: _FutureLike[_T5], + coro_or_future6: _FutureLike[_T6], + /, *, return_exceptions: Literal[False] = False, ) -> Future[tuple[_T1, _T2, _T3, _T4, _T5, _T6]]: ... @overload def gather(*coros_or_futures: _FutureLike[_T], return_exceptions: Literal[False] = False) -> Future[list[_T]]: ... # type: ignore[overload-overlap] @overload - def gather(__coro_or_future1: _FutureLike[_T1], *, return_exceptions: bool) -> Future[tuple[_T1 | BaseException]]: ... # type: ignore[overload-overlap] + def gather(coro_or_future1: _FutureLike[_T1], /, *, return_exceptions: bool) -> Future[tuple[_T1 | BaseException]]: ... # type: ignore[overload-overlap] @overload def gather( # type: ignore[overload-overlap] - __coro_or_future1: _FutureLike[_T1], __coro_or_future2: _FutureLike[_T2], *, return_exceptions: bool + coro_or_future1: _FutureLike[_T1], coro_or_future2: _FutureLike[_T2], /, *, return_exceptions: bool ) -> Future[tuple[_T1 | BaseException, _T2 | BaseException]]: ... @overload def gather( # type: ignore[overload-overlap] - __coro_or_future1: _FutureLike[_T1], - __coro_or_future2: _FutureLike[_T2], - __coro_or_future3: _FutureLike[_T3], + coro_or_future1: _FutureLike[_T1], + coro_or_future2: _FutureLike[_T2], + coro_or_future3: _FutureLike[_T3], + /, *, return_exceptions: bool, ) -> Future[tuple[_T1 | BaseException, _T2 | BaseException, _T3 | BaseException]]: ... @overload def gather( # type: ignore[overload-overlap] - __coro_or_future1: _FutureLike[_T1], - __coro_or_future2: _FutureLike[_T2], - __coro_or_future3: _FutureLike[_T3], - __coro_or_future4: _FutureLike[_T4], + coro_or_future1: _FutureLike[_T1], + coro_or_future2: _FutureLike[_T2], + coro_or_future3: _FutureLike[_T3], + coro_or_future4: _FutureLike[_T4], + /, *, return_exceptions: bool, ) -> Future[tuple[_T1 | BaseException, _T2 | BaseException, _T3 | BaseException, _T4 | BaseException]]: ... @overload def gather( # type: ignore[overload-overlap] - __coro_or_future1: _FutureLike[_T1], - __coro_or_future2: _FutureLike[_T2], - __coro_or_future3: _FutureLike[_T3], - __coro_or_future4: _FutureLike[_T4], - __coro_or_future5: _FutureLike[_T5], + coro_or_future1: _FutureLike[_T1], + coro_or_future2: _FutureLike[_T2], + coro_or_future3: _FutureLike[_T3], + coro_or_future4: _FutureLike[_T4], + coro_or_future5: _FutureLike[_T5], + /, *, return_exceptions: bool, ) -> Future[ @@ -180,12 +187,13 @@ if sys.version_info >= (3, 10): ]: ... @overload def gather( # type: ignore[overload-overlap] - __coro_or_future1: _FutureLike[_T1], - __coro_or_future2: _FutureLike[_T2], - __coro_or_future3: _FutureLike[_T3], - __coro_or_future4: _FutureLike[_T4], - __coro_or_future5: _FutureLike[_T5], - __coro_or_future6: _FutureLike[_T6], + coro_or_future1: _FutureLike[_T1], + coro_or_future2: _FutureLike[_T2], + coro_or_future3: _FutureLike[_T3], + coro_or_future4: _FutureLike[_T4], + coro_or_future5: _FutureLike[_T5], + coro_or_future6: _FutureLike[_T6], + /, *, return_exceptions: bool, ) -> Future[ @@ -204,54 +212,59 @@ if sys.version_info >= (3, 10): else: @overload def gather( # type: ignore[overload-overlap] - __coro_or_future1: _FutureLike[_T1], *, loop: AbstractEventLoop | None = None, return_exceptions: Literal[False] = False + coro_or_future1: _FutureLike[_T1], /, *, loop: AbstractEventLoop | None = None, return_exceptions: Literal[False] = False ) -> Future[tuple[_T1]]: ... @overload def gather( # type: ignore[overload-overlap] - __coro_or_future1: _FutureLike[_T1], - __coro_or_future2: _FutureLike[_T2], + coro_or_future1: _FutureLike[_T1], + coro_or_future2: _FutureLike[_T2], + /, *, loop: AbstractEventLoop | None = None, return_exceptions: Literal[False] = False, ) -> Future[tuple[_T1, _T2]]: ... @overload def gather( # type: ignore[overload-overlap] - __coro_or_future1: _FutureLike[_T1], - __coro_or_future2: _FutureLike[_T2], - __coro_or_future3: _FutureLike[_T3], + coro_or_future1: _FutureLike[_T1], + coro_or_future2: _FutureLike[_T2], + coro_or_future3: _FutureLike[_T3], + /, *, loop: AbstractEventLoop | None = None, return_exceptions: Literal[False] = False, ) -> Future[tuple[_T1, _T2, _T3]]: ... @overload def gather( # type: ignore[overload-overlap] - __coro_or_future1: _FutureLike[_T1], - __coro_or_future2: _FutureLike[_T2], - __coro_or_future3: _FutureLike[_T3], - __coro_or_future4: _FutureLike[_T4], + coro_or_future1: _FutureLike[_T1], + coro_or_future2: _FutureLike[_T2], + coro_or_future3: _FutureLike[_T3], + coro_or_future4: _FutureLike[_T4], + /, *, loop: AbstractEventLoop | None = None, return_exceptions: Literal[False] = False, ) -> Future[tuple[_T1, _T2, _T3, _T4]]: ... @overload def gather( # type: ignore[overload-overlap] - __coro_or_future1: _FutureLike[_T1], - __coro_or_future2: _FutureLike[_T2], - __coro_or_future3: _FutureLike[_T3], - __coro_or_future4: _FutureLike[_T4], - __coro_or_future5: _FutureLike[_T5], + coro_or_future1: _FutureLike[_T1], + coro_or_future2: _FutureLike[_T2], + coro_or_future3: _FutureLike[_T3], + coro_or_future4: _FutureLike[_T4], + coro_or_future5: _FutureLike[_T5], + /, *, loop: AbstractEventLoop | None = None, return_exceptions: Literal[False] = False, ) -> Future[tuple[_T1, _T2, _T3, _T4, _T5]]: ... @overload def gather( # type: ignore[overload-overlap] - __coro_or_future1: _FutureLike[_T1], - __coro_or_future2: _FutureLike[_T2], - __coro_or_future3: _FutureLike[_T3], - __coro_or_future4: _FutureLike[_T4], - __coro_or_future5: _FutureLike[_T5], - __coro_or_future6: _FutureLike[_T6], + coro_or_future1: _FutureLike[_T1], + coro_or_future2: _FutureLike[_T2], + coro_or_future3: _FutureLike[_T3], + coro_or_future4: _FutureLike[_T4], + coro_or_future5: _FutureLike[_T5], + coro_or_future6: _FutureLike[_T6], + /, *, loop: AbstractEventLoop | None = None, return_exceptions: Literal[False] = False, @@ -262,43 +275,47 @@ else: ) -> Future[list[_T]]: ... @overload def gather( # type: ignore[overload-overlap] - __coro_or_future1: _FutureLike[_T1], *, loop: AbstractEventLoop | None = None, return_exceptions: bool + coro_or_future1: _FutureLike[_T1], /, *, loop: AbstractEventLoop | None = None, return_exceptions: bool ) -> Future[tuple[_T1 | BaseException]]: ... @overload def gather( # type: ignore[overload-overlap] - __coro_or_future1: _FutureLike[_T1], - __coro_or_future2: _FutureLike[_T2], + coro_or_future1: _FutureLike[_T1], + coro_or_future2: _FutureLike[_T2], + /, *, loop: AbstractEventLoop | None = None, return_exceptions: bool, ) -> Future[tuple[_T1 | BaseException, _T2 | BaseException]]: ... @overload def gather( # type: ignore[overload-overlap] - __coro_or_future1: _FutureLike[_T1], - __coro_or_future2: _FutureLike[_T2], - __coro_or_future3: _FutureLike[_T3], + coro_or_future1: _FutureLike[_T1], + coro_or_future2: _FutureLike[_T2], + coro_or_future3: _FutureLike[_T3], + /, *, loop: AbstractEventLoop | None = None, return_exceptions: bool, ) -> Future[tuple[_T1 | BaseException, _T2 | BaseException, _T3 | BaseException]]: ... @overload def gather( # type: ignore[overload-overlap] - __coro_or_future1: _FutureLike[_T1], - __coro_or_future2: _FutureLike[_T2], - __coro_or_future3: _FutureLike[_T3], - __coro_or_future4: _FutureLike[_T4], + coro_or_future1: _FutureLike[_T1], + coro_or_future2: _FutureLike[_T2], + coro_or_future3: _FutureLike[_T3], + coro_or_future4: _FutureLike[_T4], + /, *, loop: AbstractEventLoop | None = None, return_exceptions: bool, ) -> Future[tuple[_T1 | BaseException, _T2 | BaseException, _T3 | BaseException, _T4 | BaseException]]: ... @overload def gather( # type: ignore[overload-overlap] - __coro_or_future1: _FutureLike[_T1], - __coro_or_future2: _FutureLike[_T2], - __coro_or_future3: _FutureLike[_T3], - __coro_or_future4: _FutureLike[_T4], - __coro_or_future5: _FutureLike[_T5], - __coro_or_future6: _FutureLike[_T6], + coro_or_future1: _FutureLike[_T1], + coro_or_future2: _FutureLike[_T2], + coro_or_future3: _FutureLike[_T3], + coro_or_future4: _FutureLike[_T4], + coro_or_future5: _FutureLike[_T5], + coro_or_future6: _FutureLike[_T6], + /, *, loop: AbstractEventLoop | None = None, return_exceptions: bool, @@ -411,7 +428,7 @@ class Task(Future[_T_co]): # type: ignore[type-var] # pyright: ignore[reportIn def get_coro(self) -> _TaskCompatibleCoro[_T_co]: ... def get_name(self) -> str: ... - def set_name(self, __value: object) -> None: ... + def set_name(self, value: object, /) -> None: ... if sys.version_info >= (3, 12): def get_context(self) -> Context: ... @@ -446,7 +463,8 @@ if sys.version_info >= (3, 12): class _CustomTaskConstructor(Protocol[_TaskT_co]): def __call__( self, - __coro: _TaskCompatibleCoro[Any], + coro: _TaskCompatibleCoro[Any], + /, *, loop: AbstractEventLoop, name: str | None, diff --git a/mypy/typeshed/stdlib/asyncio/threads.pyi b/mypy/typeshed/stdlib/asyncio/threads.pyi index 88c4fddcaa3f..799efd25fea4 100644 --- a/mypy/typeshed/stdlib/asyncio/threads.pyi +++ b/mypy/typeshed/stdlib/asyncio/threads.pyi @@ -6,4 +6,4 @@ __all__ = ("to_thread",) _P = ParamSpec("_P") _R = TypeVar("_R") -async def to_thread(__func: Callable[_P, _R], *args: _P.args, **kwargs: _P.kwargs) -> _R: ... +async def to_thread(func: Callable[_P, _R], /, *args: _P.args, **kwargs: _P.kwargs) -> _R: ... diff --git a/mypy/typeshed/stdlib/asyncio/trsock.pyi b/mypy/typeshed/stdlib/asyncio/trsock.pyi index 742216a84ccd..e74cf6fd4e05 100644 --- a/mypy/typeshed/stdlib/asyncio/trsock.pyi +++ b/mypy/typeshed/stdlib/asyncio/trsock.pyi @@ -51,7 +51,7 @@ class TransportSocket: else: def ioctl(self, control: int, option: int | tuple[int, int, int] | bool) -> NoReturn: ... - def listen(self, __backlog: int = ...) -> None: ... + def listen(self, backlog: int = ..., /) -> None: ... def makefile(self) -> BinaryIO: ... def sendfile(self, file: BinaryIO, offset: int = ..., count: int | None = ...) -> int: ... def close(self) -> None: ... @@ -66,11 +66,7 @@ class TransportSocket: ) -> NoReturn: ... def sendmsg( - self, - __buffers: Iterable[ReadableBuffer], - __ancdata: Iterable[_CMSG] = ..., - __flags: int = ..., - __address: _Address = ..., + self, buffers: Iterable[ReadableBuffer], ancdata: Iterable[_CMSG] = ..., flags: int = ..., address: _Address = ..., / ) -> int: ... @overload def sendto(self, data: ReadableBuffer, address: _Address) -> int: ... @@ -87,9 +83,9 @@ class TransportSocket: def recv_into(self, buffer: _WriteBuffer, nbytes: int = ..., flags: int = ...) -> int: ... def recvfrom_into(self, buffer: _WriteBuffer, nbytes: int = ..., flags: int = ...) -> tuple[int, _RetAddress]: ... def recvmsg_into( - self, __buffers: Iterable[_WriteBuffer], __ancbufsize: int = ..., __flags: int = ... + self, buffers: Iterable[_WriteBuffer], ancbufsize: int = ..., flags: int = ..., / ) -> tuple[int, list[_CMSG], int, Any]: ... - def recvmsg(self, __bufsize: int, __ancbufsize: int = ..., __flags: int = ...) -> tuple[bytes, list[_CMSG], int, Any]: ... + def recvmsg(self, bufsize: int, ancbufsize: int = ..., flags: int = ..., /) -> tuple[bytes, list[_CMSG], int, Any]: ... def recvfrom(self, bufsize: int, flags: int = ...) -> tuple[bytes, _RetAddress]: ... def recv(self, bufsize: int, flags: int = ...) -> bytes: ... def __enter__(self) -> socket.socket: ... diff --git a/mypy/typeshed/stdlib/asyncio/unix_events.pyi b/mypy/typeshed/stdlib/asyncio/unix_events.pyi index 2fbc0a4e6049..e9274b853290 100644 --- a/mypy/typeshed/stdlib/asyncio/unix_events.pyi +++ b/mypy/typeshed/stdlib/asyncio/unix_events.pyi @@ -17,7 +17,9 @@ if sys.version_info >= (3, 12): @deprecated("Deprecated as of Python 3.12; will be removed in Python 3.14") class AbstractChildWatcher: @abstractmethod - def add_child_handler(self, pid: int, callback: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts]) -> None: ... + def add_child_handler( + self, pid: int, callback: Callable[[int, int, Unpack[_Ts]], object], *args: Unpack[_Ts] + ) -> None: ... @abstractmethod def remove_child_handler(self, pid: int) -> bool: ... @abstractmethod @@ -36,7 +38,9 @@ if sys.version_info >= (3, 12): else: class AbstractChildWatcher: @abstractmethod - def add_child_handler(self, pid: int, callback: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts]) -> None: ... + def add_child_handler( + self, pid: int, callback: Callable[[int, int, Unpack[_Ts]], object], *args: Unpack[_Ts] + ) -> None: ... @abstractmethod def remove_child_handler(self, pid: int) -> bool: ... @abstractmethod @@ -87,27 +91,35 @@ if sys.platform != "win32": class SafeChildWatcher(BaseChildWatcher): def __enter__(self) -> Self: ... def __exit__(self, a: type[BaseException] | None, b: BaseException | None, c: types.TracebackType | None) -> None: ... - def add_child_handler(self, pid: int, callback: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts]) -> None: ... + def add_child_handler( + self, pid: int, callback: Callable[[int, int, Unpack[_Ts]], object], *args: Unpack[_Ts] + ) -> None: ... def remove_child_handler(self, pid: int) -> bool: ... @deprecated("Deprecated as of Python 3.12; will be removed in Python 3.14") class FastChildWatcher(BaseChildWatcher): def __enter__(self) -> Self: ... def __exit__(self, a: type[BaseException] | None, b: BaseException | None, c: types.TracebackType | None) -> None: ... - def add_child_handler(self, pid: int, callback: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts]) -> None: ... + def add_child_handler( + self, pid: int, callback: Callable[[int, int, Unpack[_Ts]], object], *args: Unpack[_Ts] + ) -> None: ... def remove_child_handler(self, pid: int) -> bool: ... else: class SafeChildWatcher(BaseChildWatcher): def __enter__(self) -> Self: ... def __exit__(self, a: type[BaseException] | None, b: BaseException | None, c: types.TracebackType | None) -> None: ... - def add_child_handler(self, pid: int, callback: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts]) -> None: ... + def add_child_handler( + self, pid: int, callback: Callable[[int, int, Unpack[_Ts]], object], *args: Unpack[_Ts] + ) -> None: ... def remove_child_handler(self, pid: int) -> bool: ... class FastChildWatcher(BaseChildWatcher): def __enter__(self) -> Self: ... def __exit__(self, a: type[BaseException] | None, b: BaseException | None, c: types.TracebackType | None) -> None: ... - def add_child_handler(self, pid: int, callback: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts]) -> None: ... + def add_child_handler( + self, pid: int, callback: Callable[[int, int, Unpack[_Ts]], object], *args: Unpack[_Ts] + ) -> None: ... def remove_child_handler(self, pid: int) -> bool: ... class _UnixSelectorEventLoop(BaseSelectorEventLoop): ... @@ -135,7 +147,9 @@ if sys.platform != "win32": def __exit__( self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: types.TracebackType | None ) -> None: ... - def add_child_handler(self, pid: int, callback: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts]) -> None: ... + def add_child_handler( + self, pid: int, callback: Callable[[int, int, Unpack[_Ts]], object], *args: Unpack[_Ts] + ) -> None: ... def remove_child_handler(self, pid: int) -> bool: ... def attach_loop(self, loop: AbstractEventLoop | None) -> None: ... @@ -147,7 +161,9 @@ if sys.platform != "win32": def __exit__( self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: types.TracebackType | None ) -> None: ... - def add_child_handler(self, pid: int, callback: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts]) -> None: ... + def add_child_handler( + self, pid: int, callback: Callable[[int, int, Unpack[_Ts]], object], *args: Unpack[_Ts] + ) -> None: ... def remove_child_handler(self, pid: int) -> bool: ... def attach_loop(self, loop: AbstractEventLoop | None) -> None: ... @@ -159,7 +175,9 @@ if sys.platform != "win32": self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: types.TracebackType | None ) -> None: ... def __del__(self) -> None: ... - def add_child_handler(self, pid: int, callback: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts]) -> None: ... + def add_child_handler( + self, pid: int, callback: Callable[[int, int, Unpack[_Ts]], object], *args: Unpack[_Ts] + ) -> None: ... def remove_child_handler(self, pid: int) -> bool: ... def attach_loop(self, loop: AbstractEventLoop | None) -> None: ... @@ -172,5 +190,7 @@ if sys.platform != "win32": def is_active(self) -> bool: ... def close(self) -> None: ... def attach_loop(self, loop: AbstractEventLoop | None) -> None: ... - def add_child_handler(self, pid: int, callback: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts]) -> None: ... + def add_child_handler( + self, pid: int, callback: Callable[[int, int, Unpack[_Ts]], object], *args: Unpack[_Ts] + ) -> None: ... def remove_child_handler(self, pid: int) -> bool: ... diff --git a/mypy/typeshed/stdlib/audioop.pyi b/mypy/typeshed/stdlib/audioop.pyi index b5934516e40f..830d6f83a273 100644 --- a/mypy/typeshed/stdlib/audioop.pyi +++ b/mypy/typeshed/stdlib/audioop.pyi @@ -5,38 +5,39 @@ _RatecvState: TypeAlias = tuple[int, tuple[tuple[int, int], ...]] class error(Exception): ... -def add(__fragment1: bytes, __fragment2: bytes, __width: int) -> bytes: ... -def adpcm2lin(__fragment: bytes, __width: int, __state: _AdpcmState | None) -> tuple[bytes, _AdpcmState]: ... -def alaw2lin(__fragment: bytes, __width: int) -> bytes: ... -def avg(__fragment: bytes, __width: int) -> int: ... -def avgpp(__fragment: bytes, __width: int) -> int: ... -def bias(__fragment: bytes, __width: int, __bias: int) -> bytes: ... -def byteswap(__fragment: bytes, __width: int) -> bytes: ... -def cross(__fragment: bytes, __width: int) -> int: ... -def findfactor(__fragment: bytes, __reference: bytes) -> float: ... -def findfit(__fragment: bytes, __reference: bytes) -> tuple[int, float]: ... -def findmax(__fragment: bytes, __length: int) -> int: ... -def getsample(__fragment: bytes, __width: int, __index: int) -> int: ... -def lin2adpcm(__fragment: bytes, __width: int, __state: _AdpcmState | None) -> tuple[bytes, _AdpcmState]: ... -def lin2alaw(__fragment: bytes, __width: int) -> bytes: ... -def lin2lin(__fragment: bytes, __width: int, __newwidth: int) -> bytes: ... -def lin2ulaw(__fragment: bytes, __width: int) -> bytes: ... -def max(__fragment: bytes, __width: int) -> int: ... -def maxpp(__fragment: bytes, __width: int) -> int: ... -def minmax(__fragment: bytes, __width: int) -> tuple[int, int]: ... -def mul(__fragment: bytes, __width: int, __factor: float) -> bytes: ... +def add(fragment1: bytes, fragment2: bytes, width: int, /) -> bytes: ... +def adpcm2lin(fragment: bytes, width: int, state: _AdpcmState | None, /) -> tuple[bytes, _AdpcmState]: ... +def alaw2lin(fragment: bytes, width: int, /) -> bytes: ... +def avg(fragment: bytes, width: int, /) -> int: ... +def avgpp(fragment: bytes, width: int, /) -> int: ... +def bias(fragment: bytes, width: int, bias: int, /) -> bytes: ... +def byteswap(fragment: bytes, width: int, /) -> bytes: ... +def cross(fragment: bytes, width: int, /) -> int: ... +def findfactor(fragment: bytes, reference: bytes, /) -> float: ... +def findfit(fragment: bytes, reference: bytes, /) -> tuple[int, float]: ... +def findmax(fragment: bytes, length: int, /) -> int: ... +def getsample(fragment: bytes, width: int, index: int, /) -> int: ... +def lin2adpcm(fragment: bytes, width: int, state: _AdpcmState | None, /) -> tuple[bytes, _AdpcmState]: ... +def lin2alaw(fragment: bytes, width: int, /) -> bytes: ... +def lin2lin(fragment: bytes, width: int, newwidth: int, /) -> bytes: ... +def lin2ulaw(fragment: bytes, width: int, /) -> bytes: ... +def max(fragment: bytes, width: int, /) -> int: ... +def maxpp(fragment: bytes, width: int, /) -> int: ... +def minmax(fragment: bytes, width: int, /) -> tuple[int, int]: ... +def mul(fragment: bytes, width: int, factor: float, /) -> bytes: ... def ratecv( - __fragment: bytes, - __width: int, - __nchannels: int, - __inrate: int, - __outrate: int, - __state: _RatecvState | None, - __weightA: int = 1, - __weightB: int = 0, + fragment: bytes, + width: int, + nchannels: int, + inrate: int, + outrate: int, + state: _RatecvState | None, + weightA: int = 1, + weightB: int = 0, + /, ) -> tuple[bytes, _RatecvState]: ... -def reverse(__fragment: bytes, __width: int) -> bytes: ... -def rms(__fragment: bytes, __width: int) -> int: ... -def tomono(__fragment: bytes, __width: int, __lfactor: float, __rfactor: float) -> bytes: ... -def tostereo(__fragment: bytes, __width: int, __lfactor: float, __rfactor: float) -> bytes: ... -def ulaw2lin(__fragment: bytes, __width: int) -> bytes: ... +def reverse(fragment: bytes, width: int, /) -> bytes: ... +def rms(fragment: bytes, width: int, /) -> int: ... +def tomono(fragment: bytes, width: int, lfactor: float, rfactor: float, /) -> bytes: ... +def tostereo(fragment: bytes, width: int, lfactor: float, rfactor: float, /) -> bytes: ... +def ulaw2lin(fragment: bytes, width: int, /) -> bytes: ... diff --git a/mypy/typeshed/stdlib/bdb.pyi b/mypy/typeshed/stdlib/bdb.pyi index 43012a253164..a72e986728a7 100644 --- a/mypy/typeshed/stdlib/bdb.pyi +++ b/mypy/typeshed/stdlib/bdb.pyi @@ -67,7 +67,7 @@ class Bdb: ) -> None: ... def runeval(self, expr: str, globals: dict[str, Any] | None = None, locals: Mapping[str, Any] | None = None) -> None: ... def runctx(self, cmd: str | CodeType, globals: dict[str, Any] | None, locals: Mapping[str, Any] | None) -> None: ... - def runcall(self, __func: Callable[_P, _T], *args: _P.args, **kwds: _P.kwargs) -> _T | None: ... + def runcall(self, func: Callable[_P, _T], /, *args: _P.args, **kwds: _P.kwargs) -> _T | None: ... class Breakpoint: next: int diff --git a/mypy/typeshed/stdlib/binascii.pyi b/mypy/typeshed/stdlib/binascii.pyi index d48507b90694..32e018c653cb 100644 --- a/mypy/typeshed/stdlib/binascii.pyi +++ b/mypy/typeshed/stdlib/binascii.pyi @@ -6,31 +6,31 @@ from typing_extensions import TypeAlias # or ASCII-only strings. _AsciiBuffer: TypeAlias = str | ReadableBuffer -def a2b_uu(__data: _AsciiBuffer) -> bytes: ... -def b2a_uu(__data: ReadableBuffer, *, backtick: bool = False) -> bytes: ... +def a2b_uu(data: _AsciiBuffer, /) -> bytes: ... +def b2a_uu(data: ReadableBuffer, /, *, backtick: bool = False) -> bytes: ... if sys.version_info >= (3, 11): - def a2b_base64(__data: _AsciiBuffer, *, strict_mode: bool = False) -> bytes: ... + def a2b_base64(data: _AsciiBuffer, /, *, strict_mode: bool = False) -> bytes: ... else: - def a2b_base64(__data: _AsciiBuffer) -> bytes: ... + def a2b_base64(data: _AsciiBuffer, /) -> bytes: ... -def b2a_base64(__data: ReadableBuffer, *, newline: bool = True) -> bytes: ... +def b2a_base64(data: ReadableBuffer, /, *, newline: bool = True) -> bytes: ... def a2b_qp(data: _AsciiBuffer, header: bool = False) -> bytes: ... def b2a_qp(data: ReadableBuffer, quotetabs: bool = False, istext: bool = True, header: bool = False) -> bytes: ... if sys.version_info < (3, 11): - def a2b_hqx(__data: _AsciiBuffer) -> bytes: ... - def rledecode_hqx(__data: ReadableBuffer) -> bytes: ... - def rlecode_hqx(__data: ReadableBuffer) -> bytes: ... - def b2a_hqx(__data: ReadableBuffer) -> bytes: ... + def a2b_hqx(data: _AsciiBuffer, /) -> bytes: ... + def rledecode_hqx(data: ReadableBuffer, /) -> bytes: ... + def rlecode_hqx(data: ReadableBuffer, /) -> bytes: ... + def b2a_hqx(data: ReadableBuffer, /) -> bytes: ... -def crc_hqx(__data: ReadableBuffer, __crc: int) -> int: ... -def crc32(__data: ReadableBuffer, __crc: int = 0) -> int: ... +def crc_hqx(data: ReadableBuffer, crc: int, /) -> int: ... +def crc32(data: ReadableBuffer, crc: int = 0, /) -> int: ... def b2a_hex(data: ReadableBuffer, sep: str | bytes = ..., bytes_per_sep: int = ...) -> bytes: ... def hexlify(data: ReadableBuffer, sep: str | bytes = ..., bytes_per_sep: int = ...) -> bytes: ... -def a2b_hex(__hexstr: _AsciiBuffer) -> bytes: ... -def unhexlify(__hexstr: _AsciiBuffer) -> bytes: ... +def a2b_hex(hexstr: _AsciiBuffer, /) -> bytes: ... +def unhexlify(hexstr: _AsciiBuffer, /) -> bytes: ... class Error(ValueError): ... class Incomplete(Exception): ... diff --git a/mypy/typeshed/stdlib/builtins.pyi b/mypy/typeshed/stdlib/builtins.pyi index 02e128234dc1..b4765b26c8e5 100644 --- a/mypy/typeshed/stdlib/builtins.pyi +++ b/mypy/typeshed/stdlib/builtins.pyi @@ -61,6 +61,7 @@ from typing import ( # noqa: Y022 from typing_extensions import ( # noqa: Y023 Concatenate, Literal, + LiteralString, ParamSpec, Self, TypeAlias, @@ -97,45 +98,44 @@ class object: __annotations__: dict[str, Any] @property def __class__(self) -> type[Self]: ... - # Ignore errors about type mismatch between property getter and setter @__class__.setter - def __class__(self, __type: type[object]) -> None: ... # noqa: F811 + def __class__(self, type: type[object], /) -> None: ... def __init__(self) -> None: ... def __new__(cls) -> Self: ... # N.B. `object.__setattr__` and `object.__delattr__` are heavily special-cased by type checkers. # Overriding them in subclasses has different semantics, even if the override has an identical signature. - def __setattr__(self, __name: str, __value: Any) -> None: ... - def __delattr__(self, __name: str) -> None: ... - def __eq__(self, __value: object) -> bool: ... - def __ne__(self, __value: object) -> bool: ... + def __setattr__(self, name: str, value: Any, /) -> None: ... + def __delattr__(self, name: str, /) -> None: ... + def __eq__(self, value: object, /) -> bool: ... + def __ne__(self, value: object, /) -> bool: ... def __str__(self) -> str: ... # noqa: Y029 def __repr__(self) -> str: ... # noqa: Y029 def __hash__(self) -> int: ... - def __format__(self, __format_spec: str) -> str: ... - def __getattribute__(self, __name: str) -> Any: ... + def __format__(self, format_spec: str, /) -> str: ... + def __getattribute__(self, name: str, /) -> Any: ... def __sizeof__(self) -> int: ... # return type of pickle methods is rather hard to express in the current type system # see #6661 and https://docs.python.org/3/library/pickle.html#object.__reduce__ def __reduce__(self) -> str | tuple[Any, ...]: ... - def __reduce_ex__(self, __protocol: SupportsIndex) -> str | tuple[Any, ...]: ... + def __reduce_ex__(self, protocol: SupportsIndex, /) -> str | tuple[Any, ...]: ... if sys.version_info >= (3, 11): def __getstate__(self) -> object: ... def __dir__(self) -> Iterable[str]: ... def __init_subclass__(cls) -> None: ... @classmethod - def __subclasshook__(cls, __subclass: type) -> bool: ... + def __subclasshook__(cls, subclass: type, /) -> bool: ... class staticmethod(Generic[_P, _R_co]): @property def __func__(self) -> Callable[_P, _R_co]: ... @property def __isabstractmethod__(self) -> bool: ... - def __init__(self, __f: Callable[_P, _R_co]) -> None: ... + def __init__(self, f: Callable[_P, _R_co], /) -> None: ... @overload - def __get__(self, __instance: None, __owner: type) -> Callable[_P, _R_co]: ... + def __get__(self, instance: None, owner: type, /) -> Callable[_P, _R_co]: ... @overload - def __get__(self, __instance: _T, __owner: type[_T] | None = None) -> Callable[_P, _R_co]: ... + def __get__(self, instance: _T, owner: type[_T] | None = None, /) -> Callable[_P, _R_co]: ... if sys.version_info >= (3, 10): __name__: str __qualname__: str @@ -148,11 +148,11 @@ class classmethod(Generic[_T, _P, _R_co]): def __func__(self) -> Callable[Concatenate[type[_T], _P], _R_co]: ... @property def __isabstractmethod__(self) -> bool: ... - def __init__(self, __f: Callable[Concatenate[type[_T], _P], _R_co]) -> None: ... + def __init__(self, f: Callable[Concatenate[type[_T], _P], _R_co], /) -> None: ... @overload - def __get__(self, __instance: _T, __owner: type[_T] | None = None) -> Callable[_P, _R_co]: ... + def __get__(self, instance: _T, owner: type[_T] | None = None, /) -> Callable[_P, _R_co]: ... @overload - def __get__(self, __instance: None, __owner: type[_T]) -> Callable[_P, _R_co]: ... + def __get__(self, instance: None, owner: type[_T], /) -> Callable[_P, _R_co]: ... if sys.version_info >= (3, 10): __name__: str __qualname__: str @@ -184,35 +184,35 @@ class type: @property def __weakrefoffset__(self) -> int: ... @overload - def __init__(self, __o: object) -> None: ... + def __init__(self, o: object, /) -> None: ... @overload - def __init__(self, __name: str, __bases: tuple[type, ...], __dict: dict[str, Any], **kwds: Any) -> None: ... + def __init__(self, name: str, bases: tuple[type, ...], dict: dict[str, Any], /, **kwds: Any) -> None: ... @overload - def __new__(cls, __o: object) -> type: ... + def __new__(cls, o: object, /) -> type: ... @overload def __new__( - cls: type[_typeshed.Self], __name: str, __bases: tuple[type, ...], __namespace: dict[str, Any], **kwds: Any + cls: type[_typeshed.Self], name: str, bases: tuple[type, ...], namespace: dict[str, Any], /, **kwds: Any ) -> _typeshed.Self: ... def __call__(self, *args: Any, **kwds: Any) -> Any: ... def __subclasses__(self: _typeshed.Self) -> list[_typeshed.Self]: ... # Note: the documentation doesn't specify what the return type is, the standard # implementation seems to be returning a list. def mro(self) -> list[type]: ... - def __instancecheck__(self, __instance: Any) -> bool: ... - def __subclasscheck__(self, __subclass: type) -> bool: ... + def __instancecheck__(self, instance: Any, /) -> bool: ... + def __subclasscheck__(self, subclass: type, /) -> bool: ... @classmethod - def __prepare__(metacls, __name: str, __bases: tuple[type, ...], **kwds: Any) -> MutableMapping[str, object]: ... + def __prepare__(metacls, name: str, bases: tuple[type, ...], /, **kwds: Any) -> MutableMapping[str, object]: ... if sys.version_info >= (3, 10): - def __or__(self, __value: Any) -> types.UnionType: ... - def __ror__(self, __value: Any) -> types.UnionType: ... + def __or__(self, value: Any, /) -> types.UnionType: ... + def __ror__(self, value: Any, /) -> types.UnionType: ... if sys.version_info >= (3, 12): __type_params__: tuple[TypeVar | ParamSpec | TypeVarTuple, ...] class super: @overload - def __init__(self, __t: Any, __obj: Any) -> None: ... + def __init__(self, t: Any, obj: Any, /) -> None: ... @overload - def __init__(self, __t: Any) -> None: ... + def __init__(self, t: Any, /) -> None: ... @overload def __init__(self) -> None: ... @@ -222,9 +222,9 @@ _LiteralInteger = _PositiveInteger | _NegativeInteger | Literal[0] # noqa: Y026 class int: @overload - def __new__(cls, __x: ConvertibleToInt = ...) -> Self: ... + def __new__(cls, x: ConvertibleToInt = ..., /) -> Self: ... @overload - def __new__(cls, __x: str | bytes | bytearray, base: SupportsIndex) -> Self: ... + def __new__(cls, x: str | bytes | bytearray, /, base: SupportsIndex) -> Self: ... def as_integer_ratio(self) -> tuple[int, Literal[1]]: ... @property def real(self) -> int: ... @@ -265,59 +265,59 @@ class int: if sys.version_info >= (3, 12): def is_integer(self) -> Literal[True]: ... - def __add__(self, __value: int) -> int: ... - def __sub__(self, __value: int) -> int: ... - def __mul__(self, __value: int) -> int: ... - def __floordiv__(self, __value: int) -> int: ... - def __truediv__(self, __value: int) -> float: ... - def __mod__(self, __value: int) -> int: ... - def __divmod__(self, __value: int) -> tuple[int, int]: ... - def __radd__(self, __value: int) -> int: ... - def __rsub__(self, __value: int) -> int: ... - def __rmul__(self, __value: int) -> int: ... - def __rfloordiv__(self, __value: int) -> int: ... - def __rtruediv__(self, __value: int) -> float: ... - def __rmod__(self, __value: int) -> int: ... - def __rdivmod__(self, __value: int) -> tuple[int, int]: ... + def __add__(self, value: int, /) -> int: ... + def __sub__(self, value: int, /) -> int: ... + def __mul__(self, value: int, /) -> int: ... + def __floordiv__(self, value: int, /) -> int: ... + def __truediv__(self, value: int, /) -> float: ... + def __mod__(self, value: int, /) -> int: ... + def __divmod__(self, value: int, /) -> tuple[int, int]: ... + def __radd__(self, value: int, /) -> int: ... + def __rsub__(self, value: int, /) -> int: ... + def __rmul__(self, value: int, /) -> int: ... + def __rfloordiv__(self, value: int, /) -> int: ... + def __rtruediv__(self, value: int, /) -> float: ... + def __rmod__(self, value: int, /) -> int: ... + def __rdivmod__(self, value: int, /) -> tuple[int, int]: ... @overload - def __pow__(self, __x: Literal[0]) -> Literal[1]: ... + def __pow__(self, x: Literal[0], /) -> Literal[1]: ... @overload - def __pow__(self, __value: Literal[0], __mod: None) -> Literal[1]: ... + def __pow__(self, value: Literal[0], mod: None, /) -> Literal[1]: ... @overload - def __pow__(self, __value: _PositiveInteger, __mod: None = None) -> int: ... + def __pow__(self, value: _PositiveInteger, mod: None = None, /) -> int: ... @overload - def __pow__(self, __value: _NegativeInteger, __mod: None = None) -> float: ... + def __pow__(self, value: _NegativeInteger, mod: None = None, /) -> float: ... # positive __value -> int; negative __value -> float # return type must be Any as `int | float` causes too many false-positive errors @overload - def __pow__(self, __value: int, __mod: None = None) -> Any: ... - @overload - def __pow__(self, __value: int, __mod: int) -> int: ... - def __rpow__(self, __value: int, __mod: int | None = None) -> Any: ... - def __and__(self, __value: int) -> int: ... - def __or__(self, __value: int) -> int: ... - def __xor__(self, __value: int) -> int: ... - def __lshift__(self, __value: int) -> int: ... - def __rshift__(self, __value: int) -> int: ... - def __rand__(self, __value: int) -> int: ... - def __ror__(self, __value: int) -> int: ... - def __rxor__(self, __value: int) -> int: ... - def __rlshift__(self, __value: int) -> int: ... - def __rrshift__(self, __value: int) -> int: ... + def __pow__(self, value: int, mod: None = None, /) -> Any: ... + @overload + def __pow__(self, value: int, mod: int, /) -> int: ... + def __rpow__(self, value: int, mod: int | None = None, /) -> Any: ... + def __and__(self, value: int, /) -> int: ... + def __or__(self, value: int, /) -> int: ... + def __xor__(self, value: int, /) -> int: ... + def __lshift__(self, value: int, /) -> int: ... + def __rshift__(self, value: int, /) -> int: ... + def __rand__(self, value: int, /) -> int: ... + def __ror__(self, value: int, /) -> int: ... + def __rxor__(self, value: int, /) -> int: ... + def __rlshift__(self, value: int, /) -> int: ... + def __rrshift__(self, value: int, /) -> int: ... def __neg__(self) -> int: ... def __pos__(self) -> int: ... def __invert__(self) -> int: ... def __trunc__(self) -> int: ... def __ceil__(self) -> int: ... def __floor__(self) -> int: ... - def __round__(self, __ndigits: SupportsIndex = ...) -> int: ... + def __round__(self, ndigits: SupportsIndex = ..., /) -> int: ... def __getnewargs__(self) -> tuple[int]: ... - def __eq__(self, __value: object) -> bool: ... - def __ne__(self, __value: object) -> bool: ... - def __lt__(self, __value: int) -> bool: ... - def __le__(self, __value: int) -> bool: ... - def __gt__(self, __value: int) -> bool: ... - def __ge__(self, __value: int) -> bool: ... + def __eq__(self, value: object, /) -> bool: ... + def __ne__(self, value: object, /) -> bool: ... + def __lt__(self, value: int, /) -> bool: ... + def __le__(self, value: int, /) -> bool: ... + def __gt__(self, value: int, /) -> bool: ... + def __ge__(self, value: int, /) -> bool: ... def __float__(self) -> float: ... def __int__(self) -> int: ... def __abs__(self) -> int: ... @@ -326,44 +326,44 @@ class int: def __index__(self) -> int: ... class float: - def __new__(cls, __x: ConvertibleToFloat = ...) -> Self: ... + def __new__(cls, x: ConvertibleToFloat = ..., /) -> Self: ... def as_integer_ratio(self) -> tuple[int, int]: ... def hex(self) -> str: ... def is_integer(self) -> bool: ... @classmethod - def fromhex(cls, __string: str) -> Self: ... + def fromhex(cls, string: str, /) -> Self: ... @property def real(self) -> float: ... @property def imag(self) -> float: ... def conjugate(self) -> float: ... - def __add__(self, __value: float) -> float: ... - def __sub__(self, __value: float) -> float: ... - def __mul__(self, __value: float) -> float: ... - def __floordiv__(self, __value: float) -> float: ... - def __truediv__(self, __value: float) -> float: ... - def __mod__(self, __value: float) -> float: ... - def __divmod__(self, __value: float) -> tuple[float, float]: ... - @overload - def __pow__(self, __value: int, __mod: None = None) -> float: ... + def __add__(self, value: float, /) -> float: ... + def __sub__(self, value: float, /) -> float: ... + def __mul__(self, value: float, /) -> float: ... + def __floordiv__(self, value: float, /) -> float: ... + def __truediv__(self, value: float, /) -> float: ... + def __mod__(self, value: float, /) -> float: ... + def __divmod__(self, value: float, /) -> tuple[float, float]: ... + @overload + def __pow__(self, value: int, mod: None = None, /) -> float: ... # positive __value -> float; negative __value -> complex # return type must be Any as `float | complex` causes too many false-positive errors @overload - def __pow__(self, __value: float, __mod: None = None) -> Any: ... - def __radd__(self, __value: float) -> float: ... - def __rsub__(self, __value: float) -> float: ... - def __rmul__(self, __value: float) -> float: ... - def __rfloordiv__(self, __value: float) -> float: ... - def __rtruediv__(self, __value: float) -> float: ... - def __rmod__(self, __value: float) -> float: ... - def __rdivmod__(self, __value: float) -> tuple[float, float]: ... + def __pow__(self, value: float, mod: None = None, /) -> Any: ... + def __radd__(self, value: float, /) -> float: ... + def __rsub__(self, value: float, /) -> float: ... + def __rmul__(self, value: float, /) -> float: ... + def __rfloordiv__(self, value: float, /) -> float: ... + def __rtruediv__(self, value: float, /) -> float: ... + def __rmod__(self, value: float, /) -> float: ... + def __rdivmod__(self, value: float, /) -> tuple[float, float]: ... @overload - def __rpow__(self, __value: _PositiveInteger, __mod: None = None) -> float: ... + def __rpow__(self, value: _PositiveInteger, mod: None = None, /) -> float: ... @overload - def __rpow__(self, __value: _NegativeInteger, __mod: None = None) -> complex: ... + def __rpow__(self, value: _NegativeInteger, mod: None = None, /) -> complex: ... # Returning `complex` for the general case gives too many false-positive errors. @overload - def __rpow__(self, __value: float, __mod: None = None) -> Any: ... + def __rpow__(self, value: float, mod: None = None, /) -> Any: ... def __getnewargs__(self) -> tuple[float]: ... def __trunc__(self) -> int: ... if sys.version_info >= (3, 9): @@ -371,15 +371,15 @@ class float: def __floor__(self) -> int: ... @overload - def __round__(self, __ndigits: None = None) -> int: ... + def __round__(self, ndigits: None = None, /) -> int: ... @overload - def __round__(self, __ndigits: SupportsIndex) -> float: ... - def __eq__(self, __value: object) -> bool: ... - def __ne__(self, __value: object) -> bool: ... - def __lt__(self, __value: float) -> bool: ... - def __le__(self, __value: float) -> bool: ... - def __gt__(self, __value: float) -> bool: ... - def __ge__(self, __value: float) -> bool: ... + def __round__(self, ndigits: SupportsIndex, /) -> float: ... + def __eq__(self, value: object, /) -> bool: ... + def __ne__(self, value: object, /) -> bool: ... + def __lt__(self, value: float, /) -> bool: ... + def __le__(self, value: float, /) -> bool: ... + def __gt__(self, value: float, /) -> bool: ... + def __ge__(self, value: float, /) -> bool: ... def __neg__(self) -> float: ... def __pos__(self) -> float: ... def __int__(self) -> int: ... @@ -403,18 +403,18 @@ class complex: @property def imag(self) -> float: ... def conjugate(self) -> complex: ... - def __add__(self, __value: complex) -> complex: ... - def __sub__(self, __value: complex) -> complex: ... - def __mul__(self, __value: complex) -> complex: ... - def __pow__(self, __value: complex, __mod: None = None) -> complex: ... - def __truediv__(self, __value: complex) -> complex: ... - def __radd__(self, __value: complex) -> complex: ... - def __rsub__(self, __value: complex) -> complex: ... - def __rmul__(self, __value: complex) -> complex: ... - def __rpow__(self, __value: complex, __mod: None = None) -> complex: ... - def __rtruediv__(self, __value: complex) -> complex: ... - def __eq__(self, __value: object) -> bool: ... - def __ne__(self, __value: object) -> bool: ... + def __add__(self, value: complex, /) -> complex: ... + def __sub__(self, value: complex, /) -> complex: ... + def __mul__(self, value: complex, /) -> complex: ... + def __pow__(self, value: complex, mod: None = None, /) -> complex: ... + def __truediv__(self, value: complex, /) -> complex: ... + def __radd__(self, value: complex, /) -> complex: ... + def __rsub__(self, value: complex, /) -> complex: ... + def __rmul__(self, value: complex, /) -> complex: ... + def __rpow__(self, value: complex, mod: None = None, /) -> complex: ... + def __rtruediv__(self, value: complex, /) -> complex: ... + def __eq__(self, value: object, /) -> bool: ... + def __ne__(self, value: object, /) -> bool: ... def __neg__(self) -> complex: ... def __pos__(self) -> complex: ... def __abs__(self) -> float: ... @@ -424,29 +424,44 @@ class complex: def __complex__(self) -> complex: ... class _FormatMapMapping(Protocol): - def __getitem__(self, __key: str) -> Any: ... + def __getitem__(self, key: str, /) -> Any: ... class _TranslateTable(Protocol): - def __getitem__(self, __key: int) -> str | int | None: ... + def __getitem__(self, key: int, /) -> str | int | None: ... class str(Sequence[str]): @overload def __new__(cls, object: object = ...) -> Self: ... @overload def __new__(cls, object: ReadableBuffer, encoding: str = ..., errors: str = ...) -> Self: ... + @overload + def capitalize(self: LiteralString) -> LiteralString: ... + @overload def capitalize(self) -> str: ... # type: ignore[misc] + @overload + def casefold(self: LiteralString) -> LiteralString: ... + @overload def casefold(self) -> str: ... # type: ignore[misc] - def center(self, __width: SupportsIndex, __fillchar: str = " ") -> str: ... # type: ignore[misc] - def count(self, __sub: str, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ...) -> int: ... + @overload + def center(self: LiteralString, width: SupportsIndex, fillchar: LiteralString = " ", /) -> LiteralString: ... + @overload + def center(self, width: SupportsIndex, fillchar: str = " ", /) -> str: ... # type: ignore[misc] + def count(self, sub: str, start: SupportsIndex | None = ..., end: SupportsIndex | None = ..., /) -> int: ... def encode(self, encoding: str = "utf-8", errors: str = "strict") -> bytes: ... def endswith( - self, __suffix: str | tuple[str, ...], __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... + self, suffix: str | tuple[str, ...], start: SupportsIndex | None = ..., end: SupportsIndex | None = ..., / ) -> bool: ... + @overload + def expandtabs(self: LiteralString, tabsize: SupportsIndex = 8) -> LiteralString: ... + @overload def expandtabs(self, tabsize: SupportsIndex = 8) -> str: ... # type: ignore[misc] - def find(self, __sub: str, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ...) -> int: ... + def find(self, sub: str, start: SupportsIndex | None = ..., end: SupportsIndex | None = ..., /) -> int: ... + @overload + def format(self: LiteralString, *args: LiteralString, **kwargs: LiteralString) -> LiteralString: ... + @overload def format(self, *args: object, **kwargs: object) -> str: ... def format_map(self, map: _FormatMapMapping) -> str: ... - def index(self, __sub: str, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ...) -> int: ... + def index(self, sub: str, start: SupportsIndex | None = ..., end: SupportsIndex | None = ..., /) -> int: ... def isalnum(self) -> bool: ... def isalpha(self) -> bool: ... def isascii(self) -> bool: ... @@ -459,86 +474,159 @@ class str(Sequence[str]): def isspace(self) -> bool: ... def istitle(self) -> bool: ... def isupper(self) -> bool: ... - def join(self, __iterable: Iterable[str]) -> str: ... # type: ignore[misc] - def ljust(self, __width: SupportsIndex, __fillchar: str = " ") -> str: ... # type: ignore[misc] + @overload + def join(self: LiteralString, iterable: Iterable[LiteralString], /) -> LiteralString: ... + @overload + def join(self, iterable: Iterable[str], /) -> str: ... # type: ignore[misc] + @overload + def ljust(self: LiteralString, width: SupportsIndex, fillchar: LiteralString = " ", /) -> LiteralString: ... + @overload + def ljust(self, width: SupportsIndex, fillchar: str = " ", /) -> str: ... # type: ignore[misc] + @overload + def lower(self: LiteralString) -> LiteralString: ... + @overload def lower(self) -> str: ... # type: ignore[misc] - def lstrip(self, __chars: str | None = None) -> str: ... # type: ignore[misc] - def partition(self, __sep: str) -> tuple[str, str, str]: ... # type: ignore[misc] - def replace(self, __old: str, __new: str, __count: SupportsIndex = -1) -> str: ... # type: ignore[misc] + @overload + def lstrip(self: LiteralString, chars: LiteralString | None = None, /) -> LiteralString: ... + @overload + def lstrip(self, chars: str | None = None, /) -> str: ... # type: ignore[misc] + @overload + def partition(self: LiteralString, sep: LiteralString, /) -> tuple[LiteralString, LiteralString, LiteralString]: ... + @overload + def partition(self, sep: str, /) -> tuple[str, str, str]: ... # type: ignore[misc] + @overload + def replace(self: LiteralString, old: LiteralString, new: LiteralString, count: SupportsIndex = -1, /) -> LiteralString: ... + @overload + def replace(self, old: str, new: str, count: SupportsIndex = -1, /) -> str: ... # type: ignore[misc] if sys.version_info >= (3, 9): - def removeprefix(self, __prefix: str) -> str: ... # type: ignore[misc] - def removesuffix(self, __suffix: str) -> str: ... # type: ignore[misc] + @overload + def removeprefix(self: LiteralString, prefix: LiteralString, /) -> LiteralString: ... + @overload + def removeprefix(self, prefix: str, /) -> str: ... # type: ignore[misc] + @overload + def removesuffix(self: LiteralString, suffix: LiteralString, /) -> LiteralString: ... + @overload + def removesuffix(self, suffix: str, /) -> str: ... # type: ignore[misc] - def rfind(self, __sub: str, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ...) -> int: ... - def rindex(self, __sub: str, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ...) -> int: ... - def rjust(self, __width: SupportsIndex, __fillchar: str = " ") -> str: ... # type: ignore[misc] - def rpartition(self, __sep: str) -> tuple[str, str, str]: ... # type: ignore[misc] + def rfind(self, sub: str, start: SupportsIndex | None = ..., end: SupportsIndex | None = ..., /) -> int: ... + def rindex(self, sub: str, start: SupportsIndex | None = ..., end: SupportsIndex | None = ..., /) -> int: ... + @overload + def rjust(self: LiteralString, width: SupportsIndex, fillchar: LiteralString = " ", /) -> LiteralString: ... + @overload + def rjust(self, width: SupportsIndex, fillchar: str = " ", /) -> str: ... # type: ignore[misc] + @overload + def rpartition(self: LiteralString, sep: LiteralString, /) -> tuple[LiteralString, LiteralString, LiteralString]: ... + @overload + def rpartition(self, sep: str, /) -> tuple[str, str, str]: ... # type: ignore[misc] + @overload + def rsplit(self: LiteralString, sep: LiteralString | None = None, maxsplit: SupportsIndex = -1) -> list[LiteralString]: ... + @overload def rsplit(self, sep: str | None = None, maxsplit: SupportsIndex = -1) -> list[str]: ... # type: ignore[misc] - def rstrip(self, __chars: str | None = None) -> str: ... # type: ignore[misc] + @overload + def rstrip(self: LiteralString, chars: LiteralString | None = None, /) -> LiteralString: ... + @overload + def rstrip(self, chars: str | None = None, /) -> str: ... # type: ignore[misc] + @overload + def split(self: LiteralString, sep: LiteralString | None = None, maxsplit: SupportsIndex = -1) -> list[LiteralString]: ... + @overload def split(self, sep: str | None = None, maxsplit: SupportsIndex = -1) -> list[str]: ... # type: ignore[misc] + @overload + def splitlines(self: LiteralString, keepends: bool = False) -> list[LiteralString]: ... + @overload def splitlines(self, keepends: bool = False) -> list[str]: ... # type: ignore[misc] def startswith( - self, __prefix: str | tuple[str, ...], __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... + self, prefix: str | tuple[str, ...], start: SupportsIndex | None = ..., end: SupportsIndex | None = ..., / ) -> bool: ... - def strip(self, __chars: str | None = None) -> str: ... # type: ignore[misc] + @overload + def strip(self: LiteralString, chars: LiteralString | None = None, /) -> LiteralString: ... + @overload + def strip(self, chars: str | None = None, /) -> str: ... # type: ignore[misc] + @overload + def swapcase(self: LiteralString) -> LiteralString: ... + @overload def swapcase(self) -> str: ... # type: ignore[misc] + @overload + def title(self: LiteralString) -> LiteralString: ... + @overload def title(self) -> str: ... # type: ignore[misc] - def translate(self, __table: _TranslateTable) -> str: ... + def translate(self, table: _TranslateTable, /) -> str: ... + @overload + def upper(self: LiteralString) -> LiteralString: ... + @overload def upper(self) -> str: ... # type: ignore[misc] - def zfill(self, __width: SupportsIndex) -> str: ... # type: ignore[misc] + @overload + def zfill(self: LiteralString, width: SupportsIndex, /) -> LiteralString: ... + @overload + def zfill(self, width: SupportsIndex, /) -> str: ... # type: ignore[misc] @staticmethod @overload - def maketrans(__x: dict[int, _T] | dict[str, _T] | dict[str | int, _T]) -> dict[int, _T]: ... + def maketrans(x: dict[int, _T] | dict[str, _T] | dict[str | int, _T], /) -> dict[int, _T]: ... @staticmethod @overload - def maketrans(__x: str, __y: str) -> dict[int, int]: ... + def maketrans(x: str, y: str, /) -> dict[int, int]: ... @staticmethod @overload - def maketrans(__x: str, __y: str, __z: str) -> dict[int, int | None]: ... - def __add__(self, __value: str) -> str: ... # type: ignore[misc] + def maketrans(x: str, y: str, z: str, /) -> dict[int, int | None]: ... + @overload + def __add__(self: LiteralString, value: LiteralString, /) -> LiteralString: ... + @overload + def __add__(self, value: str, /) -> str: ... # type: ignore[misc] # Incompatible with Sequence.__contains__ - def __contains__(self, __key: str) -> bool: ... # type: ignore[override] - def __eq__(self, __value: object) -> bool: ... - def __ge__(self, __value: str) -> bool: ... - def __getitem__(self, __key: SupportsIndex | slice) -> str: ... - def __gt__(self, __value: str) -> bool: ... + def __contains__(self, key: str, /) -> bool: ... # type: ignore[override] + def __eq__(self, value: object, /) -> bool: ... + def __ge__(self, value: str, /) -> bool: ... + def __getitem__(self, key: SupportsIndex | slice, /) -> str: ... + def __gt__(self, value: str, /) -> bool: ... def __hash__(self) -> int: ... + @overload + def __iter__(self: LiteralString) -> Iterator[LiteralString]: ... + @overload def __iter__(self) -> Iterator[str]: ... # type: ignore[misc] - def __le__(self, __value: str) -> bool: ... + def __le__(self, value: str, /) -> bool: ... def __len__(self) -> int: ... - def __lt__(self, __value: str) -> bool: ... - def __mod__(self, __value: Any) -> str: ... - def __mul__(self, __value: SupportsIndex) -> str: ... # type: ignore[misc] - def __ne__(self, __value: object) -> bool: ... - def __rmul__(self, __value: SupportsIndex) -> str: ... # type: ignore[misc] + def __lt__(self, value: str, /) -> bool: ... + @overload + def __mod__(self: LiteralString, value: LiteralString | tuple[LiteralString, ...], /) -> LiteralString: ... + @overload + def __mod__(self, value: Any, /) -> str: ... + @overload + def __mul__(self: LiteralString, value: SupportsIndex, /) -> LiteralString: ... + @overload + def __mul__(self, value: SupportsIndex, /) -> str: ... # type: ignore[misc] + def __ne__(self, value: object, /) -> bool: ... + @overload + def __rmul__(self: LiteralString, value: SupportsIndex, /) -> LiteralString: ... + @overload + def __rmul__(self, value: SupportsIndex, /) -> str: ... # type: ignore[misc] def __getnewargs__(self) -> tuple[str]: ... class bytes(Sequence[int]): @overload - def __new__(cls, __o: Iterable[SupportsIndex] | SupportsIndex | SupportsBytes | ReadableBuffer) -> Self: ... + def __new__(cls, o: Iterable[SupportsIndex] | SupportsIndex | SupportsBytes | ReadableBuffer, /) -> Self: ... @overload - def __new__(cls, __string: str, encoding: str, errors: str = ...) -> Self: ... + def __new__(cls, string: str, /, encoding: str, errors: str = ...) -> Self: ... @overload def __new__(cls) -> Self: ... def capitalize(self) -> bytes: ... - def center(self, __width: SupportsIndex, __fillchar: bytes = b" ") -> bytes: ... + def center(self, width: SupportsIndex, fillchar: bytes = b" ", /) -> bytes: ... def count( - self, __sub: ReadableBuffer | SupportsIndex, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... + self, sub: ReadableBuffer | SupportsIndex, start: SupportsIndex | None = ..., end: SupportsIndex | None = ..., / ) -> int: ... def decode(self, encoding: str = "utf-8", errors: str = "strict") -> str: ... def endswith( self, - __suffix: ReadableBuffer | tuple[ReadableBuffer, ...], - __start: SupportsIndex | None = ..., - __end: SupportsIndex | None = ..., + suffix: ReadableBuffer | tuple[ReadableBuffer, ...], + start: SupportsIndex | None = ..., + end: SupportsIndex | None = ..., + /, ) -> bool: ... def expandtabs(self, tabsize: SupportsIndex = 8) -> bytes: ... def find( - self, __sub: ReadableBuffer | SupportsIndex, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... + self, sub: ReadableBuffer | SupportsIndex, start: SupportsIndex | None = ..., end: SupportsIndex | None = ..., / ) -> int: ... def hex(self, sep: str | bytes = ..., bytes_per_sep: SupportsIndex = ...) -> str: ... def index( - self, __sub: ReadableBuffer | SupportsIndex, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... + self, sub: ReadableBuffer | SupportsIndex, start: SupportsIndex | None = ..., end: SupportsIndex | None = ..., / ) -> int: ... def isalnum(self) -> bool: ... def isalpha(self) -> bool: ... @@ -548,100 +636,102 @@ class bytes(Sequence[int]): def isspace(self) -> bool: ... def istitle(self) -> bool: ... def isupper(self) -> bool: ... - def join(self, __iterable_of_bytes: Iterable[ReadableBuffer]) -> bytes: ... - def ljust(self, __width: SupportsIndex, __fillchar: bytes | bytearray = b" ") -> bytes: ... + def join(self, iterable_of_bytes: Iterable[ReadableBuffer], /) -> bytes: ... + def ljust(self, width: SupportsIndex, fillchar: bytes | bytearray = b" ", /) -> bytes: ... def lower(self) -> bytes: ... - def lstrip(self, __bytes: ReadableBuffer | None = None) -> bytes: ... - def partition(self, __sep: ReadableBuffer) -> tuple[bytes, bytes, bytes]: ... - def replace(self, __old: ReadableBuffer, __new: ReadableBuffer, __count: SupportsIndex = -1) -> bytes: ... + def lstrip(self, bytes: ReadableBuffer | None = None, /) -> bytes: ... + def partition(self, sep: ReadableBuffer, /) -> tuple[bytes, bytes, bytes]: ... + def replace(self, old: ReadableBuffer, new: ReadableBuffer, count: SupportsIndex = -1, /) -> bytes: ... if sys.version_info >= (3, 9): - def removeprefix(self, __prefix: ReadableBuffer) -> bytes: ... - def removesuffix(self, __suffix: ReadableBuffer) -> bytes: ... + def removeprefix(self, prefix: ReadableBuffer, /) -> bytes: ... + def removesuffix(self, suffix: ReadableBuffer, /) -> bytes: ... def rfind( - self, __sub: ReadableBuffer | SupportsIndex, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... + self, sub: ReadableBuffer | SupportsIndex, start: SupportsIndex | None = ..., end: SupportsIndex | None = ..., / ) -> int: ... def rindex( - self, __sub: ReadableBuffer | SupportsIndex, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... + self, sub: ReadableBuffer | SupportsIndex, start: SupportsIndex | None = ..., end: SupportsIndex | None = ..., / ) -> int: ... - def rjust(self, __width: SupportsIndex, __fillchar: bytes | bytearray = b" ") -> bytes: ... - def rpartition(self, __sep: ReadableBuffer) -> tuple[bytes, bytes, bytes]: ... + def rjust(self, width: SupportsIndex, fillchar: bytes | bytearray = b" ", /) -> bytes: ... + def rpartition(self, sep: ReadableBuffer, /) -> tuple[bytes, bytes, bytes]: ... def rsplit(self, sep: ReadableBuffer | None = None, maxsplit: SupportsIndex = -1) -> list[bytes]: ... - def rstrip(self, __bytes: ReadableBuffer | None = None) -> bytes: ... + def rstrip(self, bytes: ReadableBuffer | None = None, /) -> bytes: ... def split(self, sep: ReadableBuffer | None = None, maxsplit: SupportsIndex = -1) -> list[bytes]: ... def splitlines(self, keepends: bool = False) -> list[bytes]: ... def startswith( self, - __prefix: ReadableBuffer | tuple[ReadableBuffer, ...], - __start: SupportsIndex | None = ..., - __end: SupportsIndex | None = ..., + prefix: ReadableBuffer | tuple[ReadableBuffer, ...], + start: SupportsIndex | None = ..., + end: SupportsIndex | None = ..., + /, ) -> bool: ... - def strip(self, __bytes: ReadableBuffer | None = None) -> bytes: ... + def strip(self, bytes: ReadableBuffer | None = None, /) -> bytes: ... def swapcase(self) -> bytes: ... def title(self) -> bytes: ... - def translate(self, __table: ReadableBuffer | None, delete: bytes = b"") -> bytes: ... + def translate(self, table: ReadableBuffer | None, /, delete: bytes = b"") -> bytes: ... def upper(self) -> bytes: ... - def zfill(self, __width: SupportsIndex) -> bytes: ... + def zfill(self, width: SupportsIndex, /) -> bytes: ... @classmethod - def fromhex(cls, __string: str) -> Self: ... + def fromhex(cls, string: str, /) -> Self: ... @staticmethod - def maketrans(__frm: ReadableBuffer, __to: ReadableBuffer) -> bytes: ... + def maketrans(frm: ReadableBuffer, to: ReadableBuffer, /) -> bytes: ... def __len__(self) -> int: ... def __iter__(self) -> Iterator[int]: ... def __hash__(self) -> int: ... @overload - def __getitem__(self, __key: SupportsIndex) -> int: ... + def __getitem__(self, key: SupportsIndex, /) -> int: ... @overload - def __getitem__(self, __key: slice) -> bytes: ... - def __add__(self, __value: ReadableBuffer) -> bytes: ... - def __mul__(self, __value: SupportsIndex) -> bytes: ... - def __rmul__(self, __value: SupportsIndex) -> bytes: ... - def __mod__(self, __value: Any) -> bytes: ... + def __getitem__(self, key: slice, /) -> bytes: ... + def __add__(self, value: ReadableBuffer, /) -> bytes: ... + def __mul__(self, value: SupportsIndex, /) -> bytes: ... + def __rmul__(self, value: SupportsIndex, /) -> bytes: ... + def __mod__(self, value: Any, /) -> bytes: ... # Incompatible with Sequence.__contains__ - def __contains__(self, __key: SupportsIndex | ReadableBuffer) -> bool: ... # type: ignore[override] - def __eq__(self, __value: object) -> bool: ... - def __ne__(self, __value: object) -> bool: ... - def __lt__(self, __value: bytes) -> bool: ... - def __le__(self, __value: bytes) -> bool: ... - def __gt__(self, __value: bytes) -> bool: ... - def __ge__(self, __value: bytes) -> bool: ... + def __contains__(self, key: SupportsIndex | ReadableBuffer, /) -> bool: ... # type: ignore[override] + def __eq__(self, value: object, /) -> bool: ... + def __ne__(self, value: object, /) -> bool: ... + def __lt__(self, value: bytes, /) -> bool: ... + def __le__(self, value: bytes, /) -> bool: ... + def __gt__(self, value: bytes, /) -> bool: ... + def __ge__(self, value: bytes, /) -> bool: ... def __getnewargs__(self) -> tuple[bytes]: ... if sys.version_info >= (3, 11): def __bytes__(self) -> bytes: ... - def __buffer__(self, __flags: int) -> memoryview: ... + def __buffer__(self, flags: int, /) -> memoryview: ... class bytearray(MutableSequence[int]): @overload def __init__(self) -> None: ... @overload - def __init__(self, __ints: Iterable[SupportsIndex] | SupportsIndex | ReadableBuffer) -> None: ... + def __init__(self, ints: Iterable[SupportsIndex] | SupportsIndex | ReadableBuffer, /) -> None: ... @overload - def __init__(self, __string: str, encoding: str, errors: str = ...) -> None: ... - def append(self, __item: SupportsIndex) -> None: ... + def __init__(self, string: str, /, encoding: str, errors: str = ...) -> None: ... + def append(self, item: SupportsIndex, /) -> None: ... def capitalize(self) -> bytearray: ... - def center(self, __width: SupportsIndex, __fillchar: bytes = b" ") -> bytearray: ... + def center(self, width: SupportsIndex, fillchar: bytes = b" ", /) -> bytearray: ... def count( - self, __sub: ReadableBuffer | SupportsIndex, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... + self, sub: ReadableBuffer | SupportsIndex, start: SupportsIndex | None = ..., end: SupportsIndex | None = ..., / ) -> int: ... def copy(self) -> bytearray: ... def decode(self, encoding: str = "utf-8", errors: str = "strict") -> str: ... def endswith( self, - __suffix: ReadableBuffer | tuple[ReadableBuffer, ...], - __start: SupportsIndex | None = ..., - __end: SupportsIndex | None = ..., + suffix: ReadableBuffer | tuple[ReadableBuffer, ...], + start: SupportsIndex | None = ..., + end: SupportsIndex | None = ..., + /, ) -> bool: ... def expandtabs(self, tabsize: SupportsIndex = 8) -> bytearray: ... - def extend(self, __iterable_of_ints: Iterable[SupportsIndex]) -> None: ... + def extend(self, iterable_of_ints: Iterable[SupportsIndex], /) -> None: ... def find( - self, __sub: ReadableBuffer | SupportsIndex, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... + self, sub: ReadableBuffer | SupportsIndex, start: SupportsIndex | None = ..., end: SupportsIndex | None = ..., / ) -> int: ... def hex(self, sep: str | bytes = ..., bytes_per_sep: SupportsIndex = ...) -> str: ... def index( - self, __sub: ReadableBuffer | SupportsIndex, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... + self, sub: ReadableBuffer | SupportsIndex, start: SupportsIndex | None = ..., end: SupportsIndex | None = ..., / ) -> int: ... - def insert(self, __index: SupportsIndex, __item: SupportsIndex) -> None: ... + def insert(self, index: SupportsIndex, item: SupportsIndex, /) -> None: ... def isalnum(self) -> bool: ... def isalpha(self) -> bool: ... def isascii(self) -> bool: ... @@ -650,76 +740,77 @@ class bytearray(MutableSequence[int]): def isspace(self) -> bool: ... def istitle(self) -> bool: ... def isupper(self) -> bool: ... - def join(self, __iterable_of_bytes: Iterable[ReadableBuffer]) -> bytearray: ... - def ljust(self, __width: SupportsIndex, __fillchar: bytes | bytearray = b" ") -> bytearray: ... + def join(self, iterable_of_bytes: Iterable[ReadableBuffer], /) -> bytearray: ... + def ljust(self, width: SupportsIndex, fillchar: bytes | bytearray = b" ", /) -> bytearray: ... def lower(self) -> bytearray: ... - def lstrip(self, __bytes: ReadableBuffer | None = None) -> bytearray: ... - def partition(self, __sep: ReadableBuffer) -> tuple[bytearray, bytearray, bytearray]: ... - def pop(self, __index: int = -1) -> int: ... - def remove(self, __value: int) -> None: ... + def lstrip(self, bytes: ReadableBuffer | None = None, /) -> bytearray: ... + def partition(self, sep: ReadableBuffer, /) -> tuple[bytearray, bytearray, bytearray]: ... + def pop(self, index: int = -1, /) -> int: ... + def remove(self, value: int, /) -> None: ... if sys.version_info >= (3, 9): - def removeprefix(self, __prefix: ReadableBuffer) -> bytearray: ... - def removesuffix(self, __suffix: ReadableBuffer) -> bytearray: ... + def removeprefix(self, prefix: ReadableBuffer, /) -> bytearray: ... + def removesuffix(self, suffix: ReadableBuffer, /) -> bytearray: ... - def replace(self, __old: ReadableBuffer, __new: ReadableBuffer, __count: SupportsIndex = -1) -> bytearray: ... + def replace(self, old: ReadableBuffer, new: ReadableBuffer, count: SupportsIndex = -1, /) -> bytearray: ... def rfind( - self, __sub: ReadableBuffer | SupportsIndex, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... + self, sub: ReadableBuffer | SupportsIndex, start: SupportsIndex | None = ..., end: SupportsIndex | None = ..., / ) -> int: ... def rindex( - self, __sub: ReadableBuffer | SupportsIndex, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... + self, sub: ReadableBuffer | SupportsIndex, start: SupportsIndex | None = ..., end: SupportsIndex | None = ..., / ) -> int: ... - def rjust(self, __width: SupportsIndex, __fillchar: bytes | bytearray = b" ") -> bytearray: ... - def rpartition(self, __sep: ReadableBuffer) -> tuple[bytearray, bytearray, bytearray]: ... + def rjust(self, width: SupportsIndex, fillchar: bytes | bytearray = b" ", /) -> bytearray: ... + def rpartition(self, sep: ReadableBuffer, /) -> tuple[bytearray, bytearray, bytearray]: ... def rsplit(self, sep: ReadableBuffer | None = None, maxsplit: SupportsIndex = -1) -> list[bytearray]: ... - def rstrip(self, __bytes: ReadableBuffer | None = None) -> bytearray: ... + def rstrip(self, bytes: ReadableBuffer | None = None, /) -> bytearray: ... def split(self, sep: ReadableBuffer | None = None, maxsplit: SupportsIndex = -1) -> list[bytearray]: ... def splitlines(self, keepends: bool = False) -> list[bytearray]: ... def startswith( self, - __prefix: ReadableBuffer | tuple[ReadableBuffer, ...], - __start: SupportsIndex | None = ..., - __end: SupportsIndex | None = ..., + prefix: ReadableBuffer | tuple[ReadableBuffer, ...], + start: SupportsIndex | None = ..., + end: SupportsIndex | None = ..., + /, ) -> bool: ... - def strip(self, __bytes: ReadableBuffer | None = None) -> bytearray: ... + def strip(self, bytes: ReadableBuffer | None = None, /) -> bytearray: ... def swapcase(self) -> bytearray: ... def title(self) -> bytearray: ... - def translate(self, __table: ReadableBuffer | None, delete: bytes = b"") -> bytearray: ... + def translate(self, table: ReadableBuffer | None, /, delete: bytes = b"") -> bytearray: ... def upper(self) -> bytearray: ... - def zfill(self, __width: SupportsIndex) -> bytearray: ... + def zfill(self, width: SupportsIndex, /) -> bytearray: ... @classmethod - def fromhex(cls, __string: str) -> Self: ... + def fromhex(cls, string: str, /) -> Self: ... @staticmethod - def maketrans(__frm: ReadableBuffer, __to: ReadableBuffer) -> bytes: ... + def maketrans(frm: ReadableBuffer, to: ReadableBuffer, /) -> bytes: ... def __len__(self) -> int: ... def __iter__(self) -> Iterator[int]: ... __hash__: ClassVar[None] # type: ignore[assignment] @overload - def __getitem__(self, __key: SupportsIndex) -> int: ... + def __getitem__(self, key: SupportsIndex, /) -> int: ... @overload - def __getitem__(self, __key: slice) -> bytearray: ... + def __getitem__(self, key: slice, /) -> bytearray: ... @overload - def __setitem__(self, __key: SupportsIndex, __value: SupportsIndex) -> None: ... + def __setitem__(self, key: SupportsIndex, value: SupportsIndex, /) -> None: ... @overload - def __setitem__(self, __key: slice, __value: Iterable[SupportsIndex] | bytes) -> None: ... - def __delitem__(self, __key: SupportsIndex | slice) -> None: ... - def __add__(self, __value: ReadableBuffer) -> bytearray: ... + def __setitem__(self, key: slice, value: Iterable[SupportsIndex] | bytes, /) -> None: ... + def __delitem__(self, key: SupportsIndex | slice, /) -> None: ... + def __add__(self, value: ReadableBuffer, /) -> bytearray: ... # The superclass wants us to accept Iterable[int], but that fails at runtime. - def __iadd__(self, __value: ReadableBuffer) -> Self: ... # type: ignore[override] - def __mul__(self, __value: SupportsIndex) -> bytearray: ... - def __rmul__(self, __value: SupportsIndex) -> bytearray: ... - def __imul__(self, __value: SupportsIndex) -> Self: ... - def __mod__(self, __value: Any) -> bytes: ... + def __iadd__(self, value: ReadableBuffer, /) -> Self: ... # type: ignore[override] + def __mul__(self, value: SupportsIndex, /) -> bytearray: ... + def __rmul__(self, value: SupportsIndex, /) -> bytearray: ... + def __imul__(self, value: SupportsIndex, /) -> Self: ... + def __mod__(self, value: Any, /) -> bytes: ... # Incompatible with Sequence.__contains__ - def __contains__(self, __key: SupportsIndex | ReadableBuffer) -> bool: ... # type: ignore[override] - def __eq__(self, __value: object) -> bool: ... - def __ne__(self, __value: object) -> bool: ... - def __lt__(self, __value: ReadableBuffer) -> bool: ... - def __le__(self, __value: ReadableBuffer) -> bool: ... - def __gt__(self, __value: ReadableBuffer) -> bool: ... - def __ge__(self, __value: ReadableBuffer) -> bool: ... + def __contains__(self, key: SupportsIndex | ReadableBuffer, /) -> bool: ... # type: ignore[override] + def __eq__(self, value: object, /) -> bool: ... + def __ne__(self, value: object, /) -> bool: ... + def __lt__(self, value: ReadableBuffer, /) -> bool: ... + def __le__(self, value: ReadableBuffer, /) -> bool: ... + def __gt__(self, value: ReadableBuffer, /) -> bool: ... + def __ge__(self, value: ReadableBuffer, /) -> bool: ... def __alloc__(self) -> int: ... - def __buffer__(self, __flags: int) -> memoryview: ... - def __release_buffer__(self, __buffer: memoryview) -> None: ... + def __buffer__(self, flags: int, /) -> memoryview: ... + def __release_buffer__(self, buffer: memoryview, /) -> None: ... @final class memoryview(Sequence[int]): @@ -750,22 +841,22 @@ class memoryview(Sequence[int]): def __new__(cls, obj: ReadableBuffer) -> Self: ... def __enter__(self) -> Self: ... def __exit__( - self, __exc_type: type[BaseException] | None, __exc_val: BaseException | None, __exc_tb: TracebackType | None + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None, / ) -> None: ... def cast(self, format: str, shape: list[int] | tuple[int, ...] = ...) -> memoryview: ... @overload - def __getitem__(self, __key: SupportsIndex | tuple[SupportsIndex, ...]) -> int: ... + def __getitem__(self, key: SupportsIndex | tuple[SupportsIndex, ...], /) -> int: ... @overload - def __getitem__(self, __key: slice) -> memoryview: ... - def __contains__(self, __x: object) -> bool: ... + def __getitem__(self, key: slice, /) -> memoryview: ... + def __contains__(self, x: object, /) -> bool: ... def __iter__(self) -> Iterator[int]: ... def __len__(self) -> int: ... - def __eq__(self, __value: object) -> bool: ... + def __eq__(self, value: object, /) -> bool: ... def __hash__(self) -> int: ... @overload - def __setitem__(self, __key: slice, __value: ReadableBuffer) -> None: ... + def __setitem__(self, key: slice, value: ReadableBuffer, /) -> None: ... @overload - def __setitem__(self, __key: SupportsIndex | tuple[SupportsIndex, ...], __value: SupportsIndex) -> None: ... + def __setitem__(self, key: SupportsIndex | tuple[SupportsIndex, ...], value: SupportsIndex, /) -> None: ... if sys.version_info >= (3, 10): def tobytes(self, order: Literal["C", "F", "A"] | None = "C") -> bytes: ... else: @@ -775,38 +866,38 @@ class memoryview(Sequence[int]): def toreadonly(self) -> memoryview: ... def release(self) -> None: ... def hex(self, sep: str | bytes = ..., bytes_per_sep: SupportsIndex = ...) -> str: ... - def __buffer__(self, __flags: int) -> memoryview: ... - def __release_buffer__(self, __buffer: memoryview) -> None: ... + def __buffer__(self, flags: int, /) -> memoryview: ... + def __release_buffer__(self, buffer: memoryview, /) -> None: ... @final class bool(int): - def __new__(cls, __o: object = ...) -> Self: ... + def __new__(cls, o: object = ..., /) -> Self: ... # The following overloads could be represented more elegantly with a TypeVar("_B", bool, int), # however mypy has a bug regarding TypeVar constraints (https://github.com/python/mypy/issues/11880). @overload - def __and__(self, __value: bool) -> bool: ... + def __and__(self, value: bool, /) -> bool: ... @overload - def __and__(self, __value: int) -> int: ... + def __and__(self, value: int, /) -> int: ... @overload - def __or__(self, __value: bool) -> bool: ... + def __or__(self, value: bool, /) -> bool: ... @overload - def __or__(self, __value: int) -> int: ... + def __or__(self, value: int, /) -> int: ... @overload - def __xor__(self, __value: bool) -> bool: ... + def __xor__(self, value: bool, /) -> bool: ... @overload - def __xor__(self, __value: int) -> int: ... + def __xor__(self, value: int, /) -> int: ... @overload - def __rand__(self, __value: bool) -> bool: ... + def __rand__(self, value: bool, /) -> bool: ... @overload - def __rand__(self, __value: int) -> int: ... + def __rand__(self, value: int, /) -> int: ... @overload - def __ror__(self, __value: bool) -> bool: ... + def __ror__(self, value: bool, /) -> bool: ... @overload - def __ror__(self, __value: int) -> int: ... + def __ror__(self, value: int, /) -> int: ... @overload - def __rxor__(self, __value: bool) -> bool: ... + def __rxor__(self, value: bool, /) -> bool: ... @overload - def __rxor__(self, __value: int) -> int: ... + def __rxor__(self, value: int, /) -> int: ... def __getnewargs__(self) -> tuple[int]: ... @deprecated("Will throw an error in Python 3.14. Use `not` for logical negation of bools instead.") def __invert__(self) -> int: ... @@ -820,38 +911,38 @@ class slice: @property def stop(self) -> Any: ... @overload - def __new__(cls, __stop: Any) -> Self: ... + def __new__(cls, stop: Any, /) -> Self: ... @overload - def __new__(cls, __start: Any, __stop: Any, __step: Any = ...) -> Self: ... - def __eq__(self, __value: object) -> bool: ... + def __new__(cls, start: Any, stop: Any, step: Any = ..., /) -> Self: ... + def __eq__(self, value: object, /) -> bool: ... __hash__: ClassVar[None] # type: ignore[assignment] - def indices(self, __len: SupportsIndex) -> tuple[int, int, int]: ... + def indices(self, len: SupportsIndex, /) -> tuple[int, int, int]: ... class tuple(Sequence[_T_co]): - def __new__(cls, __iterable: Iterable[_T_co] = ...) -> Self: ... + def __new__(cls, iterable: Iterable[_T_co] = ..., /) -> Self: ... def __len__(self) -> int: ... - def __contains__(self, __key: object) -> bool: ... + def __contains__(self, key: object, /) -> bool: ... @overload - def __getitem__(self, __key: SupportsIndex) -> _T_co: ... + def __getitem__(self, key: SupportsIndex, /) -> _T_co: ... @overload - def __getitem__(self, __key: slice) -> tuple[_T_co, ...]: ... + def __getitem__(self, key: slice, /) -> tuple[_T_co, ...]: ... def __iter__(self) -> Iterator[_T_co]: ... - def __lt__(self, __value: tuple[_T_co, ...]) -> bool: ... - def __le__(self, __value: tuple[_T_co, ...]) -> bool: ... - def __gt__(self, __value: tuple[_T_co, ...]) -> bool: ... - def __ge__(self, __value: tuple[_T_co, ...]) -> bool: ... - def __eq__(self, __value: object) -> bool: ... + def __lt__(self, value: tuple[_T_co, ...], /) -> bool: ... + def __le__(self, value: tuple[_T_co, ...], /) -> bool: ... + def __gt__(self, value: tuple[_T_co, ...], /) -> bool: ... + def __ge__(self, value: tuple[_T_co, ...], /) -> bool: ... + def __eq__(self, value: object, /) -> bool: ... def __hash__(self) -> int: ... @overload - def __add__(self, __value: tuple[_T_co, ...]) -> tuple[_T_co, ...]: ... + def __add__(self, value: tuple[_T_co, ...], /) -> tuple[_T_co, ...]: ... @overload - def __add__(self, __value: tuple[_T, ...]) -> tuple[_T_co | _T, ...]: ... - def __mul__(self, __value: SupportsIndex) -> tuple[_T_co, ...]: ... - def __rmul__(self, __value: SupportsIndex) -> tuple[_T_co, ...]: ... - def count(self, __value: Any) -> int: ... - def index(self, __value: Any, __start: SupportsIndex = 0, __stop: SupportsIndex = sys.maxsize) -> int: ... + def __add__(self, value: tuple[_T, ...], /) -> tuple[_T_co | _T, ...]: ... + def __mul__(self, value: SupportsIndex, /) -> tuple[_T_co, ...]: ... + def __rmul__(self, value: SupportsIndex, /) -> tuple[_T_co, ...]: ... + def count(self, value: Any, /) -> int: ... + def index(self, value: Any, start: SupportsIndex = 0, stop: SupportsIndex = sys.maxsize, /) -> int: ... if sys.version_info >= (3, 9): - def __class_getitem__(cls, __item: Any) -> GenericAlias: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... # Doesn't exist at runtime, but deleting this breaks mypy. See #2999 @final @@ -877,23 +968,23 @@ class function: __module__: str # mypy uses `builtins.function.__get__` to represent methods, properties, and getset_descriptors so we type the return as Any. - def __get__(self, __instance: object, __owner: type | None = None) -> Any: ... + def __get__(self, instance: object, owner: type | None = None, /) -> Any: ... class list(MutableSequence[_T]): @overload def __init__(self) -> None: ... @overload - def __init__(self, __iterable: Iterable[_T]) -> None: ... + def __init__(self, iterable: Iterable[_T], /) -> None: ... def copy(self) -> list[_T]: ... - def append(self, __object: _T) -> None: ... - def extend(self, __iterable: Iterable[_T]) -> None: ... - def pop(self, __index: SupportsIndex = -1) -> _T: ... + def append(self, object: _T, /) -> None: ... + def extend(self, iterable: Iterable[_T], /) -> None: ... + def pop(self, index: SupportsIndex = -1, /) -> _T: ... # Signature of `list.index` should be kept in line with `collections.UserList.index()` # and multiprocessing.managers.ListProxy.index() - def index(self, __value: _T, __start: SupportsIndex = 0, __stop: SupportsIndex = sys.maxsize) -> int: ... - def count(self, __value: _T) -> int: ... - def insert(self, __index: SupportsIndex, __object: _T) -> None: ... - def remove(self, __value: _T) -> None: ... + def index(self, value: _T, start: SupportsIndex = 0, stop: SupportsIndex = sys.maxsize, /) -> int: ... + def count(self, value: _T, /) -> int: ... + def insert(self, index: SupportsIndex, object: _T, /) -> None: ... + def remove(self, value: _T, /) -> None: ... # Signature of `list.sort` should be kept inline with `collections.UserList.sort()` # and multiprocessing.managers.ListProxy.sort() # @@ -907,32 +998,32 @@ class list(MutableSequence[_T]): def __iter__(self) -> Iterator[_T]: ... __hash__: ClassVar[None] # type: ignore[assignment] @overload - def __getitem__(self, __i: SupportsIndex) -> _T: ... + def __getitem__(self, i: SupportsIndex, /) -> _T: ... @overload - def __getitem__(self, __s: slice) -> list[_T]: ... + def __getitem__(self, s: slice, /) -> list[_T]: ... @overload - def __setitem__(self, __key: SupportsIndex, __value: _T) -> None: ... + def __setitem__(self, key: SupportsIndex, value: _T, /) -> None: ... @overload - def __setitem__(self, __key: slice, __value: Iterable[_T]) -> None: ... - def __delitem__(self, __key: SupportsIndex | slice) -> None: ... + def __setitem__(self, key: slice, value: Iterable[_T], /) -> None: ... + def __delitem__(self, key: SupportsIndex | slice, /) -> None: ... # Overloading looks unnecessary, but is needed to work around complex mypy problems @overload - def __add__(self, __value: list[_T]) -> list[_T]: ... + def __add__(self, value: list[_T], /) -> list[_T]: ... @overload - def __add__(self, __value: list[_S]) -> list[_S | _T]: ... - def __iadd__(self, __value: Iterable[_T]) -> Self: ... # type: ignore[misc] - def __mul__(self, __value: SupportsIndex) -> list[_T]: ... - def __rmul__(self, __value: SupportsIndex) -> list[_T]: ... - def __imul__(self, __value: SupportsIndex) -> Self: ... - def __contains__(self, __key: object) -> bool: ... + def __add__(self, value: list[_S], /) -> list[_S | _T]: ... + def __iadd__(self, value: Iterable[_T], /) -> Self: ... # type: ignore[misc] + def __mul__(self, value: SupportsIndex, /) -> list[_T]: ... + def __rmul__(self, value: SupportsIndex, /) -> list[_T]: ... + def __imul__(self, value: SupportsIndex, /) -> Self: ... + def __contains__(self, key: object, /) -> bool: ... def __reversed__(self) -> Iterator[_T]: ... - def __gt__(self, __value: list[_T]) -> bool: ... - def __ge__(self, __value: list[_T]) -> bool: ... - def __lt__(self, __value: list[_T]) -> bool: ... - def __le__(self, __value: list[_T]) -> bool: ... - def __eq__(self, __value: object) -> bool: ... + def __gt__(self, value: list[_T], /) -> bool: ... + def __ge__(self, value: list[_T], /) -> bool: ... + def __lt__(self, value: list[_T], /) -> bool: ... + def __le__(self, value: list[_T], /) -> bool: ... + def __eq__(self, value: object, /) -> bool: ... if sys.version_info >= (3, 9): - def __class_getitem__(cls, __item: Any) -> GenericAlias: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... class dict(MutableMapping[_KT, _VT]): # __init__ should be kept roughly in line with `collections.UserDict.__init__`, which has similar semantics @@ -942,19 +1033,19 @@ class dict(MutableMapping[_KT, _VT]): @overload def __init__(self: dict[str, _VT], **kwargs: _VT) -> None: ... @overload - def __init__(self, __map: SupportsKeysAndGetItem[_KT, _VT]) -> None: ... + def __init__(self, map: SupportsKeysAndGetItem[_KT, _VT], /) -> None: ... @overload - def __init__(self: dict[str, _VT], __map: SupportsKeysAndGetItem[str, _VT], **kwargs: _VT) -> None: ... + def __init__(self: dict[str, _VT], map: SupportsKeysAndGetItem[str, _VT], /, **kwargs: _VT) -> None: ... @overload - def __init__(self, __iterable: Iterable[tuple[_KT, _VT]]) -> None: ... + def __init__(self, iterable: Iterable[tuple[_KT, _VT]], /) -> None: ... @overload - def __init__(self: dict[str, _VT], __iterable: Iterable[tuple[str, _VT]], **kwargs: _VT) -> None: ... + def __init__(self: dict[str, _VT], iterable: Iterable[tuple[str, _VT]], /, **kwargs: _VT) -> None: ... # Next two overloads are for dict(string.split(sep) for string in iterable) # Cannot be Iterable[Sequence[_T]] or otherwise dict(["foo", "bar", "baz"]) is not an error @overload - def __init__(self: dict[str, str], __iterable: Iterable[list[str]]) -> None: ... + def __init__(self: dict[str, str], iterable: Iterable[list[str]], /) -> None: ... @overload - def __init__(self: dict[bytes, bytes], __iterable: Iterable[list[bytes]]) -> None: ... + def __init__(self: dict[bytes, bytes], iterable: Iterable[list[bytes]], /) -> None: ... def __new__(cls, *args: Any, **kwargs: Any) -> Self: ... def copy(self) -> dict[_KT, _VT]: ... def keys(self) -> dict_keys[_KT, _VT]: ... @@ -965,122 +1056,122 @@ class dict(MutableMapping[_KT, _VT]): # See #3800 & https://github.com/python/typing/issues/548#issuecomment-683336963. @classmethod @overload - def fromkeys(cls, __iterable: Iterable[_T], __value: None = None) -> dict[_T, Any | None]: ... + def fromkeys(cls, iterable: Iterable[_T], value: None = None, /) -> dict[_T, Any | None]: ... @classmethod @overload - def fromkeys(cls, __iterable: Iterable[_T], __value: _S) -> dict[_T, _S]: ... + def fromkeys(cls, iterable: Iterable[_T], value: _S, /) -> dict[_T, _S]: ... # Positional-only in dict, but not in MutableMapping @overload # type: ignore[override] - def get(self, __key: _KT) -> _VT | None: ... + def get(self, key: _KT, /) -> _VT | None: ... @overload - def get(self, __key: _KT, __default: _VT) -> _VT: ... + def get(self, key: _KT, default: _VT, /) -> _VT: ... @overload - def get(self, __key: _KT, __default: _T) -> _VT | _T: ... + def get(self, key: _KT, default: _T, /) -> _VT | _T: ... @overload - def pop(self, __key: _KT) -> _VT: ... + def pop(self, key: _KT, /) -> _VT: ... @overload - def pop(self, __key: _KT, __default: _VT) -> _VT: ... + def pop(self, key: _KT, default: _VT, /) -> _VT: ... @overload - def pop(self, __key: _KT, __default: _T) -> _VT | _T: ... + def pop(self, key: _KT, default: _T, /) -> _VT | _T: ... def __len__(self) -> int: ... - def __getitem__(self, __key: _KT) -> _VT: ... - def __setitem__(self, __key: _KT, __value: _VT) -> None: ... - def __delitem__(self, __key: _KT) -> None: ... + def __getitem__(self, key: _KT, /) -> _VT: ... + def __setitem__(self, key: _KT, value: _VT, /) -> None: ... + def __delitem__(self, key: _KT, /) -> None: ... def __iter__(self) -> Iterator[_KT]: ... - def __eq__(self, __value: object) -> bool: ... + def __eq__(self, value: object, /) -> bool: ... def __reversed__(self) -> Iterator[_KT]: ... __hash__: ClassVar[None] # type: ignore[assignment] if sys.version_info >= (3, 9): - def __class_getitem__(cls, __item: Any) -> GenericAlias: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... @overload - def __or__(self, __value: dict[_KT, _VT]) -> dict[_KT, _VT]: ... + def __or__(self, value: dict[_KT, _VT], /) -> dict[_KT, _VT]: ... @overload - def __or__(self, __value: dict[_T1, _T2]) -> dict[_KT | _T1, _VT | _T2]: ... + def __or__(self, value: dict[_T1, _T2], /) -> dict[_KT | _T1, _VT | _T2]: ... @overload - def __ror__(self, __value: dict[_KT, _VT]) -> dict[_KT, _VT]: ... + def __ror__(self, value: dict[_KT, _VT], /) -> dict[_KT, _VT]: ... @overload - def __ror__(self, __value: dict[_T1, _T2]) -> dict[_KT | _T1, _VT | _T2]: ... + def __ror__(self, value: dict[_T1, _T2], /) -> dict[_KT | _T1, _VT | _T2]: ... # dict.__ior__ should be kept roughly in line with MutableMapping.update() @overload # type: ignore[misc] - def __ior__(self, __value: SupportsKeysAndGetItem[_KT, _VT]) -> Self: ... + def __ior__(self, value: SupportsKeysAndGetItem[_KT, _VT], /) -> Self: ... @overload - def __ior__(self, __value: Iterable[tuple[_KT, _VT]]) -> Self: ... + def __ior__(self, value: Iterable[tuple[_KT, _VT]], /) -> Self: ... class set(MutableSet[_T]): @overload def __init__(self) -> None: ... @overload - def __init__(self, __iterable: Iterable[_T]) -> None: ... - def add(self, __element: _T) -> None: ... + def __init__(self, iterable: Iterable[_T], /) -> None: ... + def add(self, element: _T, /) -> None: ... def copy(self) -> set[_T]: ... def difference(self, *s: Iterable[Any]) -> set[_T]: ... def difference_update(self, *s: Iterable[Any]) -> None: ... - def discard(self, __element: _T) -> None: ... + def discard(self, element: _T, /) -> None: ... def intersection(self, *s: Iterable[Any]) -> set[_T]: ... def intersection_update(self, *s: Iterable[Any]) -> None: ... - def isdisjoint(self, __s: Iterable[Any]) -> bool: ... - def issubset(self, __s: Iterable[Any]) -> bool: ... - def issuperset(self, __s: Iterable[Any]) -> bool: ... - def remove(self, __element: _T) -> None: ... - def symmetric_difference(self, __s: Iterable[_T]) -> set[_T]: ... - def symmetric_difference_update(self, __s: Iterable[_T]) -> None: ... + def isdisjoint(self, s: Iterable[Any], /) -> bool: ... + def issubset(self, s: Iterable[Any], /) -> bool: ... + def issuperset(self, s: Iterable[Any], /) -> bool: ... + def remove(self, element: _T, /) -> None: ... + def symmetric_difference(self, s: Iterable[_T], /) -> set[_T]: ... + def symmetric_difference_update(self, s: Iterable[_T], /) -> None: ... def union(self, *s: Iterable[_S]) -> set[_T | _S]: ... def update(self, *s: Iterable[_T]) -> None: ... def __len__(self) -> int: ... - def __contains__(self, __o: object) -> bool: ... + def __contains__(self, o: object, /) -> bool: ... def __iter__(self) -> Iterator[_T]: ... - def __and__(self, __value: AbstractSet[object]) -> set[_T]: ... - def __iand__(self, __value: AbstractSet[object]) -> Self: ... - def __or__(self, __value: AbstractSet[_S]) -> set[_T | _S]: ... - def __ior__(self, __value: AbstractSet[_T]) -> Self: ... # type: ignore[override,misc] - def __sub__(self, __value: AbstractSet[_T | None]) -> set[_T]: ... - def __isub__(self, __value: AbstractSet[object]) -> Self: ... - def __xor__(self, __value: AbstractSet[_S]) -> set[_T | _S]: ... - def __ixor__(self, __value: AbstractSet[_T]) -> Self: ... # type: ignore[override,misc] - def __le__(self, __value: AbstractSet[object]) -> bool: ... - def __lt__(self, __value: AbstractSet[object]) -> bool: ... - def __ge__(self, __value: AbstractSet[object]) -> bool: ... - def __gt__(self, __value: AbstractSet[object]) -> bool: ... - def __eq__(self, __value: object) -> bool: ... + def __and__(self, value: AbstractSet[object], /) -> set[_T]: ... + def __iand__(self, value: AbstractSet[object], /) -> Self: ... + def __or__(self, value: AbstractSet[_S], /) -> set[_T | _S]: ... + def __ior__(self, value: AbstractSet[_T], /) -> Self: ... # type: ignore[override,misc] + def __sub__(self, value: AbstractSet[_T | None], /) -> set[_T]: ... + def __isub__(self, value: AbstractSet[object], /) -> Self: ... + def __xor__(self, value: AbstractSet[_S], /) -> set[_T | _S]: ... + def __ixor__(self, value: AbstractSet[_T], /) -> Self: ... # type: ignore[override,misc] + def __le__(self, value: AbstractSet[object], /) -> bool: ... + def __lt__(self, value: AbstractSet[object], /) -> bool: ... + def __ge__(self, value: AbstractSet[object], /) -> bool: ... + def __gt__(self, value: AbstractSet[object], /) -> bool: ... + def __eq__(self, value: object, /) -> bool: ... __hash__: ClassVar[None] # type: ignore[assignment] if sys.version_info >= (3, 9): - def __class_getitem__(cls, __item: Any) -> GenericAlias: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... class frozenset(AbstractSet[_T_co]): @overload def __new__(cls) -> Self: ... @overload - def __new__(cls, __iterable: Iterable[_T_co]) -> Self: ... + def __new__(cls, iterable: Iterable[_T_co], /) -> Self: ... def copy(self) -> frozenset[_T_co]: ... def difference(self, *s: Iterable[object]) -> frozenset[_T_co]: ... def intersection(self, *s: Iterable[object]) -> frozenset[_T_co]: ... - def isdisjoint(self, __s: Iterable[_T_co]) -> bool: ... - def issubset(self, __s: Iterable[object]) -> bool: ... - def issuperset(self, __s: Iterable[object]) -> bool: ... - def symmetric_difference(self, __s: Iterable[_T_co]) -> frozenset[_T_co]: ... + def isdisjoint(self, s: Iterable[_T_co], /) -> bool: ... + def issubset(self, s: Iterable[object], /) -> bool: ... + def issuperset(self, s: Iterable[object], /) -> bool: ... + def symmetric_difference(self, s: Iterable[_T_co], /) -> frozenset[_T_co]: ... def union(self, *s: Iterable[_S]) -> frozenset[_T_co | _S]: ... def __len__(self) -> int: ... - def __contains__(self, __o: object) -> bool: ... + def __contains__(self, o: object, /) -> bool: ... def __iter__(self) -> Iterator[_T_co]: ... - def __and__(self, __value: AbstractSet[_T_co]) -> frozenset[_T_co]: ... - def __or__(self, __value: AbstractSet[_S]) -> frozenset[_T_co | _S]: ... - def __sub__(self, __value: AbstractSet[_T_co]) -> frozenset[_T_co]: ... - def __xor__(self, __value: AbstractSet[_S]) -> frozenset[_T_co | _S]: ... - def __le__(self, __value: AbstractSet[object]) -> bool: ... - def __lt__(self, __value: AbstractSet[object]) -> bool: ... - def __ge__(self, __value: AbstractSet[object]) -> bool: ... - def __gt__(self, __value: AbstractSet[object]) -> bool: ... - def __eq__(self, __value: object) -> bool: ... + def __and__(self, value: AbstractSet[_T_co], /) -> frozenset[_T_co]: ... + def __or__(self, value: AbstractSet[_S], /) -> frozenset[_T_co | _S]: ... + def __sub__(self, value: AbstractSet[_T_co], /) -> frozenset[_T_co]: ... + def __xor__(self, value: AbstractSet[_S], /) -> frozenset[_T_co | _S]: ... + def __le__(self, value: AbstractSet[object], /) -> bool: ... + def __lt__(self, value: AbstractSet[object], /) -> bool: ... + def __ge__(self, value: AbstractSet[object], /) -> bool: ... + def __gt__(self, value: AbstractSet[object], /) -> bool: ... + def __eq__(self, value: object, /) -> bool: ... def __hash__(self) -> int: ... if sys.version_info >= (3, 9): - def __class_getitem__(cls, __item: Any) -> GenericAlias: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... class enumerate(Iterator[tuple[int, _T]]): def __new__(cls, iterable: Iterable[_T], start: int = ...) -> Self: ... def __iter__(self) -> Self: ... def __next__(self) -> tuple[int, _T]: ... if sys.version_info >= (3, 9): - def __class_getitem__(cls, __item: Any) -> GenericAlias: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... @final class range(Sequence[int]): @@ -1091,20 +1182,20 @@ class range(Sequence[int]): @property def step(self) -> int: ... @overload - def __new__(cls, __stop: SupportsIndex) -> Self: ... + def __new__(cls, stop: SupportsIndex, /) -> Self: ... @overload - def __new__(cls, __start: SupportsIndex, __stop: SupportsIndex, __step: SupportsIndex = ...) -> Self: ... - def count(self, __value: int) -> int: ... - def index(self, __value: int) -> int: ... # type: ignore[override] + def __new__(cls, start: SupportsIndex, stop: SupportsIndex, step: SupportsIndex = ..., /) -> Self: ... + def count(self, value: int, /) -> int: ... + def index(self, value: int, /) -> int: ... # type: ignore[override] def __len__(self) -> int: ... - def __eq__(self, __value: object) -> bool: ... + def __eq__(self, value: object, /) -> bool: ... def __hash__(self) -> int: ... - def __contains__(self, __key: object) -> bool: ... + def __contains__(self, key: object, /) -> bool: ... def __iter__(self) -> Iterator[int]: ... @overload - def __getitem__(self, __key: SupportsIndex) -> int: ... + def __getitem__(self, key: SupportsIndex, /) -> int: ... @overload - def __getitem__(self, __key: slice) -> range: ... + def __getitem__(self, key: slice, /) -> range: ... def __reversed__(self) -> Iterator[int]: ... class property: @@ -1119,12 +1210,12 @@ class property: fdel: Callable[[Any], None] | None = ..., doc: str | None = ..., ) -> None: ... - def getter(self, __fget: Callable[[Any], Any]) -> property: ... - def setter(self, __fset: Callable[[Any, Any], None]) -> property: ... - def deleter(self, __fdel: Callable[[Any], None]) -> property: ... - def __get__(self, __instance: Any, __owner: type | None = None) -> Any: ... - def __set__(self, __instance: Any, __value: Any) -> None: ... - def __delete__(self, __instance: Any) -> None: ... + def getter(self, fget: Callable[[Any], Any], /) -> property: ... + def setter(self, fset: Callable[[Any, Any], None], /) -> property: ... + def deleter(self, fdel: Callable[[Any], None], /) -> property: ... + def __get__(self, instance: Any, owner: type | None = None, /) -> Any: ... + def __set__(self, instance: Any, value: Any, /) -> None: ... + def __delete__(self, instance: Any, /) -> None: ... @final class _NotImplementedType(Any): @@ -1134,14 +1225,14 @@ class _NotImplementedType(Any): NotImplemented: _NotImplementedType -def abs(__x: SupportsAbs[_T]) -> _T: ... -def all(__iterable: Iterable[object]) -> bool: ... -def any(__iterable: Iterable[object]) -> bool: ... -def ascii(__obj: object) -> str: ... -def bin(__number: int | SupportsIndex) -> str: ... +def abs(x: SupportsAbs[_T], /) -> _T: ... +def all(iterable: Iterable[object], /) -> bool: ... +def any(iterable: Iterable[object], /) -> bool: ... +def ascii(obj: object, /) -> str: ... +def bin(number: int | SupportsIndex, /) -> str: ... def breakpoint(*args: Any, **kws: Any) -> None: ... -def callable(__obj: object) -> TypeGuard[Callable[..., object]]: ... -def chr(__i: int) -> str: ... +def callable(obj: object, /) -> TypeGuard[Callable[..., object]]: ... +def chr(i: int, /) -> str: ... # We define this here instead of using os.PathLike to avoid import cycle issues. # See https://github.com/python/typeshed/pull/991#issuecomment-288160993 @@ -1149,7 +1240,7 @@ class _PathLike(Protocol[AnyStr_co]): def __fspath__(self) -> AnyStr_co: ... if sys.version_info >= (3, 10): - def aiter(__async_iterable: SupportsAiter[_SupportsAnextT]) -> _SupportsAnextT: ... + def aiter(async_iterable: SupportsAiter[_SupportsAnextT], /) -> _SupportsAnextT: ... class _SupportsSynchronousAnext(Protocol[_AwaitableT_co]): def __anext__(self) -> _AwaitableT_co: ... @@ -1158,9 +1249,9 @@ if sys.version_info >= (3, 10): # `anext` is not, in fact, an async function. When default is not provided # `anext` is just a passthrough for `obj.__anext__` # See discussion in #7491 and pure-Python implementation of `anext` at https://github.com/python/cpython/blob/ea786a882b9ed4261eafabad6011bc7ef3b5bf94/Lib/test/test_asyncgen.py#L52-L80 - def anext(__i: _SupportsSynchronousAnext[_AwaitableT]) -> _AwaitableT: ... + def anext(i: _SupportsSynchronousAnext[_AwaitableT], /) -> _AwaitableT: ... @overload - async def anext(__i: SupportsAnext[_T], __default: _VT) -> _T | _VT: ... + async def anext(i: SupportsAnext[_T], default: _VT, /) -> _T | _VT: ... # compile() returns a CodeType, unless the flags argument includes PyCF_ONLY_AST (=1024), # in which case it returns ast.AST. We have overloads for flag 0 (the default) and for @@ -1210,86 +1301,86 @@ def compile( ) -> Any: ... def copyright() -> None: ... def credits() -> None: ... -def delattr(__obj: object, __name: str) -> None: ... -def dir(__o: object = ...) -> list[str]: ... +def delattr(obj: object, name: str, /) -> None: ... +def dir(o: object = ..., /) -> list[str]: ... @overload -def divmod(__x: SupportsDivMod[_T_contra, _T_co], __y: _T_contra) -> _T_co: ... +def divmod(x: SupportsDivMod[_T_contra, _T_co], y: _T_contra, /) -> _T_co: ... @overload -def divmod(__x: _T_contra, __y: SupportsRDivMod[_T_contra, _T_co]) -> _T_co: ... +def divmod(x: _T_contra, y: SupportsRDivMod[_T_contra, _T_co], /) -> _T_co: ... # The `globals` argument to `eval` has to be `dict[str, Any]` rather than `dict[str, object]` due to invariance. # (The `globals` argument has to be a "real dict", rather than any old mapping, unlike the `locals` argument.) def eval( - __source: str | ReadableBuffer | CodeType, - __globals: dict[str, Any] | None = None, - __locals: Mapping[str, object] | None = None, + source: str | ReadableBuffer | CodeType, globals: dict[str, Any] | None = None, locals: Mapping[str, object] | None = None, / ) -> Any: ... # Comment above regarding `eval` applies to `exec` as well if sys.version_info >= (3, 11): def exec( - __source: str | ReadableBuffer | CodeType, - __globals: dict[str, Any] | None = None, - __locals: Mapping[str, object] | None = None, + source: str | ReadableBuffer | CodeType, + globals: dict[str, Any] | None = None, + locals: Mapping[str, object] | None = None, + /, *, closure: tuple[_Cell, ...] | None = None, ) -> None: ... else: def exec( - __source: str | ReadableBuffer | CodeType, - __globals: dict[str, Any] | None = None, - __locals: Mapping[str, object] | None = None, + source: str | ReadableBuffer | CodeType, + globals: dict[str, Any] | None = None, + locals: Mapping[str, object] | None = None, + /, ) -> None: ... def exit(code: sys._ExitCode = None) -> NoReturn: ... class filter(Iterator[_T]): @overload - def __new__(cls, __function: None, __iterable: Iterable[_T | None]) -> Self: ... + def __new__(cls, function: None, iterable: Iterable[_T | None], /) -> Self: ... @overload - def __new__(cls, __function: Callable[[_S], TypeGuard[_T]], __iterable: Iterable[_S]) -> Self: ... + def __new__(cls, function: Callable[[_S], TypeGuard[_T]], iterable: Iterable[_S], /) -> Self: ... @overload - def __new__(cls, __function: Callable[[_T], Any], __iterable: Iterable[_T]) -> Self: ... + def __new__(cls, function: Callable[[_T], Any], iterable: Iterable[_T], /) -> Self: ... def __iter__(self) -> Self: ... def __next__(self) -> _T: ... -def format(__value: object, __format_spec: str = "") -> str: ... +def format(value: object, format_spec: str = "", /) -> str: ... @overload -def getattr(__o: object, __name: str) -> Any: ... +def getattr(o: object, name: str, /) -> Any: ... # While technically covered by the last overload, spelling out the types for None, bool # and basic containers help mypy out in some tricky situations involving type context # (aka bidirectional inference) @overload -def getattr(__o: object, __name: str, __default: None) -> Any | None: ... +def getattr(o: object, name: str, default: None, /) -> Any | None: ... @overload -def getattr(__o: object, __name: str, __default: bool) -> Any | bool: ... +def getattr(o: object, name: str, default: bool, /) -> Any | bool: ... @overload -def getattr(__o: object, __name: str, __default: list[Any]) -> Any | list[Any]: ... +def getattr(o: object, name: str, default: list[Any], /) -> Any | list[Any]: ... @overload -def getattr(__o: object, __name: str, __default: dict[Any, Any]) -> Any | dict[Any, Any]: ... +def getattr(o: object, name: str, default: dict[Any, Any], /) -> Any | dict[Any, Any]: ... @overload -def getattr(__o: object, __name: str, __default: _T) -> Any | _T: ... +def getattr(o: object, name: str, default: _T, /) -> Any | _T: ... def globals() -> dict[str, Any]: ... -def hasattr(__obj: object, __name: str) -> bool: ... -def hash(__obj: object) -> int: ... +def hasattr(obj: object, name: str, /) -> bool: ... +def hash(obj: object, /) -> int: ... def help(request: object = ...) -> None: ... -def hex(__number: int | SupportsIndex) -> str: ... -def id(__obj: object) -> int: ... -def input(__prompt: object = "") -> str: ... +def hex(number: int | SupportsIndex, /) -> str: ... +def id(obj: object, /) -> int: ... +def input(prompt: object = "", /) -> str: ... class _GetItemIterable(Protocol[_T_co]): - def __getitem__(self, __i: int) -> _T_co: ... + def __getitem__(self, i: int, /) -> _T_co: ... @overload -def iter(__object: SupportsIter[_SupportsNextT]) -> _SupportsNextT: ... +def iter(object: SupportsIter[_SupportsNextT], /) -> _SupportsNextT: ... @overload -def iter(__object: _GetItemIterable[_T]) -> Iterator[_T]: ... +def iter(object: _GetItemIterable[_T], /) -> Iterator[_T]: ... @overload -def iter(__object: Callable[[], _T | None], __sentinel: None) -> Iterator[_T]: ... +def iter(object: Callable[[], _T | None], sentinel: None, /) -> Iterator[_T]: ... @overload -def iter(__object: Callable[[], _T], __sentinel: object) -> Iterator[_T]: ... +def iter(object: Callable[[], _T], sentinel: object, /) -> Iterator[_T]: ... # Keep this alias in sync with unittest.case._ClassInfo if sys.version_info >= (3, 10): @@ -1297,50 +1388,53 @@ if sys.version_info >= (3, 10): else: _ClassInfo: TypeAlias = type | tuple[_ClassInfo, ...] -def isinstance(__obj: object, __class_or_tuple: _ClassInfo) -> bool: ... -def issubclass(__cls: type, __class_or_tuple: _ClassInfo) -> bool: ... -def len(__obj: Sized) -> int: ... +def isinstance(obj: object, class_or_tuple: _ClassInfo, /) -> bool: ... +def issubclass(cls: type, class_or_tuple: _ClassInfo, /) -> bool: ... +def len(obj: Sized, /) -> int: ... def license() -> None: ... def locals() -> dict[str, Any]: ... class map(Iterator[_S]): @overload - def __new__(cls, __func: Callable[[_T1], _S], __iter1: Iterable[_T1]) -> Self: ... + def __new__(cls, func: Callable[[_T1], _S], iter1: Iterable[_T1], /) -> Self: ... @overload - def __new__(cls, __func: Callable[[_T1, _T2], _S], __iter1: Iterable[_T1], __iter2: Iterable[_T2]) -> Self: ... + def __new__(cls, func: Callable[[_T1, _T2], _S], iter1: Iterable[_T1], iter2: Iterable[_T2], /) -> Self: ... @overload def __new__( - cls, __func: Callable[[_T1, _T2, _T3], _S], __iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3] + cls, func: Callable[[_T1, _T2, _T3], _S], iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], / ) -> Self: ... @overload def __new__( cls, - __func: Callable[[_T1, _T2, _T3, _T4], _S], - __iter1: Iterable[_T1], - __iter2: Iterable[_T2], - __iter3: Iterable[_T3], - __iter4: Iterable[_T4], + func: Callable[[_T1, _T2, _T3, _T4], _S], + iter1: Iterable[_T1], + iter2: Iterable[_T2], + iter3: Iterable[_T3], + iter4: Iterable[_T4], + /, ) -> Self: ... @overload def __new__( cls, - __func: Callable[[_T1, _T2, _T3, _T4, _T5], _S], - __iter1: Iterable[_T1], - __iter2: Iterable[_T2], - __iter3: Iterable[_T3], - __iter4: Iterable[_T4], - __iter5: Iterable[_T5], + func: Callable[[_T1, _T2, _T3, _T4, _T5], _S], + iter1: Iterable[_T1], + iter2: Iterable[_T2], + iter3: Iterable[_T3], + iter4: Iterable[_T4], + iter5: Iterable[_T5], + /, ) -> Self: ... @overload def __new__( cls, - __func: Callable[..., _S], - __iter1: Iterable[Any], - __iter2: Iterable[Any], - __iter3: Iterable[Any], - __iter4: Iterable[Any], - __iter5: Iterable[Any], - __iter6: Iterable[Any], + func: Callable[..., _S], + iter1: Iterable[Any], + iter2: Iterable[Any], + iter3: Iterable[Any], + iter4: Iterable[Any], + iter5: Iterable[Any], + iter6: Iterable[Any], + /, *iterables: Iterable[Any], ) -> Self: ... def __iter__(self) -> Self: ... @@ -1348,37 +1442,37 @@ class map(Iterator[_S]): @overload def max( - __arg1: SupportsRichComparisonT, __arg2: SupportsRichComparisonT, *_args: SupportsRichComparisonT, key: None = None + arg1: SupportsRichComparisonT, arg2: SupportsRichComparisonT, /, *_args: SupportsRichComparisonT, key: None = None ) -> SupportsRichComparisonT: ... @overload -def max(__arg1: _T, __arg2: _T, *_args: _T, key: Callable[[_T], SupportsRichComparison]) -> _T: ... +def max(arg1: _T, arg2: _T, /, *_args: _T, key: Callable[[_T], SupportsRichComparison]) -> _T: ... @overload -def max(__iterable: Iterable[SupportsRichComparisonT], *, key: None = None) -> SupportsRichComparisonT: ... +def max(iterable: Iterable[SupportsRichComparisonT], /, *, key: None = None) -> SupportsRichComparisonT: ... @overload -def max(__iterable: Iterable[_T], *, key: Callable[[_T], SupportsRichComparison]) -> _T: ... +def max(iterable: Iterable[_T], /, *, key: Callable[[_T], SupportsRichComparison]) -> _T: ... @overload -def max(__iterable: Iterable[SupportsRichComparisonT], *, key: None = None, default: _T) -> SupportsRichComparisonT | _T: ... +def max(iterable: Iterable[SupportsRichComparisonT], /, *, key: None = None, default: _T) -> SupportsRichComparisonT | _T: ... @overload -def max(__iterable: Iterable[_T1], *, key: Callable[[_T1], SupportsRichComparison], default: _T2) -> _T1 | _T2: ... +def max(iterable: Iterable[_T1], /, *, key: Callable[[_T1], SupportsRichComparison], default: _T2) -> _T1 | _T2: ... @overload def min( - __arg1: SupportsRichComparisonT, __arg2: SupportsRichComparisonT, *_args: SupportsRichComparisonT, key: None = None + arg1: SupportsRichComparisonT, arg2: SupportsRichComparisonT, /, *_args: SupportsRichComparisonT, key: None = None ) -> SupportsRichComparisonT: ... @overload -def min(__arg1: _T, __arg2: _T, *_args: _T, key: Callable[[_T], SupportsRichComparison]) -> _T: ... +def min(arg1: _T, arg2: _T, /, *_args: _T, key: Callable[[_T], SupportsRichComparison]) -> _T: ... @overload -def min(__iterable: Iterable[SupportsRichComparisonT], *, key: None = None) -> SupportsRichComparisonT: ... +def min(iterable: Iterable[SupportsRichComparisonT], /, *, key: None = None) -> SupportsRichComparisonT: ... @overload -def min(__iterable: Iterable[_T], *, key: Callable[[_T], SupportsRichComparison]) -> _T: ... +def min(iterable: Iterable[_T], /, *, key: Callable[[_T], SupportsRichComparison]) -> _T: ... @overload -def min(__iterable: Iterable[SupportsRichComparisonT], *, key: None = None, default: _T) -> SupportsRichComparisonT | _T: ... +def min(iterable: Iterable[SupportsRichComparisonT], /, *, key: None = None, default: _T) -> SupportsRichComparisonT | _T: ... @overload -def min(__iterable: Iterable[_T1], *, key: Callable[[_T1], SupportsRichComparison], default: _T2) -> _T1 | _T2: ... +def min(iterable: Iterable[_T1], /, *, key: Callable[[_T1], SupportsRichComparison], default: _T2) -> _T1 | _T2: ... @overload -def next(__i: SupportsNext[_T]) -> _T: ... +def next(i: SupportsNext[_T], /) -> _T: ... @overload -def next(__i: SupportsNext[_T], __default: _VT) -> _T | _VT: ... -def oct(__number: int | SupportsIndex) -> str: ... +def next(i: SupportsNext[_T], default: _VT, /) -> _T | _VT: ... +def oct(number: int | SupportsIndex, /) -> str: ... _Opener: TypeAlias = Callable[[str, int], int] @@ -1468,7 +1562,7 @@ def open( closefd: bool = True, opener: _Opener | None = None, ) -> IO[Any]: ... -def ord(__c: str | bytes | bytearray) -> int: ... +def ord(c: str | bytes | bytearray, /) -> int: ... class _SupportsWriteAndFlush(SupportsWrite[_T_contra], SupportsFlush, Protocol[_T_contra]): ... @@ -1489,13 +1583,13 @@ _E = TypeVar("_E", contravariant=True) _M = TypeVar("_M", contravariant=True) class _SupportsPow2(Protocol[_E, _T_co]): - def __pow__(self, __other: _E) -> _T_co: ... + def __pow__(self, other: _E, /) -> _T_co: ... class _SupportsPow3NoneOnly(Protocol[_E, _T_co]): - def __pow__(self, __other: _E, __modulo: None = None) -> _T_co: ... + def __pow__(self, other: _E, modulo: None = None, /) -> _T_co: ... class _SupportsPow3(Protocol[_E, _M, _T_co]): - def __pow__(self, __other: _E, __modulo: _M) -> _T_co: ... + def __pow__(self, other: _E, modulo: _M, /) -> _T_co: ... _SupportsSomeKindOfPow = ( # noqa: Y026 # TODO: Use TypeAlias once mypy bugs are fixed _SupportsPow2[Any, Any] | _SupportsPow3NoneOnly[Any, Any] | _SupportsPow3[Any, Any, Any] @@ -1544,14 +1638,14 @@ def quit(code: sys._ExitCode = None) -> NoReturn: ... class reversed(Iterator[_T]): @overload - def __new__(cls, __sequence: Reversible[_T]) -> Iterator[_T]: ... # type: ignore[misc] + def __new__(cls, sequence: Reversible[_T], /) -> Iterator[_T]: ... # type: ignore[misc] @overload - def __new__(cls, __sequence: SupportsLenAndGetItem[_T]) -> Iterator[_T]: ... # type: ignore[misc] + def __new__(cls, sequence: SupportsLenAndGetItem[_T], /) -> Iterator[_T]: ... # type: ignore[misc] def __iter__(self) -> Self: ... def __next__(self) -> _T: ... def __length_hint__(self) -> int: ... -def repr(__obj: object) -> str: ... +def repr(obj: object, /) -> str: ... # See https://github.com/python/typeshed/pull/9141 # and https://github.com/python/typeshed/pull/9151 @@ -1561,7 +1655,7 @@ class _SupportsRound1(Protocol[_T_co]): def __round__(self) -> _T_co: ... class _SupportsRound2(Protocol[_T_co]): - def __round__(self, __ndigits: int) -> _T_co: ... + def __round__(self, ndigits: int, /) -> _T_co: ... @overload def round(number: _SupportsRound1[_T], ndigits: None = None) -> _T: ... @@ -1570,13 +1664,13 @@ def round(number: _SupportsRound2[_T], ndigits: SupportsIndex) -> _T: ... # See https://github.com/python/typeshed/pull/6292#discussion_r748875189 # for why arg 3 of `setattr` should be annotated with `Any` and not `object` -def setattr(__obj: object, __name: str, __value: Any) -> None: ... +def setattr(obj: object, name: str, value: Any, /) -> None: ... @overload def sorted( - __iterable: Iterable[SupportsRichComparisonT], *, key: None = None, reverse: bool = False + iterable: Iterable[SupportsRichComparisonT], /, *, key: None = None, reverse: bool = False ) -> list[SupportsRichComparisonT]: ... @overload -def sorted(__iterable: Iterable[_T], *, key: Callable[[_T], SupportsRichComparison], reverse: bool = False) -> list[_T]: ... +def sorted(iterable: Iterable[_T], /, *, key: Callable[[_T], SupportsRichComparison], reverse: bool = False) -> list[_T]: ... _AddableT1 = TypeVar("_AddableT1", bound=SupportsAdd[Any, Any]) _AddableT2 = TypeVar("_AddableT2", bound=SupportsAdd[Any, Any]) @@ -1590,62 +1684,58 @@ _SupportsSumNoDefaultT = TypeVar("_SupportsSumNoDefaultT", bound=_SupportsSumWit # without creating many false-positive errors (see #7578). # Instead, we special-case the most common examples of this: bool and literal integers. @overload -def sum(__iterable: Iterable[bool], start: int = 0) -> int: ... # type: ignore[overload-overlap] +def sum(iterable: Iterable[bool | _LiteralInteger], /, start: int = 0) -> int: ... # type: ignore[overload-overlap] @overload -def sum(__iterable: Iterable[_SupportsSumNoDefaultT]) -> _SupportsSumNoDefaultT | Literal[0]: ... +def sum(iterable: Iterable[_SupportsSumNoDefaultT], /) -> _SupportsSumNoDefaultT | Literal[0]: ... @overload -def sum(__iterable: Iterable[_AddableT1], start: _AddableT2) -> _AddableT1 | _AddableT2: ... +def sum(iterable: Iterable[_AddableT1], /, start: _AddableT2) -> _AddableT1 | _AddableT2: ... # The argument to `vars()` has to have a `__dict__` attribute, so the second overload can't be annotated with `object` # (A "SupportsDunderDict" protocol doesn't work) # Use a type: ignore to make complaints about overlapping overloads go away @overload -def vars(__object: type) -> types.MappingProxyType[str, Any]: ... # type: ignore[overload-overlap] +def vars(object: type, /) -> types.MappingProxyType[str, Any]: ... # type: ignore[overload-overlap] @overload -def vars(__object: Any = ...) -> dict[str, Any]: ... +def vars(object: Any = ..., /) -> dict[str, Any]: ... class zip(Iterator[_T_co]): if sys.version_info >= (3, 10): @overload def __new__(cls, *, strict: bool = ...) -> zip[Any]: ... @overload - def __new__(cls, __iter1: Iterable[_T1], *, strict: bool = ...) -> zip[tuple[_T1]]: ... + def __new__(cls, iter1: Iterable[_T1], /, *, strict: bool = ...) -> zip[tuple[_T1]]: ... @overload - def __new__(cls, __iter1: Iterable[_T1], __iter2: Iterable[_T2], *, strict: bool = ...) -> zip[tuple[_T1, _T2]]: ... + def __new__(cls, iter1: Iterable[_T1], iter2: Iterable[_T2], /, *, strict: bool = ...) -> zip[tuple[_T1, _T2]]: ... @overload def __new__( - cls, __iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3], *, strict: bool = ... + cls, iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], /, *, strict: bool = ... ) -> zip[tuple[_T1, _T2, _T3]]: ... @overload def __new__( - cls, - __iter1: Iterable[_T1], - __iter2: Iterable[_T2], - __iter3: Iterable[_T3], - __iter4: Iterable[_T4], - *, - strict: bool = ..., + cls, iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], iter4: Iterable[_T4], /, *, strict: bool = ... ) -> zip[tuple[_T1, _T2, _T3, _T4]]: ... @overload def __new__( cls, - __iter1: Iterable[_T1], - __iter2: Iterable[_T2], - __iter3: Iterable[_T3], - __iter4: Iterable[_T4], - __iter5: Iterable[_T5], + iter1: Iterable[_T1], + iter2: Iterable[_T2], + iter3: Iterable[_T3], + iter4: Iterable[_T4], + iter5: Iterable[_T5], + /, *, strict: bool = ..., ) -> zip[tuple[_T1, _T2, _T3, _T4, _T5]]: ... @overload def __new__( cls, - __iter1: Iterable[Any], - __iter2: Iterable[Any], - __iter3: Iterable[Any], - __iter4: Iterable[Any], - __iter5: Iterable[Any], - __iter6: Iterable[Any], + iter1: Iterable[Any], + iter2: Iterable[Any], + iter3: Iterable[Any], + iter4: Iterable[Any], + iter5: Iterable[Any], + iter6: Iterable[Any], + /, *iterables: Iterable[Any], strict: bool = ..., ) -> zip[tuple[Any, ...]]: ... @@ -1653,33 +1743,29 @@ class zip(Iterator[_T_co]): @overload def __new__(cls) -> zip[Any]: ... @overload - def __new__(cls, __iter1: Iterable[_T1]) -> zip[tuple[_T1]]: ... + def __new__(cls, iter1: Iterable[_T1], /) -> zip[tuple[_T1]]: ... @overload - def __new__(cls, __iter1: Iterable[_T1], __iter2: Iterable[_T2]) -> zip[tuple[_T1, _T2]]: ... + def __new__(cls, iter1: Iterable[_T1], iter2: Iterable[_T2], /) -> zip[tuple[_T1, _T2]]: ... @overload - def __new__(cls, __iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3]) -> zip[tuple[_T1, _T2, _T3]]: ... + def __new__(cls, iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], /) -> zip[tuple[_T1, _T2, _T3]]: ... @overload def __new__( - cls, __iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3], __iter4: Iterable[_T4] + cls, iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], iter4: Iterable[_T4], / ) -> zip[tuple[_T1, _T2, _T3, _T4]]: ... @overload def __new__( - cls, - __iter1: Iterable[_T1], - __iter2: Iterable[_T2], - __iter3: Iterable[_T3], - __iter4: Iterable[_T4], - __iter5: Iterable[_T5], + cls, iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], iter4: Iterable[_T4], iter5: Iterable[_T5], / ) -> zip[tuple[_T1, _T2, _T3, _T4, _T5]]: ... @overload def __new__( cls, - __iter1: Iterable[Any], - __iter2: Iterable[Any], - __iter3: Iterable[Any], - __iter4: Iterable[Any], - __iter5: Iterable[Any], - __iter6: Iterable[Any], + iter1: Iterable[Any], + iter2: Iterable[Any], + iter3: Iterable[Any], + iter4: Iterable[Any], + iter5: Iterable[Any], + iter6: Iterable[Any], + /, *iterables: Iterable[Any], ) -> zip[tuple[Any, ...]]: ... @@ -1695,7 +1781,7 @@ def __import__( fromlist: Sequence[str] = (), level: int = 0, ) -> types.ModuleType: ... -def __build_class__(__func: Callable[[], _Cell | Any], __name: str, *bases: Any, metaclass: Any = ..., **kwds: Any) -> Any: ... +def __build_class__(func: Callable[[], _Cell | Any], name: str, /, *bases: Any, metaclass: Any = ..., **kwds: Any) -> Any: ... if sys.version_info >= (3, 10): from types import EllipsisType @@ -1722,12 +1808,12 @@ class BaseException: __suppress_context__: bool __traceback__: TracebackType | None def __init__(self, *args: object) -> None: ... - def __setstate__(self, __state: dict[str, Any] | None) -> None: ... - def with_traceback(self, __tb: TracebackType | None) -> Self: ... + def __setstate__(self, state: dict[str, Any] | None, /) -> None: ... + def with_traceback(self, tb: TracebackType | None, /) -> Self: ... if sys.version_info >= (3, 11): # only present after add_note() is called __notes__: list[str] - def add_note(self, __note: str) -> None: ... + def add_note(self, note: str, /) -> None: ... class GeneratorExit(BaseException): ... class KeyboardInterrupt(BaseException): ... @@ -1837,7 +1923,7 @@ class UnicodeDecodeError(UnicodeError): start: int end: int reason: str - def __init__(self, __encoding: str, __object: ReadableBuffer, __start: int, __end: int, __reason: str) -> None: ... + def __init__(self, encoding: str, object: ReadableBuffer, start: int, end: int, reason: str, /) -> None: ... class UnicodeEncodeError(UnicodeError): encoding: str @@ -1845,7 +1931,7 @@ class UnicodeEncodeError(UnicodeError): start: int end: int reason: str - def __init__(self, __encoding: str, __object: str, __start: int, __end: int, __reason: str) -> None: ... + def __init__(self, encoding: str, object: str, start: int, end: int, reason: str, /) -> None: ... class UnicodeTranslateError(UnicodeError): encoding: None @@ -1853,7 +1939,7 @@ class UnicodeTranslateError(UnicodeError): start: int end: int reason: str - def __init__(self, __object: str, __start: int, __end: int, __reason: str) -> None: ... + def __init__(self, object: str, start: int, end: int, reason: str, /) -> None: ... class Warning(Exception): ... class UserWarning(Warning): ... @@ -1878,60 +1964,60 @@ if sys.version_info >= (3, 11): # See `check_exception_group.py` for use-cases and comments. class BaseExceptionGroup(BaseException, Generic[_BaseExceptionT_co]): - def __new__(cls, __message: str, __exceptions: Sequence[_BaseExceptionT_co]) -> Self: ... - def __init__(self, __message: str, __exceptions: Sequence[_BaseExceptionT_co]) -> None: ... + def __new__(cls, message: str, exceptions: Sequence[_BaseExceptionT_co], /) -> Self: ... + def __init__(self, message: str, exceptions: Sequence[_BaseExceptionT_co], /) -> None: ... @property def message(self) -> str: ... @property def exceptions(self) -> tuple[_BaseExceptionT_co | BaseExceptionGroup[_BaseExceptionT_co], ...]: ... @overload def subgroup( - self, __condition: type[_ExceptionT] | tuple[type[_ExceptionT], ...] + self, condition: type[_ExceptionT] | tuple[type[_ExceptionT], ...], / ) -> ExceptionGroup[_ExceptionT] | None: ... @overload def subgroup( - self, __condition: type[_BaseExceptionT] | tuple[type[_BaseExceptionT], ...] + self, condition: type[_BaseExceptionT] | tuple[type[_BaseExceptionT], ...], / ) -> BaseExceptionGroup[_BaseExceptionT] | None: ... @overload def subgroup( - self, __condition: Callable[[_BaseExceptionT_co | Self], bool] + self, condition: Callable[[_BaseExceptionT_co | Self], bool], / ) -> BaseExceptionGroup[_BaseExceptionT_co] | None: ... @overload def split( - self, __condition: type[_ExceptionT] | tuple[type[_ExceptionT], ...] + self, condition: type[_ExceptionT] | tuple[type[_ExceptionT], ...], / ) -> tuple[ExceptionGroup[_ExceptionT] | None, BaseExceptionGroup[_BaseExceptionT_co] | None]: ... @overload def split( - self, __condition: type[_BaseExceptionT] | tuple[type[_BaseExceptionT], ...] + self, condition: type[_BaseExceptionT] | tuple[type[_BaseExceptionT], ...], / ) -> tuple[BaseExceptionGroup[_BaseExceptionT] | None, BaseExceptionGroup[_BaseExceptionT_co] | None]: ... @overload def split( - self, __condition: Callable[[_BaseExceptionT_co | Self], bool] + self, condition: Callable[[_BaseExceptionT_co | Self], bool], / ) -> tuple[BaseExceptionGroup[_BaseExceptionT_co] | None, BaseExceptionGroup[_BaseExceptionT_co] | None]: ... # In reality it is `NonEmptySequence`: @overload - def derive(self, __excs: Sequence[_ExceptionT]) -> ExceptionGroup[_ExceptionT]: ... + def derive(self, excs: Sequence[_ExceptionT], /) -> ExceptionGroup[_ExceptionT]: ... @overload - def derive(self, __excs: Sequence[_BaseExceptionT]) -> BaseExceptionGroup[_BaseExceptionT]: ... - def __class_getitem__(cls, __item: Any) -> GenericAlias: ... + def derive(self, excs: Sequence[_BaseExceptionT], /) -> BaseExceptionGroup[_BaseExceptionT]: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... class ExceptionGroup(BaseExceptionGroup[_ExceptionT_co], Exception): - def __new__(cls, __message: str, __exceptions: Sequence[_ExceptionT_co]) -> Self: ... - def __init__(self, __message: str, __exceptions: Sequence[_ExceptionT_co]) -> None: ... + def __new__(cls, message: str, exceptions: Sequence[_ExceptionT_co], /) -> Self: ... + def __init__(self, message: str, exceptions: Sequence[_ExceptionT_co], /) -> None: ... @property def exceptions(self) -> tuple[_ExceptionT_co | ExceptionGroup[_ExceptionT_co], ...]: ... # We accept a narrower type, but that's OK. @overload # type: ignore[override] def subgroup( - self, __condition: type[_ExceptionT] | tuple[type[_ExceptionT], ...] + self, condition: type[_ExceptionT] | tuple[type[_ExceptionT], ...], / ) -> ExceptionGroup[_ExceptionT] | None: ... @overload - def subgroup(self, __condition: Callable[[_ExceptionT_co | Self], bool]) -> ExceptionGroup[_ExceptionT_co] | None: ... + def subgroup(self, condition: Callable[[_ExceptionT_co | Self], bool], /) -> ExceptionGroup[_ExceptionT_co] | None: ... @overload # type: ignore[override] def split( - self, __condition: type[_ExceptionT] | tuple[type[_ExceptionT], ...] + self, condition: type[_ExceptionT] | tuple[type[_ExceptionT], ...], / ) -> tuple[ExceptionGroup[_ExceptionT] | None, ExceptionGroup[_ExceptionT_co] | None]: ... @overload def split( - self, __condition: Callable[[_ExceptionT_co | Self], bool] + self, condition: Callable[[_ExceptionT_co | Self], bool], / ) -> tuple[ExceptionGroup[_ExceptionT_co] | None, ExceptionGroup[_ExceptionT_co] | None]: ... diff --git a/mypy/typeshed/stdlib/bz2.pyi b/mypy/typeshed/stdlib/bz2.pyi index 620d59a6010c..a7837e1b9ff8 100644 --- a/mypy/typeshed/stdlib/bz2.pyi +++ b/mypy/typeshed/stdlib/bz2.pyi @@ -14,7 +14,7 @@ __all__ = ["BZ2File", "BZ2Compressor", "BZ2Decompressor", "open", "compress", "d class _ReadableFileobj(_compression._Reader, Protocol): ... class _WritableFileobj(Protocol): - def write(self, __b: bytes) -> object: ... + def write(self, b: bytes, /) -> object: ... # The following attributes and methods are optional: # def fileno(self) -> int: ... # def close(self) -> object: ... @@ -132,7 +132,7 @@ class BZ2File(BaseStream, IO[bytes]): @final class BZ2Compressor: def __init__(self, compresslevel: int = ...) -> None: ... - def compress(self, __data: ReadableBuffer) -> bytes: ... + def compress(self, data: ReadableBuffer, /) -> bytes: ... def flush(self) -> bytes: ... @final diff --git a/mypy/typeshed/stdlib/cProfile.pyi b/mypy/typeshed/stdlib/cProfile.pyi index c212f0383eaf..0cf6e34ec99e 100644 --- a/mypy/typeshed/stdlib/cProfile.pyi +++ b/mypy/typeshed/stdlib/cProfile.pyi @@ -24,7 +24,7 @@ class Profile(_lsprof.Profiler): def snapshot_stats(self) -> None: ... def run(self, cmd: str) -> Self: ... def runctx(self, cmd: str, globals: dict[str, Any], locals: dict[str, Any]) -> Self: ... - def runcall(self, __func: Callable[_P, _T], *args: _P.args, **kw: _P.kwargs) -> _T: ... + def runcall(self, func: Callable[_P, _T], /, *args: _P.args, **kw: _P.kwargs) -> _T: ... def __enter__(self) -> Self: ... def __exit__(self, *exc_info: Unused) -> None: ... diff --git a/mypy/typeshed/stdlib/cgi.pyi b/mypy/typeshed/stdlib/cgi.pyi index 91179c2ed8d5..d20be33e3d76 100644 --- a/mypy/typeshed/stdlib/cgi.pyi +++ b/mypy/typeshed/stdlib/cgi.pyi @@ -33,7 +33,7 @@ def parse_multipart( ) -> dict[str, list[Any]]: ... class _Environ(Protocol): - def __getitem__(self, __k: str) -> str: ... + def __getitem__(self, k: str, /) -> str: ... def keys(self) -> Iterable[str]: ... def parse_header(line: str) -> tuple[str, dict[str, str]]: ... diff --git a/mypy/typeshed/stdlib/cmath.pyi b/mypy/typeshed/stdlib/cmath.pyi index 8aad19dafcfb..fab9d10230f8 100644 --- a/mypy/typeshed/stdlib/cmath.pyi +++ b/mypy/typeshed/stdlib/cmath.pyi @@ -11,26 +11,26 @@ tau: float _C: TypeAlias = SupportsFloat | SupportsComplex | SupportsIndex | complex -def acos(__z: _C) -> complex: ... -def acosh(__z: _C) -> complex: ... -def asin(__z: _C) -> complex: ... -def asinh(__z: _C) -> complex: ... -def atan(__z: _C) -> complex: ... -def atanh(__z: _C) -> complex: ... -def cos(__z: _C) -> complex: ... -def cosh(__z: _C) -> complex: ... -def exp(__z: _C) -> complex: ... +def acos(z: _C, /) -> complex: ... +def acosh(z: _C, /) -> complex: ... +def asin(z: _C, /) -> complex: ... +def asinh(z: _C, /) -> complex: ... +def atan(z: _C, /) -> complex: ... +def atanh(z: _C, /) -> complex: ... +def cos(z: _C, /) -> complex: ... +def cosh(z: _C, /) -> complex: ... +def exp(z: _C, /) -> complex: ... def isclose(a: _C, b: _C, *, rel_tol: SupportsFloat = 1e-09, abs_tol: SupportsFloat = 0.0) -> bool: ... -def isinf(__z: _C) -> bool: ... -def isnan(__z: _C) -> bool: ... -def log(__x: _C, __base: _C = ...) -> complex: ... -def log10(__z: _C) -> complex: ... -def phase(__z: _C) -> float: ... -def polar(__z: _C) -> tuple[float, float]: ... -def rect(__r: float, __phi: float) -> complex: ... -def sin(__z: _C) -> complex: ... -def sinh(__z: _C) -> complex: ... -def sqrt(__z: _C) -> complex: ... -def tan(__z: _C) -> complex: ... -def tanh(__z: _C) -> complex: ... -def isfinite(__z: _C) -> bool: ... +def isinf(z: _C, /) -> bool: ... +def isnan(z: _C, /) -> bool: ... +def log(x: _C, base: _C = ..., /) -> complex: ... +def log10(z: _C, /) -> complex: ... +def phase(z: _C, /) -> float: ... +def polar(z: _C, /) -> tuple[float, float]: ... +def rect(r: float, phi: float, /) -> complex: ... +def sin(z: _C, /) -> complex: ... +def sinh(z: _C, /) -> complex: ... +def sqrt(z: _C, /) -> complex: ... +def tan(z: _C, /) -> complex: ... +def tanh(z: _C, /) -> complex: ... +def isfinite(z: _C, /) -> bool: ... diff --git a/mypy/typeshed/stdlib/codecs.pyi b/mypy/typeshed/stdlib/codecs.pyi index 7e192d91ddc5..6e53b780c473 100644 --- a/mypy/typeshed/stdlib/codecs.pyi +++ b/mypy/typeshed/stdlib/codecs.pyi @@ -59,13 +59,13 @@ BOM64_BE: Literal[b"\x00\x00\xfe\xff"] BOM64_LE: Literal[b"\xff\xfe\x00\x00"] class _WritableStream(Protocol): - def write(self, __data: bytes) -> object: ... - def seek(self, __offset: int, __whence: int) -> object: ... + def write(self, data: bytes, /) -> object: ... + def seek(self, offset: int, whence: int, /) -> object: ... def close(self) -> object: ... class _ReadableStream(Protocol): - def read(self, __size: int = ...) -> bytes: ... - def seek(self, __offset: int, __whence: int) -> object: ... + def read(self, size: int = ..., /) -> bytes: ... + def seek(self, offset: int, whence: int, /) -> object: ... def close(self) -> object: ... class _Stream(_WritableStream, _ReadableStream, Protocol): ... @@ -77,16 +77,16 @@ class _Stream(_WritableStream, _ReadableStream, Protocol): ... # They were much more common in Python 2 than in Python 3. class _Encoder(Protocol): - def __call__(self, __input: str, __errors: str = ...) -> tuple[bytes, int]: ... # signature of Codec().encode + def __call__(self, input: str, errors: str = ..., /) -> tuple[bytes, int]: ... # signature of Codec().encode class _Decoder(Protocol): - def __call__(self, __input: bytes, __errors: str = ...) -> tuple[str, int]: ... # signature of Codec().decode + def __call__(self, input: bytes, errors: str = ..., /) -> tuple[str, int]: ... # signature of Codec().decode class _StreamReader(Protocol): - def __call__(self, __stream: _ReadableStream, __errors: str = ...) -> StreamReader: ... + def __call__(self, stream: _ReadableStream, errors: str = ..., /) -> StreamReader: ... class _StreamWriter(Protocol): - def __call__(self, __stream: _WritableStream, __errors: str = ...) -> StreamWriter: ... + def __call__(self, stream: _WritableStream, errors: str = ..., /) -> StreamWriter: ... class _IncrementalEncoder(Protocol): def __call__(self, errors: str = ...) -> IncrementalEncoder: ... diff --git a/mypy/typeshed/stdlib/collections/__init__.pyi b/mypy/typeshed/stdlib/collections/__init__.pyi index 0df800a4a3be..1d23ecd66a8d 100644 --- a/mypy/typeshed/stdlib/collections/__init__.pyi +++ b/mypy/typeshed/stdlib/collections/__init__.pyi @@ -49,21 +49,21 @@ class UserDict(MutableMapping[_KT, _VT]): data: dict[_KT, _VT] # __init__ should be kept roughly in line with `dict.__init__`, which has the same semantics @overload - def __init__(self, __dict: None = None) -> None: ... + def __init__(self, dict: None = None, /) -> None: ... @overload - def __init__(self: UserDict[str, _VT], __dict: None = None, **kwargs: _VT) -> None: ... + def __init__(self: UserDict[str, _VT], dict: None = None, /, **kwargs: _VT) -> None: ... @overload - def __init__(self, __dict: SupportsKeysAndGetItem[_KT, _VT]) -> None: ... + def __init__(self, dict: SupportsKeysAndGetItem[_KT, _VT], /) -> None: ... @overload - def __init__(self: UserDict[str, _VT], __dict: SupportsKeysAndGetItem[str, _VT], **kwargs: _VT) -> None: ... + def __init__(self: UserDict[str, _VT], dict: SupportsKeysAndGetItem[str, _VT], /, **kwargs: _VT) -> None: ... @overload - def __init__(self, __iterable: Iterable[tuple[_KT, _VT]]) -> None: ... + def __init__(self, iterable: Iterable[tuple[_KT, _VT]], /) -> None: ... @overload - def __init__(self: UserDict[str, _VT], __iterable: Iterable[tuple[str, _VT]], **kwargs: _VT) -> None: ... + def __init__(self: UserDict[str, _VT], iterable: Iterable[tuple[str, _VT]], /, **kwargs: _VT) -> None: ... @overload - def __init__(self: UserDict[str, str], __iterable: Iterable[list[str]]) -> None: ... + def __init__(self: UserDict[str, str], iterable: Iterable[list[str]], /) -> None: ... @overload - def __init__(self: UserDict[bytes, bytes], __iterable: Iterable[list[bytes]]) -> None: ... + def __init__(self: UserDict[bytes, bytes], iterable: Iterable[list[bytes]], /) -> None: ... def __len__(self) -> int: ... def __getitem__(self, key: _KT) -> _VT: ... def __setitem__(self, key: _KT, item: _VT) -> None: ... @@ -137,8 +137,10 @@ class UserList(MutableSequence[_T]): def copy(self) -> Self: ... def __copy__(self) -> Self: ... def count(self, item: _T) -> int: ... - # All arguments are passed to `list.index` at runtime, so the signature should be kept in line with `list.index`. - def index(self, item: _T, __start: SupportsIndex = 0, __stop: SupportsIndex = sys.maxsize) -> int: ... + # The runtime signature is "item, *args", and the arguments are then passed + # to `list.index`. In order to give more precise types, we pretend that the + # `item` argument is positional-only. + def index(self, item: _T, start: SupportsIndex = 0, stop: SupportsIndex = sys.maxsize, /) -> int: ... # All arguments are passed to `list.sort` at runtime, so the signature should be kept in line with `list.sort`. @overload def sort(self: UserList[SupportsRichComparisonT], *, key: None = None, reverse: bool = False) -> None: ... @@ -200,8 +202,8 @@ class UserString(Sequence[UserString]): maketrans = str.maketrans def partition(self, sep: str) -> tuple[str, str, str]: ... if sys.version_info >= (3, 9): - def removeprefix(self, __prefix: str | UserString) -> Self: ... - def removesuffix(self, __suffix: str | UserString) -> Self: ... + def removeprefix(self, prefix: str | UserString, /) -> Self: ... + def removesuffix(self, suffix: str | UserString, /) -> Self: ... def replace(self, old: str | UserString, new: str | UserString, maxsplit: int = -1) -> Self: ... def rfind(self, sub: str | UserString, start: int = 0, end: int = sys.maxsize) -> int: ... @@ -227,58 +229,58 @@ class deque(MutableSequence[_T]): def __init__(self, *, maxlen: int | None = None) -> None: ... @overload def __init__(self, iterable: Iterable[_T], maxlen: int | None = None) -> None: ... - def append(self, __x: _T) -> None: ... - def appendleft(self, __x: _T) -> None: ... + def append(self, x: _T, /) -> None: ... + def appendleft(self, x: _T, /) -> None: ... def copy(self) -> Self: ... - def count(self, __x: _T) -> int: ... - def extend(self, __iterable: Iterable[_T]) -> None: ... - def extendleft(self, __iterable: Iterable[_T]) -> None: ... - def insert(self, __i: int, __x: _T) -> None: ... - def index(self, __x: _T, __start: int = 0, __stop: int = ...) -> int: ... + def count(self, x: _T, /) -> int: ... + def extend(self, iterable: Iterable[_T], /) -> None: ... + def extendleft(self, iterable: Iterable[_T], /) -> None: ... + def insert(self, i: int, x: _T, /) -> None: ... + def index(self, x: _T, start: int = 0, stop: int = ..., /) -> int: ... def pop(self) -> _T: ... # type: ignore[override] def popleft(self) -> _T: ... - def remove(self, __value: _T) -> None: ... - def rotate(self, __n: int = 1) -> None: ... + def remove(self, value: _T, /) -> None: ... + def rotate(self, n: int = 1, /) -> None: ... def __copy__(self) -> Self: ... def __len__(self) -> int: ... # These methods of deque don't take slices, unlike MutableSequence, hence the type: ignores - def __getitem__(self, __key: SupportsIndex) -> _T: ... # type: ignore[override] - def __setitem__(self, __key: SupportsIndex, __value: _T) -> None: ... # type: ignore[override] - def __delitem__(self, __key: SupportsIndex) -> None: ... # type: ignore[override] - def __contains__(self, __key: object) -> bool: ... + def __getitem__(self, key: SupportsIndex, /) -> _T: ... # type: ignore[override] + def __setitem__(self, key: SupportsIndex, value: _T, /) -> None: ... # type: ignore[override] + def __delitem__(self, key: SupportsIndex, /) -> None: ... # type: ignore[override] + def __contains__(self, key: object, /) -> bool: ... def __reduce__(self) -> tuple[type[Self], tuple[()], None, Iterator[_T]]: ... - def __iadd__(self, __value: Iterable[_T]) -> Self: ... - def __add__(self, __value: Self) -> Self: ... - def __mul__(self, __value: int) -> Self: ... - def __imul__(self, __value: int) -> Self: ... - def __lt__(self, __value: deque[_T]) -> bool: ... - def __le__(self, __value: deque[_T]) -> bool: ... - def __gt__(self, __value: deque[_T]) -> bool: ... - def __ge__(self, __value: deque[_T]) -> bool: ... - def __eq__(self, __value: object) -> bool: ... + def __iadd__(self, value: Iterable[_T], /) -> Self: ... + def __add__(self, value: Self, /) -> Self: ... + def __mul__(self, value: int, /) -> Self: ... + def __imul__(self, value: int, /) -> Self: ... + def __lt__(self, value: deque[_T], /) -> bool: ... + def __le__(self, value: deque[_T], /) -> bool: ... + def __gt__(self, value: deque[_T], /) -> bool: ... + def __ge__(self, value: deque[_T], /) -> bool: ... + def __eq__(self, value: object, /) -> bool: ... if sys.version_info >= (3, 9): - def __class_getitem__(cls, __item: Any) -> GenericAlias: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... class Counter(dict[_T, int], Generic[_T]): @overload - def __init__(self, __iterable: None = None) -> None: ... + def __init__(self, iterable: None = None, /) -> None: ... @overload - def __init__(self: Counter[str], __iterable: None = None, **kwargs: int) -> None: ... + def __init__(self: Counter[str], iterable: None = None, /, **kwargs: int) -> None: ... @overload - def __init__(self, __mapping: SupportsKeysAndGetItem[_T, int]) -> None: ... + def __init__(self, mapping: SupportsKeysAndGetItem[_T, int], /) -> None: ... @overload - def __init__(self, __iterable: Iterable[_T]) -> None: ... + def __init__(self, iterable: Iterable[_T], /) -> None: ... def copy(self) -> Self: ... def elements(self) -> Iterator[_T]: ... def most_common(self, n: int | None = None) -> list[tuple[_T, int]]: ... @classmethod def fromkeys(cls, iterable: Any, v: int | None = None) -> NoReturn: ... # type: ignore[override] @overload - def subtract(self, __iterable: None = None) -> None: ... + def subtract(self, iterable: None = None, /) -> None: ... @overload - def subtract(self, __mapping: Mapping[_T, int]) -> None: ... + def subtract(self, mapping: Mapping[_T, int], /) -> None: ... @overload - def subtract(self, __iterable: Iterable[_T]) -> None: ... + def subtract(self, iterable: Iterable[_T], /) -> None: ... # Unlike dict.update(), use Mapping instead of SupportsKeysAndGetItem for the first overload # (source code does an `isinstance(other, Mapping)` check) # @@ -286,11 +288,11 @@ class Counter(dict[_T, int], Generic[_T]): # (if it were `Iterable[_T] | Iterable[tuple[_T, int]]`, # the tuples would be added as keys, breaking type safety) @overload # type: ignore[override] - def update(self, __m: Mapping[_T, int], **kwargs: int) -> None: ... + def update(self, m: Mapping[_T, int], /, **kwargs: int) -> None: ... @overload - def update(self, __iterable: Iterable[_T], **kwargs: int) -> None: ... + def update(self, iterable: Iterable[_T], /, **kwargs: int) -> None: ... @overload - def update(self, __iterable: None = None, **kwargs: int) -> None: ... + def update(self, iterable: None = None, /, **kwargs: int) -> None: ... def __missing__(self, key: _T) -> int: ... def __delitem__(self, elem: object) -> None: ... if sys.version_info >= (3, 10): @@ -371,16 +373,16 @@ class OrderedDict(dict[_KT, _VT], Reversible[_KT], Generic[_KT, _VT]): def pop(self, key: _KT, default: _VT) -> _VT: ... @overload def pop(self, key: _KT, default: _T) -> _VT | _T: ... - def __eq__(self, __value: object) -> bool: ... + def __eq__(self, value: object, /) -> bool: ... if sys.version_info >= (3, 9): @overload - def __or__(self, __value: dict[_KT, _VT]) -> Self: ... + def __or__(self, value: dict[_KT, _VT], /) -> Self: ... @overload - def __or__(self, __value: dict[_T1, _T2]) -> OrderedDict[_KT | _T1, _VT | _T2]: ... + def __or__(self, value: dict[_T1, _T2], /) -> OrderedDict[_KT | _T1, _VT | _T2]: ... @overload - def __ror__(self, __value: dict[_KT, _VT]) -> Self: ... + def __ror__(self, value: dict[_KT, _VT], /) -> Self: ... @overload - def __ror__(self, __value: dict[_T1, _T2]) -> OrderedDict[_KT | _T1, _VT | _T2]: ... # type: ignore[misc] + def __ror__(self, value: dict[_T1, _T2], /) -> OrderedDict[_KT | _T1, _VT | _T2]: ... # type: ignore[misc] class defaultdict(dict[_KT, _VT]): default_factory: Callable[[], _VT] | None @@ -389,39 +391,41 @@ class defaultdict(dict[_KT, _VT]): @overload def __init__(self: defaultdict[str, _VT], **kwargs: _VT) -> None: ... @overload - def __init__(self, __default_factory: Callable[[], _VT] | None) -> None: ... + def __init__(self, default_factory: Callable[[], _VT] | None, /) -> None: ... @overload - def __init__(self: defaultdict[str, _VT], __default_factory: Callable[[], _VT] | None, **kwargs: _VT) -> None: ... + def __init__(self: defaultdict[str, _VT], default_factory: Callable[[], _VT] | None, /, **kwargs: _VT) -> None: ... @overload - def __init__(self, __default_factory: Callable[[], _VT] | None, __map: SupportsKeysAndGetItem[_KT, _VT]) -> None: ... + def __init__(self, default_factory: Callable[[], _VT] | None, map: SupportsKeysAndGetItem[_KT, _VT], /) -> None: ... @overload def __init__( self: defaultdict[str, _VT], - __default_factory: Callable[[], _VT] | None, - __map: SupportsKeysAndGetItem[str, _VT], + default_factory: Callable[[], _VT] | None, + map: SupportsKeysAndGetItem[str, _VT], + /, **kwargs: _VT, ) -> None: ... @overload - def __init__(self, __default_factory: Callable[[], _VT] | None, __iterable: Iterable[tuple[_KT, _VT]]) -> None: ... + def __init__(self, default_factory: Callable[[], _VT] | None, iterable: Iterable[tuple[_KT, _VT]], /) -> None: ... @overload def __init__( self: defaultdict[str, _VT], - __default_factory: Callable[[], _VT] | None, - __iterable: Iterable[tuple[str, _VT]], + default_factory: Callable[[], _VT] | None, + iterable: Iterable[tuple[str, _VT]], + /, **kwargs: _VT, ) -> None: ... - def __missing__(self, __key: _KT) -> _VT: ... + def __missing__(self, key: _KT, /) -> _VT: ... def __copy__(self) -> Self: ... def copy(self) -> Self: ... if sys.version_info >= (3, 9): @overload - def __or__(self, __value: dict[_KT, _VT]) -> Self: ... + def __or__(self, value: dict[_KT, _VT], /) -> Self: ... @overload - def __or__(self, __value: dict[_T1, _T2]) -> defaultdict[_KT | _T1, _VT | _T2]: ... + def __or__(self, value: dict[_T1, _T2], /) -> defaultdict[_KT | _T1, _VT | _T2]: ... @overload - def __ror__(self, __value: dict[_KT, _VT]) -> Self: ... + def __ror__(self, value: dict[_KT, _VT], /) -> Self: ... @overload - def __ror__(self, __value: dict[_T1, _T2]) -> defaultdict[_KT | _T1, _VT | _T2]: ... # type: ignore[misc] + def __ror__(self, value: dict[_T1, _T2], /) -> defaultdict[_KT | _T1, _VT | _T2]: ... # type: ignore[misc] class ChainMap(MutableMapping[_KT, _VT]): maps: list[MutableMapping[_KT, _VT]] @@ -457,10 +461,14 @@ class ChainMap(MutableMapping[_KT, _VT]): # All arguments to `fromkeys` are passed to `dict.fromkeys` at runtime, so the signature should be kept in line with `dict.fromkeys`. @classmethod @overload - def fromkeys(cls, iterable: Iterable[_T], __value: None = None) -> ChainMap[_T, Any | None]: ... + def fromkeys(cls, iterable: Iterable[_T]) -> ChainMap[_T, Any | None]: ... @classmethod @overload - def fromkeys(cls, __iterable: Iterable[_T], __value: _S) -> ChainMap[_T, _S]: ... + # Special-case None: the user probably wants to add non-None values later. + def fromkeys(cls, iterable: Iterable[_T], value: None, /) -> ChainMap[_T, Any | None]: ... + @classmethod + @overload + def fromkeys(cls, iterable: Iterable[_T], value: _S, /) -> ChainMap[_T, _S]: ... if sys.version_info >= (3, 9): @overload def __or__(self, other: Mapping[_KT, _VT]) -> Self: ... diff --git a/mypy/typeshed/stdlib/compileall.pyi b/mypy/typeshed/stdlib/compileall.pyi index 7f101bf79f6d..9fb3608f2979 100644 --- a/mypy/typeshed/stdlib/compileall.pyi +++ b/mypy/typeshed/stdlib/compileall.pyi @@ -6,7 +6,7 @@ from typing import Any, Protocol __all__ = ["compile_dir", "compile_file", "compile_path"] class _SupportsSearch(Protocol): - def search(self, __string: str) -> Any: ... + def search(self, string: str, /) -> Any: ... if sys.version_info >= (3, 10): def compile_dir( diff --git a/mypy/typeshed/stdlib/concurrent/futures/_base.pyi b/mypy/typeshed/stdlib/concurrent/futures/_base.pyi index 9ea4d5dff6fb..7dfdda224013 100644 --- a/mypy/typeshed/stdlib/concurrent/futures/_base.pyi +++ b/mypy/typeshed/stdlib/concurrent/futures/_base.pyi @@ -1,7 +1,7 @@ import sys import threading from _typeshed import Unused -from collections.abc import Callable, Iterable, Iterator +from collections.abc import Callable, Collection, Iterable, Iterator from logging import Logger from types import TracebackType from typing import Any, Generic, Literal, NamedTuple, Protocol, TypeVar @@ -58,7 +58,7 @@ class Future(Generic[_T]): class Executor: if sys.version_info >= (3, 9): - def submit(self, __fn: Callable[_P, _T], *args: _P.args, **kwargs: _P.kwargs) -> Future[_T]: ... + def submit(self, fn: Callable[_P, _T], /, *args: _P.args, **kwargs: _P.kwargs) -> Future[_T]: ... else: def submit(self, fn: Callable[_P, _T], *args: _P.args, **kwargs: _P.kwargs) -> Future[_T]: ... @@ -91,9 +91,15 @@ class DoneAndNotDoneFutures(NamedTuple, Generic[_T]): done: set[Future[_T]] not_done: set[Future[_T]] -def wait( - fs: Iterable[Future[_T]], timeout: float | None = None, return_when: str = "ALL_COMPLETED" -) -> DoneAndNotDoneFutures[_T]: ... +if sys.version_info >= (3, 9): + def wait( + fs: Iterable[Future[_T]], timeout: float | None = None, return_when: str = "ALL_COMPLETED" + ) -> DoneAndNotDoneFutures[_T]: ... + +else: + def wait( + fs: Collection[Future[_T]], timeout: float | None = None, return_when: str = "ALL_COMPLETED" + ) -> DoneAndNotDoneFutures[_T]: ... class _Waiter: event: threading.Event diff --git a/mypy/typeshed/stdlib/contextlib.pyi b/mypy/typeshed/stdlib/contextlib.pyi index eb4e95b33509..f82bb4b7b6ad 100644 --- a/mypy/typeshed/stdlib/contextlib.pyi +++ b/mypy/typeshed/stdlib/contextlib.pyi @@ -42,7 +42,7 @@ class AbstractContextManager(Protocol[_T_co]): def __enter__(self) -> _T_co: ... @abstractmethod 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, / ) -> bool | None: ... @runtime_checkable @@ -50,7 +50,7 @@ class AbstractAsyncContextManager(Protocol[_T_co]): async def __aenter__(self) -> _T_co: ... @abstractmethod async def __aexit__( - 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, / ) -> bool | None: ... class ContextDecorator: @@ -145,12 +145,12 @@ class redirect_stderr(_RedirectStream[_T_io]): ... class ExitStack(metaclass=abc.ABCMeta): def enter_context(self, cm: AbstractContextManager[_T]) -> _T: ... def push(self, exit: _CM_EF) -> _CM_EF: ... - def callback(self, __callback: Callable[_P, _T], *args: _P.args, **kwds: _P.kwargs) -> Callable[_P, _T]: ... + def callback(self, callback: Callable[_P, _T], /, *args: _P.args, **kwds: _P.kwargs) -> Callable[_P, _T]: ... def pop_all(self) -> Self: ... def close(self) -> None: ... 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, / ) -> bool: ... _ExitCoroFunc: TypeAlias = Callable[ @@ -165,15 +165,15 @@ class AsyncExitStack(metaclass=abc.ABCMeta): async def enter_async_context(self, cm: AbstractAsyncContextManager[_T]) -> _T: ... def push(self, exit: _CM_EF) -> _CM_EF: ... def push_async_exit(self, exit: _ACM_EF) -> _ACM_EF: ... - def callback(self, __callback: Callable[_P, _T], *args: _P.args, **kwds: _P.kwargs) -> Callable[_P, _T]: ... + def callback(self, callback: Callable[_P, _T], /, *args: _P.args, **kwds: _P.kwargs) -> Callable[_P, _T]: ... def push_async_callback( - self, __callback: Callable[_P, Awaitable[_T]], *args: _P.args, **kwds: _P.kwargs + self, callback: Callable[_P, Awaitable[_T]], /, *args: _P.args, **kwds: _P.kwargs ) -> Callable[_P, Awaitable[_T]]: ... def pop_all(self) -> Self: ... async def aclose(self) -> None: ... async def __aenter__(self) -> Self: ... async def __aexit__( - 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, / ) -> bool: ... if sys.version_info >= (3, 10): diff --git a/mypy/typeshed/stdlib/contextvars.pyi b/mypy/typeshed/stdlib/contextvars.pyi index 3245cdd5dad2..ceb9085fa187 100644 --- a/mypy/typeshed/stdlib/contextvars.pyi +++ b/mypy/typeshed/stdlib/contextvars.pyi @@ -24,11 +24,11 @@ class ContextVar(Generic[_T]): @overload def get(self) -> _T: ... @overload - def get(self, __default: _T) -> _T: ... + def get(self, default: _T, /) -> _T: ... @overload - def get(self, __default: _D) -> _D | _T: ... - def set(self, __value: _T) -> Token[_T]: ... - def reset(self, __token: Token[_T]) -> None: ... + def get(self, default: _D, /) -> _D | _T: ... + def set(self, value: _T, /) -> Token[_T]: ... + def reset(self, token: Token[_T], /) -> None: ... if sys.version_info >= (3, 9): def __class_getitem__(cls, item: Any) -> GenericAlias: ... @@ -50,14 +50,14 @@ def copy_context() -> Context: ... class Context(Mapping[ContextVar[Any], Any]): def __init__(self) -> None: ... @overload - def get(self, __key: ContextVar[_T], __default: None = None) -> _T | None: ... + def get(self, key: ContextVar[_T], default: None = None, /) -> _T | None: ... @overload - def get(self, __key: ContextVar[_T], __default: _T) -> _T: ... + def get(self, key: ContextVar[_T], default: _T, /) -> _T: ... @overload - def get(self, __key: ContextVar[_T], __default: _D) -> _T | _D: ... + def get(self, key: ContextVar[_T], default: _D, /) -> _T | _D: ... def run(self, callable: Callable[_P, _T], *args: _P.args, **kwargs: _P.kwargs) -> _T: ... def copy(self) -> Context: ... - def __getitem__(self, __key: ContextVar[_T]) -> _T: ... + def __getitem__(self, key: ContextVar[_T], /) -> _T: ... def __iter__(self) -> Iterator[ContextVar[Any]]: ... def __len__(self) -> int: ... - def __eq__(self, __value: object) -> bool: ... + def __eq__(self, value: object, /) -> bool: ... diff --git a/mypy/typeshed/stdlib/curses/__init__.pyi b/mypy/typeshed/stdlib/curses/__init__.pyi index db44fa6a6be7..2a82ae9bda22 100644 --- a/mypy/typeshed/stdlib/curses/__init__.pyi +++ b/mypy/typeshed/stdlib/curses/__init__.pyi @@ -18,4 +18,4 @@ if sys.platform != "win32": COLORS: int COLOR_PAIRS: int - def wrapper(__func: Callable[Concatenate[_CursesWindow, _P], _T], *arg: _P.args, **kwds: _P.kwargs) -> _T: ... + def wrapper(func: Callable[Concatenate[_CursesWindow, _P], _T], /, *arg: _P.args, **kwds: _P.kwargs) -> _T: ... diff --git a/mypy/typeshed/stdlib/curses/panel.pyi b/mypy/typeshed/stdlib/curses/panel.pyi index 30803791f039..403ae9b50019 100644 --- a/mypy/typeshed/stdlib/curses/panel.pyi +++ b/mypy/typeshed/stdlib/curses/panel.pyi @@ -20,6 +20,6 @@ if sys.platform != "win32": def window(self) -> _CursesWindow: ... def bottom_panel() -> _Curses_Panel: ... - def new_panel(__win: _CursesWindow) -> _Curses_Panel: ... + def new_panel(win: _CursesWindow, /) -> _Curses_Panel: ... def top_panel() -> _Curses_Panel: ... def update_panels() -> _Curses_Panel: ... diff --git a/mypy/typeshed/stdlib/dataclasses.pyi b/mypy/typeshed/stdlib/dataclasses.pyi index 389a159a915f..00e0d31d092a 100644 --- a/mypy/typeshed/stdlib/dataclasses.pyi +++ b/mypy/typeshed/stdlib/dataclasses.pyi @@ -55,9 +55,9 @@ def astuple(obj: DataclassInstance) -> tuple[Any, ...]: ... @overload def astuple(obj: DataclassInstance, *, tuple_factory: Callable[[list[Any]], _T]) -> _T: ... @overload -def dataclass(__cls: None) -> Callable[[type[_T]], type[_T]]: ... +def dataclass(cls: None, /) -> Callable[[type[_T]], type[_T]]: ... @overload -def dataclass(__cls: type[_T]) -> type[_T]: ... +def dataclass(cls: type[_T], /) -> type[_T]: ... if sys.version_info >= (3, 11): @overload @@ -227,16 +227,18 @@ if sys.version_info >= (3, 9): else: class _InitVarMeta(type): # Not used, instead `InitVar.__class_getitem__` is called. - def __getitem__(self, params: Any) -> InitVar[Any]: ... + # pyright ignore is needed because pyright (not unreasonably) thinks this + # is an invalid use of InitVar. + def __getitem__(self, params: Any) -> InitVar[Any]: ... # pyright: ignore class InitVar(Generic[_T], metaclass=_InitVarMeta): type: Type[_T] def __init__(self, type: Type[_T]) -> None: ... if sys.version_info >= (3, 9): @overload - def __class_getitem__(cls, type: Type[_T]) -> InitVar[_T]: ... + def __class_getitem__(cls, type: Type[_T]) -> InitVar[_T]: ... # pyright: ignore @overload - def __class_getitem__(cls, type: Any) -> InitVar[Any]: ... + def __class_getitem__(cls, type: Any) -> InitVar[Any]: ... # pyright: ignore if sys.version_info >= (3, 12): def make_dataclass( @@ -310,4 +312,4 @@ else: frozen: bool = False, ) -> type: ... -def replace(__obj: _DataclassT, **changes: Any) -> _DataclassT: ... +def replace(obj: _DataclassT, /, **changes: Any) -> _DataclassT: ... diff --git a/mypy/typeshed/stdlib/datetime.pyi b/mypy/typeshed/stdlib/datetime.pyi index 852208cd83a1..7b890ca010dc 100644 --- a/mypy/typeshed/stdlib/datetime.pyi +++ b/mypy/typeshed/stdlib/datetime.pyi @@ -14,12 +14,12 @@ MAXYEAR: Literal[9999] class tzinfo: @abstractmethod - def tzname(self, __dt: datetime | None) -> str | None: ... + def tzname(self, dt: datetime | None, /) -> str | None: ... @abstractmethod - def utcoffset(self, __dt: datetime | None) -> timedelta | None: ... + def utcoffset(self, dt: datetime | None, /) -> timedelta | None: ... @abstractmethod - def dst(self, __dt: datetime | None) -> timedelta | None: ... - def fromutc(self, __dt: datetime) -> datetime: ... + def dst(self, dt: datetime | None, /) -> timedelta | None: ... + def fromutc(self, dt: datetime, /) -> datetime: ... # Alias required to avoid name conflicts with date(time).tzinfo. _TzInfo: TypeAlias = tzinfo @@ -30,11 +30,11 @@ class timezone(tzinfo): min: ClassVar[timezone] max: ClassVar[timezone] def __init__(self, offset: timedelta, name: str = ...) -> None: ... - def tzname(self, __dt: datetime | None) -> str: ... - def utcoffset(self, __dt: datetime | None) -> timedelta: ... - def dst(self, __dt: datetime | None) -> None: ... + def tzname(self, dt: datetime | None, /) -> str: ... + def utcoffset(self, dt: datetime | None, /) -> timedelta: ... + def dst(self, dt: datetime | None, /) -> None: ... def __hash__(self) -> int: ... - def __eq__(self, __value: object) -> bool: ... + def __eq__(self, value: object, /) -> bool: ... if sys.version_info >= (3, 11): UTC: timezone @@ -51,13 +51,13 @@ class date: resolution: ClassVar[timedelta] def __new__(cls, year: SupportsIndex, month: SupportsIndex, day: SupportsIndex) -> Self: ... @classmethod - def fromtimestamp(cls, __timestamp: float) -> Self: ... + def fromtimestamp(cls, timestamp: float, /) -> Self: ... @classmethod def today(cls) -> Self: ... @classmethod - def fromordinal(cls, __n: int) -> Self: ... + def fromordinal(cls, n: int, /) -> Self: ... @classmethod - def fromisoformat(cls, __date_string: str) -> Self: ... + def fromisoformat(cls, date_string: str, /) -> Self: ... @classmethod def fromisocalendar(cls, year: int, week: int, day: int) -> Self: ... @property @@ -73,26 +73,26 @@ class date: if sys.version_info >= (3, 12): def strftime(self, format: str) -> str: ... else: - def strftime(self, __format: str) -> str: ... + def strftime(self, format: str, /) -> str: ... - def __format__(self, __fmt: str) -> str: ... + def __format__(self, fmt: str, /) -> str: ... def isoformat(self) -> str: ... def timetuple(self) -> struct_time: ... def toordinal(self) -> int: ... def replace(self, year: SupportsIndex = ..., month: SupportsIndex = ..., day: SupportsIndex = ...) -> Self: ... - def __le__(self, __value: date) -> bool: ... - def __lt__(self, __value: date) -> bool: ... - def __ge__(self, __value: date) -> bool: ... - def __gt__(self, __value: date) -> bool: ... - def __eq__(self, __value: object) -> bool: ... - def __add__(self, __value: timedelta) -> Self: ... - def __radd__(self, __value: timedelta) -> Self: ... + def __le__(self, value: date, /) -> bool: ... + def __lt__(self, value: date, /) -> bool: ... + def __ge__(self, value: date, /) -> bool: ... + def __gt__(self, value: date, /) -> bool: ... + def __eq__(self, value: object, /) -> bool: ... + def __add__(self, value: timedelta, /) -> Self: ... + def __radd__(self, value: timedelta, /) -> Self: ... @overload - def __sub__(self, __value: datetime) -> NoReturn: ... + def __sub__(self, value: datetime, /) -> NoReturn: ... @overload - def __sub__(self, __value: Self) -> timedelta: ... + def __sub__(self, value: Self, /) -> timedelta: ... @overload - def __sub__(self, __value: timedelta) -> Self: ... + def __sub__(self, value: timedelta, /) -> Self: ... def __hash__(self) -> int: ... def weekday(self) -> int: ... def isoweekday(self) -> int: ... @@ -127,24 +127,24 @@ class time: def tzinfo(self) -> _TzInfo | None: ... @property def fold(self) -> int: ... - def __le__(self, __value: time) -> bool: ... - def __lt__(self, __value: time) -> bool: ... - def __ge__(self, __value: time) -> bool: ... - def __gt__(self, __value: time) -> bool: ... - def __eq__(self, __value: object) -> bool: ... + def __le__(self, value: time, /) -> bool: ... + def __lt__(self, value: time, /) -> bool: ... + def __ge__(self, value: time, /) -> bool: ... + def __gt__(self, value: time, /) -> bool: ... + def __eq__(self, value: object, /) -> bool: ... def __hash__(self) -> int: ... def isoformat(self, timespec: str = ...) -> str: ... @classmethod - def fromisoformat(cls, __time_string: str) -> Self: ... + def fromisoformat(cls, time_string: str, /) -> Self: ... # On <3.12, the name of the parameter in the pure-Python implementation # didn't match the name in the C implementation, # meaning it is only *safe* to pass it as a keyword argument on 3.12+ if sys.version_info >= (3, 12): def strftime(self, format: str) -> str: ... else: - def strftime(self, __format: str) -> str: ... + def strftime(self, format: str, /) -> str: ... - def __format__(self, __fmt: str) -> str: ... + def __format__(self, fmt: str, /) -> str: ... def utcoffset(self) -> timedelta | None: ... def tzname(self) -> str | None: ... def dst(self) -> timedelta | None: ... @@ -183,30 +183,30 @@ class timedelta: @property def microseconds(self) -> int: ... def total_seconds(self) -> float: ... - def __add__(self, __value: timedelta) -> timedelta: ... - def __radd__(self, __value: timedelta) -> timedelta: ... - def __sub__(self, __value: timedelta) -> timedelta: ... - def __rsub__(self, __value: timedelta) -> timedelta: ... + def __add__(self, value: timedelta, /) -> timedelta: ... + def __radd__(self, value: timedelta, /) -> timedelta: ... + def __sub__(self, value: timedelta, /) -> timedelta: ... + def __rsub__(self, value: timedelta, /) -> timedelta: ... def __neg__(self) -> timedelta: ... def __pos__(self) -> timedelta: ... def __abs__(self) -> timedelta: ... - def __mul__(self, __value: float) -> timedelta: ... - def __rmul__(self, __value: float) -> timedelta: ... + def __mul__(self, value: float, /) -> timedelta: ... + def __rmul__(self, value: float, /) -> timedelta: ... @overload - def __floordiv__(self, __value: timedelta) -> int: ... + def __floordiv__(self, value: timedelta, /) -> int: ... @overload - def __floordiv__(self, __value: int) -> timedelta: ... + def __floordiv__(self, value: int, /) -> timedelta: ... @overload - def __truediv__(self, __value: timedelta) -> float: ... + def __truediv__(self, value: timedelta, /) -> float: ... @overload - def __truediv__(self, __value: float) -> timedelta: ... - def __mod__(self, __value: timedelta) -> timedelta: ... - def __divmod__(self, __value: timedelta) -> tuple[int, timedelta]: ... - def __le__(self, __value: timedelta) -> bool: ... - def __lt__(self, __value: timedelta) -> bool: ... - def __ge__(self, __value: timedelta) -> bool: ... - def __gt__(self, __value: timedelta) -> bool: ... - def __eq__(self, __value: object) -> bool: ... + def __truediv__(self, value: float, /) -> timedelta: ... + def __mod__(self, value: timedelta, /) -> timedelta: ... + def __divmod__(self, value: timedelta, /) -> tuple[int, timedelta]: ... + def __le__(self, value: timedelta, /) -> bool: ... + def __lt__(self, value: timedelta, /) -> bool: ... + def __ge__(self, value: timedelta, /) -> bool: ... + def __gt__(self, value: timedelta, /) -> bool: ... + def __eq__(self, value: object, /) -> bool: ... def __bool__(self) -> bool: ... def __hash__(self) -> int: ... @@ -246,11 +246,11 @@ class datetime(date): def fromtimestamp(cls, timestamp: float, tz: _TzInfo | None = ...) -> Self: ... else: @classmethod - def fromtimestamp(cls, __timestamp: float, tz: _TzInfo | None = ...) -> Self: ... + def fromtimestamp(cls, timestamp: float, /, tz: _TzInfo | None = ...) -> Self: ... @classmethod @deprecated("Use timezone-aware objects to represent datetimes in UTC; e.g. by calling .fromtimestamp(datetime.UTC)") - def utcfromtimestamp(cls, __t: float) -> Self: ... + def utcfromtimestamp(cls, t: float, /) -> Self: ... @classmethod def now(cls, tz: _TzInfo | None = None) -> Self: ... @classmethod @@ -279,17 +279,17 @@ class datetime(date): def astimezone(self, tz: _TzInfo | None = ...) -> Self: ... def isoformat(self, sep: str = ..., timespec: str = ...) -> str: ... @classmethod - def strptime(cls, __date_string: str, __format: str) -> Self: ... + def strptime(cls, date_string: str, format: str, /) -> Self: ... def utcoffset(self) -> timedelta | None: ... def tzname(self) -> str | None: ... def dst(self) -> timedelta | None: ... - def __le__(self, __value: datetime) -> bool: ... # type: ignore[override] - def __lt__(self, __value: datetime) -> bool: ... # type: ignore[override] - def __ge__(self, __value: datetime) -> bool: ... # type: ignore[override] - def __gt__(self, __value: datetime) -> bool: ... # type: ignore[override] - def __eq__(self, __value: object) -> bool: ... + def __le__(self, value: datetime, /) -> bool: ... # type: ignore[override] + def __lt__(self, value: datetime, /) -> bool: ... # type: ignore[override] + def __ge__(self, value: datetime, /) -> bool: ... # type: ignore[override] + def __gt__(self, value: datetime, /) -> bool: ... # type: ignore[override] + def __eq__(self, value: object, /) -> bool: ... def __hash__(self) -> int: ... @overload # type: ignore[override] - def __sub__(self, __value: Self) -> timedelta: ... + def __sub__(self, value: Self, /) -> timedelta: ... @overload - def __sub__(self, __value: timedelta) -> Self: ... + def __sub__(self, value: timedelta, /) -> Self: ... diff --git a/mypy/typeshed/stdlib/dbm/gnu.pyi b/mypy/typeshed/stdlib/dbm/gnu.pyi index 0f818ed5e7f5..8b562019fcfb 100644 --- a/mypy/typeshed/stdlib/dbm/gnu.pyi +++ b/mypy/typeshed/stdlib/dbm/gnu.pyi @@ -38,4 +38,4 @@ if sys.platform != "win32": __new__: None # type: ignore[assignment] __init__: None # type: ignore[assignment] - def open(__filename: str, __flags: str = "r", __mode: int = 0o666) -> _gdbm: ... + def open(filename: str, flags: str = "r", mode: int = 0o666, /) -> _gdbm: ... diff --git a/mypy/typeshed/stdlib/dbm/ndbm.pyi b/mypy/typeshed/stdlib/dbm/ndbm.pyi index a7a6d52d8f19..5eb84e6949fc 100644 --- a/mypy/typeshed/stdlib/dbm/ndbm.pyi +++ b/mypy/typeshed/stdlib/dbm/ndbm.pyi @@ -34,4 +34,4 @@ if sys.platform != "win32": __new__: None # type: ignore[assignment] __init__: None # type: ignore[assignment] - def open(__filename: str, __flags: str = "r", __mode: int = 0o666) -> _dbm: ... + def open(filename: str, flags: str = "r", mode: int = 0o666, /) -> _dbm: ... diff --git a/mypy/typeshed/stdlib/distutils/core.pyi b/mypy/typeshed/stdlib/distutils/core.pyi index 7b0bdd1b35bd..c41c8ba19a8b 100644 --- a/mypy/typeshed/stdlib/distutils/core.pyi +++ b/mypy/typeshed/stdlib/distutils/core.pyi @@ -53,5 +53,5 @@ def setup( password: str = ..., fullname: str = ..., **attrs: Any, -) -> None: ... +) -> Distribution: ... def run_setup(script_name: str, script_args: list[str] | None = None, stop_after: str = "run") -> Distribution: ... diff --git a/mypy/typeshed/stdlib/email/charset.pyi b/mypy/typeshed/stdlib/email/charset.pyi index f8de016ab8bf..2d12df337207 100644 --- a/mypy/typeshed/stdlib/email/charset.pyi +++ b/mypy/typeshed/stdlib/email/charset.pyi @@ -25,7 +25,7 @@ class Charset: @overload def body_encode(self, string: str | bytes) -> str: ... def __eq__(self, other: object) -> bool: ... - def __ne__(self, __value: object) -> bool: ... + def __ne__(self, value: object, /) -> bool: ... def add_charset( charset: str, header_enc: int | None = None, body_enc: int | None = None, output_charset: str | None = None diff --git a/mypy/typeshed/stdlib/email/header.pyi b/mypy/typeshed/stdlib/email/header.pyi index fc9d73331bae..212132c6be18 100644 --- a/mypy/typeshed/stdlib/email/header.pyi +++ b/mypy/typeshed/stdlib/email/header.pyi @@ -17,7 +17,7 @@ class Header: def append(self, s: bytes | bytearray | str, charset: Charset | str | None = None, errors: str = "strict") -> None: ... def encode(self, splitchars: str = ";, \t", maxlinelen: int | None = None, linesep: str = "\n") -> str: ... def __eq__(self, other: object) -> bool: ... - def __ne__(self, __value: object) -> bool: ... + def __ne__(self, value: object, /) -> bool: ... # decode_header() either returns list[tuple[str, None]] if the header # contains no encoded parts, or list[tuple[bytes, str | None]] if the header diff --git a/mypy/typeshed/stdlib/email/headerregistry.pyi b/mypy/typeshed/stdlib/email/headerregistry.pyi index 93a2b3ee72b5..2ffdca9b2f22 100644 --- a/mypy/typeshed/stdlib/email/headerregistry.pyi +++ b/mypy/typeshed/stdlib/email/headerregistry.pyi @@ -140,9 +140,9 @@ class MessageIDHeader: class _HeaderParser(Protocol): max_count: ClassVar[Literal[1] | None] @staticmethod - def value_parser(__value: str) -> TokenList: ... + def value_parser(value: str, /) -> TokenList: ... @classmethod - def parse(cls, __value: str, __kwds: dict[str, Any]) -> None: ... + def parse(cls, value: str, kwds: dict[str, Any], /) -> None: ... class HeaderRegistry: registry: dict[str, type[_HeaderParser]] diff --git a/mypy/typeshed/stdlib/email/message.pyi b/mypy/typeshed/stdlib/email/message.pyi index 7384f3146a8e..d7d7e8c8e908 100644 --- a/mypy/typeshed/stdlib/email/message.pyi +++ b/mypy/typeshed/stdlib/email/message.pyi @@ -15,16 +15,20 @@ _PayloadType: TypeAlias = Message | str _EncodedPayloadType: TypeAlias = Message | bytes _MultipartPayloadType: TypeAlias = list[_PayloadType] _CharsetType: TypeAlias = Charset | str | None -# Type returned by Policy.header_fetch_parse, AnyOf[str | Header] +# Type returned by Policy.header_fetch_parse, often str or Header. _HeaderType: TypeAlias = Any -_HeaderTypeParam: TypeAlias = str | Header +# Type accepted by Policy.header_store_parse. +_HeaderTypeParam: TypeAlias = str | Header | Any class _SupportsEncodeToPayload(Protocol): - def encode(self, __encoding: str) -> _PayloadType | _MultipartPayloadType | _SupportsDecodeToPayload: ... + def encode(self, encoding: str, /) -> _PayloadType | _MultipartPayloadType | _SupportsDecodeToPayload: ... class _SupportsDecodeToPayload(Protocol): - def decode(self, __encoding: str, __errors: str) -> _PayloadType | _MultipartPayloadType: ... + def decode(self, encoding: str, errors: str, /) -> _PayloadType | _MultipartPayloadType: ... +# TODO: This class should be generic over the header policy and/or the header +# value types allowed by the policy. This depends on PEP 696 support +# (https://github.com/python/typeshed/issues/11422). class Message: policy: Policy # undocumented preamble: str | None diff --git a/mypy/typeshed/stdlib/encodings/utf_8.pyi b/mypy/typeshed/stdlib/encodings/utf_8.pyi index 0de51026f9f5..bb745399eb8c 100644 --- a/mypy/typeshed/stdlib/encodings/utf_8.pyi +++ b/mypy/typeshed/stdlib/encodings/utf_8.pyi @@ -6,16 +6,16 @@ class IncrementalEncoder(codecs.IncrementalEncoder): class IncrementalDecoder(codecs.BufferedIncrementalDecoder): @staticmethod - def _buffer_decode(__data: ReadableBuffer, __errors: str | None = None, __final: bool = False) -> tuple[str, int]: ... + def _buffer_decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ... class StreamWriter(codecs.StreamWriter): @staticmethod - def encode(__str: str, __errors: str | None = None) -> tuple[bytes, int]: ... + def encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ... class StreamReader(codecs.StreamReader): @staticmethod - def decode(__data: ReadableBuffer, __errors: str | None = None, __final: bool = False) -> tuple[str, int]: ... + def decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ... def getregentry() -> codecs.CodecInfo: ... -def encode(__str: str, __errors: str | None = None) -> tuple[bytes, int]: ... +def encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ... def decode(input: ReadableBuffer, errors: str | None = "strict") -> tuple[str, int]: ... diff --git a/mypy/typeshed/stdlib/fcntl.pyi b/mypy/typeshed/stdlib/fcntl.pyi index 7e5af76c2aae..ccf638205bbe 100644 --- a/mypy/typeshed/stdlib/fcntl.pyi +++ b/mypy/typeshed/stdlib/fcntl.pyi @@ -106,22 +106,22 @@ if sys.platform != "win32": FICLONERANGE: int @overload - def fcntl(__fd: FileDescriptorLike, __cmd: int, __arg: int = 0) -> int: ... + def fcntl(fd: FileDescriptorLike, cmd: int, arg: int = 0, /) -> int: ... @overload - def fcntl(__fd: FileDescriptorLike, __cmd: int, __arg: str | ReadOnlyBuffer) -> bytes: ... + def fcntl(fd: FileDescriptorLike, cmd: int, arg: str | ReadOnlyBuffer, /) -> bytes: ... # If arg is an int, return int @overload - def ioctl(__fd: FileDescriptorLike, __request: int, __arg: int = 0, __mutate_flag: bool = True) -> int: ... + def ioctl(fd: FileDescriptorLike, request: int, arg: int = 0, mutate_flag: bool = True, /) -> int: ... # The return type works as follows: # - If arg is a read-write buffer, return int if mutate_flag is True, otherwise bytes # - If arg is a read-only buffer, return bytes (and ignore the value of mutate_flag) # We can't represent that precisely as we can't distinguish between read-write and read-only # buffers, so we add overloads for a few unambiguous cases and use Any for the rest. @overload - def ioctl(__fd: FileDescriptorLike, __request: int, __arg: bytes, __mutate_flag: bool = True) -> bytes: ... + def ioctl(fd: FileDescriptorLike, request: int, arg: bytes, mutate_flag: bool = True, /) -> bytes: ... @overload - def ioctl(__fd: FileDescriptorLike, __request: int, __arg: WriteableBuffer, __mutate_flag: Literal[False]) -> bytes: ... + def ioctl(fd: FileDescriptorLike, request: int, arg: WriteableBuffer, mutate_flag: Literal[False], /) -> bytes: ... @overload - def ioctl(__fd: FileDescriptorLike, __request: int, __arg: Buffer, __mutate_flag: bool = True) -> Any: ... - def flock(__fd: FileDescriptorLike, __operation: int) -> None: ... - def lockf(__fd: FileDescriptorLike, __cmd: int, __len: int = 0, __start: int = 0, __whence: int = 0) -> Any: ... + def ioctl(fd: FileDescriptorLike, request: int, arg: Buffer, mutate_flag: bool = True, /) -> Any: ... + def flock(fd: FileDescriptorLike, operation: int, /) -> None: ... + def lockf(fd: FileDescriptorLike, cmd: int, len: int = 0, start: int = 0, whence: int = 0, /) -> Any: ... diff --git a/mypy/typeshed/stdlib/fractions.pyi b/mypy/typeshed/stdlib/fractions.pyi index 43eaa21bd039..086aff50344c 100644 --- a/mypy/typeshed/stdlib/fractions.pyi +++ b/mypy/typeshed/stdlib/fractions.pyi @@ -24,7 +24,7 @@ class Fraction(Rational): @overload def __new__(cls, numerator: int | Rational = 0, denominator: int | Rational | None = None) -> Self: ... @overload - def __new__(cls, __value: float | Decimal | str) -> Self: ... + def __new__(cls, value: float | Decimal | str, /) -> Self: ... @classmethod def from_float(cls, f: float) -> Self: ... @classmethod diff --git a/mypy/typeshed/stdlib/functools.pyi b/mypy/typeshed/stdlib/functools.pyi index d3f702bcef4f..27550cfe08e6 100644 --- a/mypy/typeshed/stdlib/functools.pyi +++ b/mypy/typeshed/stdlib/functools.pyi @@ -36,9 +36,9 @@ _PWrapper = ParamSpec("_PWrapper") _RWrapper = TypeVar("_RWrapper") @overload -def reduce(__function: Callable[[_T, _S], _T], __sequence: Iterable[_S], __initial: _T) -> _T: ... +def reduce(function: Callable[[_T, _S], _T], sequence: Iterable[_S], initial: _T, /) -> _T: ... @overload -def reduce(__function: Callable[[_T, _T], _T], __sequence: Iterable[_T]) -> _T: ... +def reduce(function: Callable[[_T, _T], _T], sequence: Iterable[_T], /) -> _T: ... class _CacheInfo(NamedTuple): hits: int @@ -61,7 +61,7 @@ class _lru_cache_wrapper(Generic[_T]): def cache_parameters(self) -> _CacheParameters: ... def __copy__(self) -> _lru_cache_wrapper[_T]: ... - def __deepcopy__(self, __memo: Any) -> _lru_cache_wrapper[_T]: ... + def __deepcopy__(self, memo: Any, /) -> _lru_cache_wrapper[_T]: ... @overload def lru_cache(maxsize: int | None = 128, typed: bool = False) -> Callable[[Callable[..., _T]], _lru_cache_wrapper[_T]]: ... @@ -129,8 +129,8 @@ class partial(Generic[_T]): def args(self) -> tuple[Any, ...]: ... @property def keywords(self) -> dict[str, Any]: ... - def __new__(cls, __func: Callable[..., _T], *args: Any, **kwargs: Any) -> Self: ... - def __call__(__self, *args: Any, **kwargs: Any) -> _T: ... + def __new__(cls, func: Callable[..., _T], /, *args: Any, **kwargs: Any) -> Self: ... + def __call__(self, /, *args: Any, **kwargs: Any) -> _T: ... if sys.version_info >= (3, 9): def __class_getitem__(cls, item: Any) -> GenericAlias: ... @@ -142,9 +142,9 @@ class partialmethod(Generic[_T]): args: tuple[Any, ...] keywords: dict[str, Any] @overload - def __init__(self, __func: Callable[..., _T], *args: Any, **keywords: Any) -> None: ... + def __init__(self, func: Callable[..., _T], /, *args: Any, **keywords: Any) -> None: ... @overload - def __init__(self, __func: _Descriptor, *args: Any, **keywords: Any) -> None: ... + def __init__(self, func: _Descriptor, /, *args: Any, **keywords: Any) -> None: ... def __get__(self, obj: Any, cls: type[Any] | None = None) -> Callable[..., _T]: ... @property def __isabstractmethod__(self) -> bool: ... @@ -166,7 +166,7 @@ class _SingleDispatchCallable(Generic[_T]): @overload def register(self, cls: type[Any], func: Callable[..., _T]) -> Callable[..., _T]: ... def _clear_cache(self) -> None: ... - def __call__(__self, *args: Any, **kwargs: Any) -> _T: ... + def __call__(self, /, *args: Any, **kwargs: Any) -> _T: ... def singledispatch(func: Callable[..., _T]) -> _SingleDispatchCallable[_T]: ... @@ -199,7 +199,7 @@ class cached_property(Generic[_T_co]): def __class_getitem__(cls, item: Any) -> GenericAlias: ... if sys.version_info >= (3, 9): - def cache(__user_function: Callable[..., _T]) -> _lru_cache_wrapper[_T]: ... + def cache(user_function: Callable[..., _T], /) -> _lru_cache_wrapper[_T]: ... def _make_key( args: tuple[Hashable, ...], diff --git a/mypy/typeshed/stdlib/gc.pyi b/mypy/typeshed/stdlib/gc.pyi index 914c41434791..31179add314c 100644 --- a/mypy/typeshed/stdlib/gc.pyi +++ b/mypy/typeshed/stdlib/gc.pyi @@ -27,11 +27,11 @@ def get_referents(*objs: Any) -> list[Any]: ... def get_referrers(*objs: Any) -> list[Any]: ... def get_stats() -> list[dict[str, Any]]: ... def get_threshold() -> tuple[int, int, int]: ... -def is_tracked(__obj: Any) -> bool: ... +def is_tracked(obj: Any, /) -> bool: ... if sys.version_info >= (3, 9): - def is_finalized(__obj: Any) -> bool: ... + def is_finalized(obj: Any, /) -> bool: ... def isenabled() -> bool: ... -def set_debug(__flags: int) -> None: ... +def set_debug(flags: int, /) -> None: ... def set_threshold(threshold0: int, threshold1: int = ..., threshold2: int = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/gzip.pyi b/mypy/typeshed/stdlib/gzip.pyi index 2c33d7cf5810..7f43795dd01f 100644 --- a/mypy/typeshed/stdlib/gzip.pyi +++ b/mypy/typeshed/stdlib/gzip.pyi @@ -22,15 +22,15 @@ FNAME: int # actually Literal[8] # undocumented FCOMMENT: int # actually Literal[16] # undocumented class _ReadableFileobj(Protocol): - def read(self, __n: int) -> bytes: ... - def seek(self, __n: int) -> object: ... + def read(self, n: int, /) -> bytes: ... + def seek(self, n: int, /) -> object: ... # The following attributes and methods are optional: # name: str # mode: str # def fileno() -> int: ... class _WritableFileobj(Protocol): - def write(self, __b: bytes) -> object: ... + def write(self, b: bytes, /) -> object: ... def flush(self) -> object: ... # The following attributes and methods are optional: # name: str diff --git a/mypy/typeshed/stdlib/hashlib.pyi b/mypy/typeshed/stdlib/hashlib.pyi index 38e846ab7eb3..93bd986c9d31 100644 --- a/mypy/typeshed/stdlib/hashlib.pyi +++ b/mypy/typeshed/stdlib/hashlib.pyi @@ -59,7 +59,7 @@ class _Hash: def copy(self) -> Self: ... def digest(self) -> bytes: ... def hexdigest(self) -> str: ... - def update(self, __data: ReadableBuffer) -> None: ... + def update(self, data: ReadableBuffer, /) -> None: ... if sys.version_info >= (3, 9): def new(name: str, data: ReadableBuffer = b"", *, usedforsecurity: bool = ...) -> _Hash: ... @@ -92,9 +92,9 @@ class _VarLenHash: name: str def __init__(self, data: ReadableBuffer = ...) -> None: ... def copy(self) -> _VarLenHash: ... - def digest(self, __length: int) -> bytes: ... - def hexdigest(self, __length: int) -> str: ... - def update(self, __data: ReadableBuffer) -> None: ... + def digest(self, length: int, /) -> bytes: ... + def hexdigest(self, length: int, /) -> str: ... + def update(self, data: ReadableBuffer, /) -> None: ... sha3_224 = _Hash sha3_256 = _Hash @@ -116,7 +116,8 @@ class _BlakeHash(_Hash): if sys.version_info >= (3, 9): def __init__( self, - __data: ReadableBuffer = ..., + data: ReadableBuffer = ..., + /, *, digest_size: int = ..., key: ReadableBuffer = ..., @@ -134,7 +135,8 @@ class _BlakeHash(_Hash): else: def __init__( self, - __data: ReadableBuffer = ..., + data: ReadableBuffer = ..., + /, *, digest_size: int = ..., key: ReadableBuffer = ..., @@ -157,9 +159,9 @@ if sys.version_info >= (3, 11): def getbuffer(self) -> ReadableBuffer: ... class _FileDigestFileObj(Protocol): - def readinto(self, __buf: bytearray) -> int: ... + def readinto(self, buf: bytearray, /) -> int: ... def readable(self) -> bool: ... def file_digest( - __fileobj: _BytesIOLike | _FileDigestFileObj, __digest: str | Callable[[], _Hash], *, _bufsize: int = 262144 + fileobj: _BytesIOLike | _FileDigestFileObj, digest: str | Callable[[], _Hash], /, *, _bufsize: int = 262144 ) -> _Hash: ... diff --git a/mypy/typeshed/stdlib/heapq.pyi b/mypy/typeshed/stdlib/heapq.pyi index 9198febd3cfa..7a3aa8b442a5 100644 --- a/mypy/typeshed/stdlib/heapq.pyi +++ b/mypy/typeshed/stdlib/heapq.pyi @@ -14,4 +14,4 @@ def merge( ) -> Iterable[_S]: ... def nlargest(n: int, iterable: Iterable[_S], key: Callable[[_S], SupportsRichComparison] | None = None) -> list[_S]: ... def nsmallest(n: int, iterable: Iterable[_S], key: Callable[[_S], SupportsRichComparison] | None = None) -> list[_S]: ... -def _heapify_max(__heap: list[Any]) -> None: ... # undocumented +def _heapify_max(heap: list[Any], /) -> None: ... # undocumented diff --git a/mypy/typeshed/stdlib/hmac.pyi b/mypy/typeshed/stdlib/hmac.pyi index 614121529416..ac1372dd1e9c 100644 --- a/mypy/typeshed/stdlib/hmac.pyi +++ b/mypy/typeshed/stdlib/hmac.pyi @@ -32,7 +32,7 @@ class HMAC: def copy(self) -> HMAC: ... @overload -def compare_digest(__a: ReadableBuffer, __b: ReadableBuffer) -> bool: ... +def compare_digest(a: ReadableBuffer, b: ReadableBuffer, /) -> bool: ... @overload -def compare_digest(__a: AnyStr, __b: AnyStr) -> bool: ... +def compare_digest(a: AnyStr, b: AnyStr, /) -> bool: ... def digest(key: SizedBuffer, msg: ReadableBuffer, digest: _DigestMod) -> bytes: ... diff --git a/mypy/typeshed/stdlib/imghdr.pyi b/mypy/typeshed/stdlib/imghdr.pyi index d0960a5a1c5c..6e1b858b8f32 100644 --- a/mypy/typeshed/stdlib/imghdr.pyi +++ b/mypy/typeshed/stdlib/imghdr.pyi @@ -6,8 +6,8 @@ __all__ = ["what"] class _ReadableBinary(Protocol): def tell(self) -> int: ... - def read(self, __size: int) -> bytes: ... - def seek(self, __offset: int) -> Any: ... + def read(self, size: int, /) -> bytes: ... + def seek(self, offset: int, /) -> Any: ... @overload def what(file: StrPath | _ReadableBinary, h: None = None) -> str | None: ... diff --git a/mypy/typeshed/stdlib/imp.pyi b/mypy/typeshed/stdlib/imp.pyi index b532f480fa13..ee5a0cd7bc72 100644 --- a/mypy/typeshed/stdlib/imp.pyi +++ b/mypy/typeshed/stdlib/imp.pyi @@ -45,7 +45,7 @@ class _FileLike(Protocol): def read(self) -> str | bytes: ... def close(self) -> Any: ... def __enter__(self) -> Any: ... - def __exit__(self, __typ: type[BaseException] | None, __exc: BaseException | None, __tb: TracebackType | None) -> Any: ... + def __exit__(self, typ: type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None, /) -> Any: ... # PathLike doesn't work for the pathname argument here def load_source(name: str, pathname: str, file: _FileLike | None = None) -> types.ModuleType: ... diff --git a/mypy/typeshed/stdlib/importlib/abc.pyi b/mypy/typeshed/stdlib/importlib/abc.pyi index 825eab7ffde2..75e78ed59172 100644 --- a/mypy/typeshed/stdlib/importlib/abc.pyi +++ b/mypy/typeshed/stdlib/importlib/abc.pyi @@ -72,7 +72,7 @@ if sys.version_info >= (3, 10): def invalidate_caches(self) -> None: ... # Not defined on the actual class, but expected to exist. def find_spec( - self, __fullname: str, __path: Sequence[str] | None, __target: types.ModuleType | None = ... + self, fullname: str, path: Sequence[str] | None, target: types.ModuleType | None = ..., / ) -> ModuleSpec | None: ... class PathEntryFinder(metaclass=ABCMeta): @@ -91,7 +91,7 @@ else: def invalidate_caches(self) -> None: ... # Not defined on the actual class, but expected to exist. def find_spec( - self, __fullname: str, __path: Sequence[str] | None, __target: types.ModuleType | None = ... + self, fullname: str, path: Sequence[str] | None, target: types.ModuleType | None = ..., / ) -> ModuleSpec | None: ... class PathEntryFinder(Finder): @@ -138,25 +138,25 @@ if sys.version_info >= (3, 9): def joinpath(self, *descendants: str) -> Traversable: ... else: @abstractmethod - def joinpath(self, __child: str) -> Traversable: ... + def joinpath(self, child: str, /) -> Traversable: ... # The documentation and runtime protocol allows *args, **kwargs arguments, # but this would mean that all implementers would have to support them, # which is not the case. @overload @abstractmethod - def open(self, __mode: Literal["r"] = "r", *, encoding: str | None = None, errors: str | None = None) -> IO[str]: ... + def open(self, mode: Literal["r"] = "r", /, *, encoding: str | None = None, errors: str | None = None) -> IO[str]: ... @overload @abstractmethod - def open(self, __mode: Literal["rb"]) -> IO[bytes]: ... + def open(self, mode: Literal["rb"], /) -> IO[bytes]: ... @property @abstractmethod def name(self) -> str: ... if sys.version_info >= (3, 10): - def __truediv__(self, __child: str) -> Traversable: ... + def __truediv__(self, child: str, /) -> Traversable: ... else: @abstractmethod - def __truediv__(self, __child: str) -> Traversable: ... + def __truediv__(self, child: str, /) -> Traversable: ... @abstractmethod def read_bytes(self) -> bytes: ... diff --git a/mypy/typeshed/stdlib/inspect.pyi b/mypy/typeshed/stdlib/inspect.pyi index 06a8ff6a3462..bb5ddc37c603 100644 --- a/mypy/typeshed/stdlib/inspect.pyi +++ b/mypy/typeshed/stdlib/inspect.pyi @@ -225,10 +225,10 @@ def isasyncgenfunction(obj: Callable[_P, Any]) -> TypeGuard[Callable[_P, AsyncGe def isasyncgenfunction(obj: object) -> TypeGuard[Callable[..., AsyncGeneratorType[Any, Any]]]: ... class _SupportsSet(Protocol[_T_cont, _V_cont]): - def __set__(self, __instance: _T_cont, __value: _V_cont) -> None: ... + def __set__(self, instance: _T_cont, value: _V_cont, /) -> None: ... class _SupportsDelete(Protocol[_T_cont]): - def __delete__(self, __instance: _T_cont) -> None: ... + def __delete__(self, instance: _T_cont, /) -> None: ... def isasyncgen(object: object) -> TypeGuard[AsyncGeneratorType[Any, Any]]: ... def istraceback(object: object) -> TypeGuard[TracebackType]: ... @@ -482,7 +482,7 @@ def formatargvalues( formatvalue: Callable[[Any], str] | None = ..., ) -> str: ... def getmro(cls: type) -> tuple[type, ...]: ... -def getcallargs(__func: Callable[_P, Any], *args: _P.args, **kwds: _P.kwargs) -> dict[str, Any]: ... +def getcallargs(func: Callable[_P, Any], /, *args: _P.args, **kwds: _P.kwargs) -> dict[str, Any]: ... class ClosureVars(NamedTuple): nonlocals: Mapping[str, Any] diff --git a/mypy/typeshed/stdlib/io.pyi b/mypy/typeshed/stdlib/io.pyi index 659b216c43dc..e7ed1b0b5ee5 100644 --- a/mypy/typeshed/stdlib/io.pyi +++ b/mypy/typeshed/stdlib/io.pyi @@ -63,15 +63,15 @@ class IOBase(metaclass=abc.ABCMeta): def isatty(self) -> bool: ... def readable(self) -> bool: ... read: Callable[..., Any] - def readlines(self, __hint: int = -1) -> list[bytes]: ... - def seek(self, __offset: int, __whence: int = ...) -> int: ... + def readlines(self, hint: int = -1, /) -> list[bytes]: ... + def seek(self, offset: int, whence: int = ..., /) -> int: ... def seekable(self) -> bool: ... def tell(self) -> int: ... - def truncate(self, __size: int | None = ...) -> int: ... + def truncate(self, size: int | None = ..., /) -> int: ... def writable(self) -> bool: ... write: Callable[..., Any] - def writelines(self, __lines: Iterable[ReadableBuffer]) -> None: ... - def readline(self, __size: int | None = -1) -> bytes: ... + def writelines(self, lines: Iterable[ReadableBuffer], /) -> None: ... + def readline(self, size: int | None = -1, /) -> bytes: ... def __del__(self) -> None: ... @property def closed(self) -> bool: ... @@ -79,18 +79,18 @@ class IOBase(metaclass=abc.ABCMeta): class RawIOBase(IOBase): def readall(self) -> bytes: ... - def readinto(self, __buffer: WriteableBuffer) -> int | None: ... - def write(self, __b: ReadableBuffer) -> int | None: ... - def read(self, __size: int = -1) -> bytes | None: ... + def readinto(self, buffer: WriteableBuffer, /) -> int | None: ... + def write(self, b: ReadableBuffer, /) -> int | None: ... + def read(self, size: int = -1, /) -> bytes | None: ... class BufferedIOBase(IOBase): raw: RawIOBase # This is not part of the BufferedIOBase API and may not exist on some implementations. def detach(self) -> RawIOBase: ... - def readinto(self, __buffer: WriteableBuffer) -> int: ... - def write(self, __buffer: ReadableBuffer) -> int: ... - def readinto1(self, __buffer: WriteableBuffer) -> int: ... - def read(self, __size: int | None = ...) -> bytes: ... - def read1(self, __size: int = ...) -> bytes: ... + def readinto(self, buffer: WriteableBuffer, /) -> int: ... + def write(self, buffer: ReadableBuffer, /) -> int: ... + def readinto1(self, buffer: WriteableBuffer, /) -> int: ... + def read(self, size: int | None = ..., /) -> bytes: ... + def read1(self, size: int = ..., /) -> bytes: ... class FileIO(RawIOBase, BinaryIO): # type: ignore[misc] # incompatible definitions of writelines in the base classes mode: str @@ -103,8 +103,8 @@ class FileIO(RawIOBase, BinaryIO): # type: ignore[misc] # incompatible definit ) -> None: ... @property def closefd(self) -> bool: ... - def write(self, __b: ReadableBuffer) -> int: ... - def read(self, __size: int = -1) -> bytes: ... + def write(self, b: ReadableBuffer, /) -> int: ... + def read(self, size: int = -1, /) -> bytes: ... def __enter__(self) -> Self: ... class BytesIO(BufferedIOBase, BinaryIO): # type: ignore[misc] # incompatible definitions of methods in the base classes @@ -116,25 +116,25 @@ class BytesIO(BufferedIOBase, BinaryIO): # type: ignore[misc] # incompatible d def __enter__(self) -> Self: ... def getvalue(self) -> bytes: ... def getbuffer(self) -> memoryview: ... - def read1(self, __size: int | None = -1) -> bytes: ... + def read1(self, size: int | None = -1, /) -> bytes: ... class BufferedReader(BufferedIOBase, BinaryIO): # type: ignore[misc] # incompatible definitions of methods in the base classes def __enter__(self) -> Self: ... def __init__(self, raw: RawIOBase, buffer_size: int = ...) -> None: ... - def peek(self, __size: int = 0) -> bytes: ... + def peek(self, size: int = 0, /) -> bytes: ... class BufferedWriter(BufferedIOBase, BinaryIO): # type: ignore[misc] # incompatible definitions of writelines in the base classes def __enter__(self) -> Self: ... def __init__(self, raw: RawIOBase, buffer_size: int = ...) -> None: ... - def write(self, __buffer: ReadableBuffer) -> int: ... + def write(self, buffer: ReadableBuffer, /) -> int: ... class BufferedRandom(BufferedReader, BufferedWriter): # type: ignore[misc] # incompatible definitions of methods in the base classes def __enter__(self) -> Self: ... - def seek(self, __target: int, __whence: int = 0) -> int: ... # stubtest needs this + def seek(self, target: int, whence: int = 0, /) -> int: ... # stubtest needs this class BufferedRWPair(BufferedIOBase): def __init__(self, reader: RawIOBase, writer: RawIOBase, buffer_size: int = ...) -> None: ... - def peek(self, __size: int = ...) -> bytes: ... + def peek(self, size: int = ..., /) -> bytes: ... class TextIOBase(IOBase): encoding: str @@ -143,11 +143,11 @@ class TextIOBase(IOBase): def __iter__(self) -> Iterator[str]: ... # type: ignore[override] def __next__(self) -> str: ... # type: ignore[override] def detach(self) -> BinaryIO: ... - def write(self, __s: str) -> int: ... - def writelines(self, __lines: Iterable[str]) -> None: ... # type: ignore[override] - def readline(self, __size: int = ...) -> str: ... # type: ignore[override] - def readlines(self, __hint: int = -1) -> list[str]: ... # type: ignore[override] - def read(self, __size: int | None = ...) -> str: ... + def write(self, s: str, /) -> int: ... + def writelines(self, lines: Iterable[str], /) -> None: ... # type: ignore[override] + def readline(self, size: int = ..., /) -> str: ... # type: ignore[override] + def readlines(self, hint: int = -1, /) -> list[str]: ... # type: ignore[override] + def read(self, size: int | None = ..., /) -> str: ... @type_check_only class _WrappedBuffer(Protocol): @@ -207,14 +207,14 @@ class TextIOWrapper(TextIOBase, TextIO): # type: ignore[misc] # incompatible d def __enter__(self) -> Self: ... def __iter__(self) -> Iterator[str]: ... # type: ignore[override] def __next__(self) -> str: ... # type: ignore[override] - def writelines(self, __lines: Iterable[str]) -> None: ... # type: ignore[override] - def readline(self, __size: int = -1) -> str: ... # type: ignore[override] - def readlines(self, __hint: int = -1) -> list[str]: ... # type: ignore[override] + def writelines(self, lines: Iterable[str], /) -> None: ... # type: ignore[override] + def readline(self, size: int = -1, /) -> str: ... # type: ignore[override] + def readlines(self, hint: int = -1, /) -> list[str]: ... # type: ignore[override] # Equals the "buffer" argument passed in to the constructor. def detach(self) -> BinaryIO: ... # TextIOWrapper's version of seek only supports a limited subset of # operations. - def seek(self, __cookie: int, __whence: int = 0) -> int: ... + def seek(self, cookie: int, whence: int = 0, /) -> int: ... class StringIO(TextIOWrapper): def __init__(self, initial_value: str | None = ..., newline: str | None = ...) -> None: ... @@ -229,10 +229,10 @@ class IncrementalNewlineDecoder(codecs.IncrementalDecoder): def decode(self, input: ReadableBuffer | str, final: bool = False) -> str: ... @property def newlines(self) -> str | tuple[str, ...] | None: ... - def setstate(self, __state: tuple[bytes, int]) -> None: ... + def setstate(self, state: tuple[bytes, int], /) -> None: ... if sys.version_info >= (3, 10): @overload - def text_encoding(__encoding: None, __stacklevel: int = 2) -> Literal["locale", "utf-8"]: ... + def text_encoding(encoding: None, stacklevel: int = 2, /) -> Literal["locale", "utf-8"]: ... @overload - def text_encoding(__encoding: _T, __stacklevel: int = 2) -> _T: ... + def text_encoding(encoding: _T, stacklevel: int = 2, /) -> _T: ... diff --git a/mypy/typeshed/stdlib/itertools.pyi b/mypy/typeshed/stdlib/itertools.pyi index 0e501e1ade4d..264064dcd682 100644 --- a/mypy/typeshed/stdlib/itertools.pyi +++ b/mypy/typeshed/stdlib/itertools.pyi @@ -35,7 +35,7 @@ class count(Iterator[_N]): def __iter__(self) -> Self: ... class cycle(Iterator[_T]): - def __init__(self, __iterable: Iterable[_T]) -> None: ... + def __init__(self, iterable: Iterable[_T], /) -> None: ... def __next__(self) -> _T: ... def __iter__(self) -> Self: ... @@ -62,9 +62,9 @@ class chain(Iterator[_T]): def __iter__(self) -> Self: ... @classmethod # We use type[Any] and not type[_S] to not lose the type inference from __iterable - def from_iterable(cls: type[Any], __iterable: Iterable[Iterable[_S]]) -> chain[_S]: ... + def from_iterable(cls: type[Any], iterable: Iterable[Iterable[_S]], /) -> chain[_S]: ... if sys.version_info >= (3, 9): - def __class_getitem__(cls, __item: Any) -> GenericAlias: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... class compress(Iterator[_T]): def __init__(self, data: Iterable[_T], selectors: Iterable[Any]) -> None: ... @@ -72,12 +72,12 @@ class compress(Iterator[_T]): def __next__(self) -> _T: ... class dropwhile(Iterator[_T]): - def __init__(self, __predicate: _Predicate[_T], __iterable: Iterable[_T]) -> None: ... + def __init__(self, predicate: _Predicate[_T], iterable: Iterable[_T], /) -> None: ... def __iter__(self) -> Self: ... def __next__(self) -> _T: ... class filterfalse(Iterator[_T]): - def __init__(self, __predicate: _Predicate[_T] | None, __iterable: Iterable[_T]) -> None: ... + def __init__(self, predicate: _Predicate[_T] | None, iterable: Iterable[_T], /) -> None: ... def __iter__(self) -> Self: ... def __next__(self) -> _T: ... @@ -91,74 +91,70 @@ class groupby(Iterator[tuple[_T_co, Iterator[_S_co]]], Generic[_T_co, _S_co]): class islice(Iterator[_T]): @overload - def __init__(self, __iterable: Iterable[_T], __stop: int | None) -> None: ... + def __init__(self, iterable: Iterable[_T], stop: int | None, /) -> None: ... @overload - def __init__(self, __iterable: Iterable[_T], __start: int | None, __stop: int | None, __step: int | None = ...) -> None: ... + def __init__(self, iterable: Iterable[_T], start: int | None, stop: int | None, step: int | None = ..., /) -> None: ... def __iter__(self) -> Self: ... def __next__(self) -> _T: ... class starmap(Iterator[_T_co]): - def __new__(cls, __function: Callable[..., _T], __iterable: Iterable[Iterable[Any]]) -> starmap[_T]: ... + def __new__(cls, function: Callable[..., _T], iterable: Iterable[Iterable[Any]], /) -> starmap[_T]: ... def __iter__(self) -> Self: ... def __next__(self) -> _T_co: ... class takewhile(Iterator[_T]): - def __init__(self, __predicate: _Predicate[_T], __iterable: Iterable[_T]) -> None: ... + def __init__(self, predicate: _Predicate[_T], iterable: Iterable[_T], /) -> None: ... def __iter__(self) -> Self: ... def __next__(self) -> _T: ... -def tee(__iterable: Iterable[_T], __n: int = 2) -> tuple[Iterator[_T], ...]: ... +def tee(iterable: Iterable[_T], n: int = 2, /) -> tuple[Iterator[_T], ...]: ... class zip_longest(Iterator[_T_co]): # one iterable (fillvalue doesn't matter) @overload - def __new__(cls, __iter1: Iterable[_T1], *, fillvalue: object = ...) -> zip_longest[tuple[_T1]]: ... + def __new__(cls, iter1: Iterable[_T1], /, *, fillvalue: object = ...) -> zip_longest[tuple[_T1]]: ... # two iterables @overload # In the overloads without fillvalue, all of the tuple members could theoretically be None, # but we return Any instead to avoid false positives for code where we know one of the iterables # is longer. - def __new__(cls, __iter1: Iterable[_T1], __iter2: Iterable[_T2]) -> zip_longest[tuple[_T1 | Any, _T2 | Any]]: ... + def __new__(cls, iter1: Iterable[_T1], iter2: Iterable[_T2], /) -> zip_longest[tuple[_T1 | Any, _T2 | Any]]: ... @overload def __new__( - cls, __iter1: Iterable[_T1], __iter2: Iterable[_T2], *, fillvalue: _T + cls, iter1: Iterable[_T1], iter2: Iterable[_T2], /, *, fillvalue: _T ) -> zip_longest[tuple[_T1 | _T, _T2 | _T]]: ... # three iterables @overload def __new__( - cls, __iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3] + cls, iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], / ) -> zip_longest[tuple[_T1 | Any, _T2 | Any, _T3 | Any]]: ... @overload def __new__( - cls, __iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3], *, fillvalue: _T + cls, iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], /, *, fillvalue: _T ) -> zip_longest[tuple[_T1 | _T, _T2 | _T, _T3 | _T]]: ... # four iterables @overload def __new__( - cls, __iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3], __iter4: Iterable[_T4] + cls, iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], iter4: Iterable[_T4], / ) -> zip_longest[tuple[_T1 | Any, _T2 | Any, _T3 | Any, _T4 | Any]]: ... @overload def __new__( - cls, __iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3], __iter4: Iterable[_T4], *, fillvalue: _T + cls, iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], iter4: Iterable[_T4], /, *, fillvalue: _T ) -> zip_longest[tuple[_T1 | _T, _T2 | _T, _T3 | _T, _T4 | _T]]: ... # five iterables @overload def __new__( - cls, - __iter1: Iterable[_T1], - __iter2: Iterable[_T2], - __iter3: Iterable[_T3], - __iter4: Iterable[_T4], - __iter5: Iterable[_T5], + cls, iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], iter4: Iterable[_T4], iter5: Iterable[_T5], / ) -> zip_longest[tuple[_T1 | Any, _T2 | Any, _T3 | Any, _T4 | Any, _T5 | Any]]: ... @overload def __new__( cls, - __iter1: Iterable[_T1], - __iter2: Iterable[_T2], - __iter3: Iterable[_T3], - __iter4: Iterable[_T4], - __iter5: Iterable[_T5], + iter1: Iterable[_T1], + iter2: Iterable[_T2], + iter3: Iterable[_T3], + iter4: Iterable[_T4], + iter5: Iterable[_T5], + /, *, fillvalue: _T, ) -> zip_longest[tuple[_T1 | _T, _T2 | _T, _T3 | _T, _T4 | _T, _T5 | _T]]: ... @@ -166,23 +162,25 @@ class zip_longest(Iterator[_T_co]): @overload def __new__( cls, - __iter1: Iterable[_T], - __iter2: Iterable[_T], - __iter3: Iterable[_T], - __iter4: Iterable[_T], - __iter5: Iterable[_T], - __iter6: Iterable[_T], + iter1: Iterable[_T], + iter2: Iterable[_T], + iter3: Iterable[_T], + iter4: Iterable[_T], + iter5: Iterable[_T], + iter6: Iterable[_T], + /, *iterables: Iterable[_T], ) -> zip_longest[tuple[_T | Any, ...]]: ... @overload def __new__( cls, - __iter1: Iterable[_T], - __iter2: Iterable[_T], - __iter3: Iterable[_T], - __iter4: Iterable[_T], - __iter5: Iterable[_T], - __iter6: Iterable[_T], + iter1: Iterable[_T], + iter2: Iterable[_T], + iter3: Iterable[_T], + iter4: Iterable[_T], + iter5: Iterable[_T], + iter6: Iterable[_T], + /, *iterables: Iterable[_T], fillvalue: _T, ) -> zip_longest[tuple[_T, ...]]: ... @@ -191,33 +189,29 @@ class zip_longest(Iterator[_T_co]): class product(Iterator[_T_co]): @overload - def __new__(cls, __iter1: Iterable[_T1]) -> product[tuple[_T1]]: ... + def __new__(cls, iter1: Iterable[_T1], /) -> product[tuple[_T1]]: ... @overload - def __new__(cls, __iter1: Iterable[_T1], __iter2: Iterable[_T2]) -> product[tuple[_T1, _T2]]: ... + def __new__(cls, iter1: Iterable[_T1], iter2: Iterable[_T2], /) -> product[tuple[_T1, _T2]]: ... @overload - def __new__(cls, __iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3]) -> product[tuple[_T1, _T2, _T3]]: ... + def __new__(cls, iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], /) -> product[tuple[_T1, _T2, _T3]]: ... @overload def __new__( - cls, __iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3], __iter4: Iterable[_T4] + cls, iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], iter4: Iterable[_T4], / ) -> product[tuple[_T1, _T2, _T3, _T4]]: ... @overload def __new__( - cls, - __iter1: Iterable[_T1], - __iter2: Iterable[_T2], - __iter3: Iterable[_T3], - __iter4: Iterable[_T4], - __iter5: Iterable[_T5], + cls, iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], iter4: Iterable[_T4], iter5: Iterable[_T5], / ) -> product[tuple[_T1, _T2, _T3, _T4, _T5]]: ... @overload def __new__( cls, - __iter1: Iterable[_T1], - __iter2: Iterable[_T2], - __iter3: Iterable[_T3], - __iter4: Iterable[_T4], - __iter5: Iterable[_T5], - __iter6: Iterable[_T6], + iter1: Iterable[_T1], + iter2: Iterable[_T2], + iter3: Iterable[_T3], + iter4: Iterable[_T4], + iter5: Iterable[_T5], + iter6: Iterable[_T6], + /, ) -> product[tuple[_T1, _T2, _T3, _T4, _T5, _T6]]: ... @overload def __new__(cls, *iterables: Iterable[_T1], repeat: int = 1) -> product[tuple[_T1, ...]]: ... @@ -268,7 +262,7 @@ class combinations_with_replacement(Iterator[_T_co]): if sys.version_info >= (3, 10): class pairwise(Iterator[_T_co]): - def __new__(cls, __iterable: Iterable[_T]) -> pairwise[tuple[_T, _T]]: ... + def __new__(cls, iterable: Iterable[_T], /) -> pairwise[tuple[_T, _T]]: ... def __iter__(self) -> Self: ... def __next__(self) -> _T_co: ... diff --git a/mypy/typeshed/stdlib/json/encoder.pyi b/mypy/typeshed/stdlib/json/encoder.pyi index 0c0d366eb7a2..c1062688bd93 100644 --- a/mypy/typeshed/stdlib/json/encoder.pyi +++ b/mypy/typeshed/stdlib/json/encoder.pyi @@ -10,6 +10,8 @@ INFINITY: float def py_encode_basestring(s: str) -> str: ... # undocumented def py_encode_basestring_ascii(s: str) -> str: ... # undocumented +def encode_basestring(s: str) -> str: ... # undocumented +def encode_basestring_ascii(s: str) -> str: ... # undocumented class JSONEncoder: item_separator: str diff --git a/mypy/typeshed/stdlib/lib2to3/fixer_base.pyi b/mypy/typeshed/stdlib/lib2to3/fixer_base.pyi index 5468ab1db5c3..06813c94308a 100644 --- a/mypy/typeshed/stdlib/lib2to3/fixer_base.pyi +++ b/mypy/typeshed/stdlib/lib2to3/fixer_base.pyi @@ -38,5 +38,5 @@ class BaseFix: class ConditionalFix(BaseFix, metaclass=ABCMeta): skip_on: ClassVar[str | None] - def start_tree(self, __tree: Node, __filename: StrPath) -> None: ... + def start_tree(self, tree: Node, filename: StrPath, /) -> None: ... def should_skip(self, node: Base) -> bool: ... diff --git a/mypy/typeshed/stdlib/logging/__init__.pyi b/mypy/typeshed/stdlib/logging/__init__.pyi index eae2bcd3e96c..a62d0674df4c 100644 --- a/mypy/typeshed/stdlib/logging/__init__.pyi +++ b/mypy/typeshed/stdlib/logging/__init__.pyi @@ -71,12 +71,12 @@ _FormatStyle: TypeAlias = Literal["%", "{", "$"] if sys.version_info >= (3, 12): class _SupportsFilter(Protocol): - def filter(self, __record: LogRecord) -> bool | LogRecord: ... + def filter(self, record: LogRecord, /) -> bool | LogRecord: ... _FilterType: TypeAlias = Filter | Callable[[LogRecord], bool | LogRecord] | _SupportsFilter else: class _SupportsFilter(Protocol): - def filter(self, __record: LogRecord) -> bool: ... + def filter(self, record: LogRecord, /) -> bool: ... _FilterType: TypeAlias = Filter | Callable[[LogRecord], bool] | _SupportsFilter @@ -341,6 +341,9 @@ class LogRecord: stack_info: str | None thread: int | None threadName: str | None + if sys.version_info >= (3, 12): + taskName: str | None + def __init__( self, name: str, @@ -355,7 +358,7 @@ class LogRecord: ) -> None: ... def getMessage(self) -> str: ... # Allows setting contextual information on LogRecord objects as per the docs, see #7833 - def __setattr__(self, __name: str, __value: Any) -> None: ... + def __setattr__(self, name: str, value: Any, /) -> None: ... _L = TypeVar("_L", bound=Logger | LoggerAdapter[Any]) diff --git a/mypy/typeshed/stdlib/logging/handlers.pyi b/mypy/typeshed/stdlib/logging/handlers.pyi index 2280dbad4c5d..4c3dc913308c 100644 --- a/mypy/typeshed/stdlib/logging/handlers.pyi +++ b/mypy/typeshed/stdlib/logging/handlers.pyi @@ -253,7 +253,7 @@ class HTTPHandler(Handler): class _QueueLike(Protocol[_T]): def get(self) -> _T: ... - def put_nowait(self, __item: _T) -> None: ... + def put_nowait(self, item: _T, /) -> None: ... class QueueHandler(Handler): queue: _QueueLike[Any] diff --git a/mypy/typeshed/stdlib/lzma.pyi b/mypy/typeshed/stdlib/lzma.pyi index 05248ee0e710..c05e46a02aeb 100644 --- a/mypy/typeshed/stdlib/lzma.pyi +++ b/mypy/typeshed/stdlib/lzma.pyi @@ -99,7 +99,7 @@ class LZMACompressor: def __init__( self, format: int | None = ..., check: int = ..., preset: int | None = ..., filters: _FilterChain | None = ... ) -> None: ... - def compress(self, __data: ReadableBuffer) -> bytes: ... + def compress(self, data: ReadableBuffer, /) -> bytes: ... def flush(self) -> bytes: ... class LZMAError(Exception): ... @@ -194,4 +194,4 @@ def compress( def decompress( data: ReadableBuffer, format: int = 0, memlimit: int | None = None, filters: _FilterChain | None = None ) -> bytes: ... -def is_check_supported(__check_id: int) -> bool: ... +def is_check_supported(check_id: int, /) -> bool: ... diff --git a/mypy/typeshed/stdlib/marshal.pyi b/mypy/typeshed/stdlib/marshal.pyi index 21f05c908479..69546344f5bf 100644 --- a/mypy/typeshed/stdlib/marshal.pyi +++ b/mypy/typeshed/stdlib/marshal.pyi @@ -27,7 +27,7 @@ _Marshallable: TypeAlias = ( | ReadableBuffer ) -def dump(__value: _Marshallable, __file: SupportsWrite[bytes], __version: int = 4) -> None: ... -def load(__file: SupportsRead[bytes]) -> Any: ... -def dumps(__value: _Marshallable, __version: int = 4) -> bytes: ... -def loads(__bytes: ReadableBuffer) -> Any: ... +def dump(value: _Marshallable, file: SupportsWrite[bytes], version: int = 4, /) -> None: ... +def load(file: SupportsRead[bytes], /) -> Any: ... +def dumps(value: _Marshallable, version: int = 4, /) -> bytes: ... +def loads(bytes: ReadableBuffer, /) -> Any: ... diff --git a/mypy/typeshed/stdlib/math.pyi b/mypy/typeshed/stdlib/math.pyi index ee0693912a8b..0c2fd4aba719 100644 --- a/mypy/typeshed/stdlib/math.pyi +++ b/mypy/typeshed/stdlib/math.pyi @@ -14,58 +14,58 @@ inf: float nan: float tau: float -def acos(__x: _SupportsFloatOrIndex) -> float: ... -def acosh(__x: _SupportsFloatOrIndex) -> float: ... -def asin(__x: _SupportsFloatOrIndex) -> float: ... -def asinh(__x: _SupportsFloatOrIndex) -> float: ... -def atan(__x: _SupportsFloatOrIndex) -> float: ... -def atan2(__y: _SupportsFloatOrIndex, __x: _SupportsFloatOrIndex) -> float: ... -def atanh(__x: _SupportsFloatOrIndex) -> float: ... +def acos(x: _SupportsFloatOrIndex, /) -> float: ... +def acosh(x: _SupportsFloatOrIndex, /) -> float: ... +def asin(x: _SupportsFloatOrIndex, /) -> float: ... +def asinh(x: _SupportsFloatOrIndex, /) -> float: ... +def atan(x: _SupportsFloatOrIndex, /) -> float: ... +def atan2(y: _SupportsFloatOrIndex, x: _SupportsFloatOrIndex, /) -> float: ... +def atanh(x: _SupportsFloatOrIndex, /) -> float: ... if sys.version_info >= (3, 11): - def cbrt(__x: _SupportsFloatOrIndex) -> float: ... + def cbrt(x: _SupportsFloatOrIndex, /) -> float: ... class _SupportsCeil(Protocol[_T_co]): def __ceil__(self) -> _T_co: ... @overload -def ceil(__x: _SupportsCeil[_T]) -> _T: ... +def ceil(x: _SupportsCeil[_T], /) -> _T: ... @overload -def ceil(__x: _SupportsFloatOrIndex) -> int: ... -def comb(__n: SupportsIndex, __k: SupportsIndex) -> int: ... -def copysign(__x: _SupportsFloatOrIndex, __y: _SupportsFloatOrIndex) -> float: ... -def cos(__x: _SupportsFloatOrIndex) -> float: ... -def cosh(__x: _SupportsFloatOrIndex) -> float: ... -def degrees(__x: _SupportsFloatOrIndex) -> float: ... -def dist(__p: Iterable[_SupportsFloatOrIndex], __q: Iterable[_SupportsFloatOrIndex]) -> float: ... -def erf(__x: _SupportsFloatOrIndex) -> float: ... -def erfc(__x: _SupportsFloatOrIndex) -> float: ... -def exp(__x: _SupportsFloatOrIndex) -> float: ... +def ceil(x: _SupportsFloatOrIndex, /) -> int: ... +def comb(n: SupportsIndex, k: SupportsIndex, /) -> int: ... +def copysign(x: _SupportsFloatOrIndex, y: _SupportsFloatOrIndex, /) -> float: ... +def cos(x: _SupportsFloatOrIndex, /) -> float: ... +def cosh(x: _SupportsFloatOrIndex, /) -> float: ... +def degrees(x: _SupportsFloatOrIndex, /) -> float: ... +def dist(p: Iterable[_SupportsFloatOrIndex], q: Iterable[_SupportsFloatOrIndex], /) -> float: ... +def erf(x: _SupportsFloatOrIndex, /) -> float: ... +def erfc(x: _SupportsFloatOrIndex, /) -> float: ... +def exp(x: _SupportsFloatOrIndex, /) -> float: ... if sys.version_info >= (3, 11): - def exp2(__x: _SupportsFloatOrIndex) -> float: ... + def exp2(x: _SupportsFloatOrIndex, /) -> float: ... -def expm1(__x: _SupportsFloatOrIndex) -> float: ... -def fabs(__x: _SupportsFloatOrIndex) -> float: ... -def factorial(__x: SupportsIndex) -> int: ... +def expm1(x: _SupportsFloatOrIndex, /) -> float: ... +def fabs(x: _SupportsFloatOrIndex, /) -> float: ... +def factorial(x: SupportsIndex, /) -> int: ... class _SupportsFloor(Protocol[_T_co]): def __floor__(self) -> _T_co: ... @overload -def floor(__x: _SupportsFloor[_T]) -> _T: ... +def floor(x: _SupportsFloor[_T], /) -> _T: ... @overload -def floor(__x: _SupportsFloatOrIndex) -> int: ... -def fmod(__x: _SupportsFloatOrIndex, __y: _SupportsFloatOrIndex) -> float: ... -def frexp(__x: _SupportsFloatOrIndex) -> tuple[float, int]: ... -def fsum(__seq: Iterable[_SupportsFloatOrIndex]) -> float: ... -def gamma(__x: _SupportsFloatOrIndex) -> float: ... +def floor(x: _SupportsFloatOrIndex, /) -> int: ... +def fmod(x: _SupportsFloatOrIndex, y: _SupportsFloatOrIndex, /) -> float: ... +def frexp(x: _SupportsFloatOrIndex, /) -> tuple[float, int]: ... +def fsum(seq: Iterable[_SupportsFloatOrIndex], /) -> float: ... +def gamma(x: _SupportsFloatOrIndex, /) -> float: ... if sys.version_info >= (3, 9): def gcd(*integers: SupportsIndex) -> int: ... else: - def gcd(__x: SupportsIndex, __y: SupportsIndex) -> int: ... + def gcd(x: SupportsIndex, y: SupportsIndex, /) -> int: ... def hypot(*coordinates: _SupportsFloatOrIndex) -> float: ... def isclose( @@ -75,51 +75,51 @@ def isclose( rel_tol: _SupportsFloatOrIndex = 1e-09, abs_tol: _SupportsFloatOrIndex = 0.0, ) -> bool: ... -def isinf(__x: _SupportsFloatOrIndex) -> bool: ... -def isfinite(__x: _SupportsFloatOrIndex) -> bool: ... -def isnan(__x: _SupportsFloatOrIndex) -> bool: ... -def isqrt(__n: SupportsIndex) -> int: ... +def isinf(x: _SupportsFloatOrIndex, /) -> bool: ... +def isfinite(x: _SupportsFloatOrIndex, /) -> bool: ... +def isnan(x: _SupportsFloatOrIndex, /) -> bool: ... +def isqrt(n: SupportsIndex, /) -> int: ... if sys.version_info >= (3, 9): def lcm(*integers: SupportsIndex) -> int: ... -def ldexp(__x: _SupportsFloatOrIndex, __i: int) -> float: ... -def lgamma(__x: _SupportsFloatOrIndex) -> float: ... +def ldexp(x: _SupportsFloatOrIndex, i: int, /) -> float: ... +def lgamma(x: _SupportsFloatOrIndex, /) -> float: ... def log(x: _SupportsFloatOrIndex, base: _SupportsFloatOrIndex = ...) -> float: ... -def log10(__x: _SupportsFloatOrIndex) -> float: ... -def log1p(__x: _SupportsFloatOrIndex) -> float: ... -def log2(__x: _SupportsFloatOrIndex) -> float: ... -def modf(__x: _SupportsFloatOrIndex) -> tuple[float, float]: ... +def log10(x: _SupportsFloatOrIndex, /) -> float: ... +def log1p(x: _SupportsFloatOrIndex, /) -> float: ... +def log2(x: _SupportsFloatOrIndex, /) -> float: ... +def modf(x: _SupportsFloatOrIndex, /) -> tuple[float, float]: ... if sys.version_info >= (3, 12): - def nextafter(__x: _SupportsFloatOrIndex, __y: _SupportsFloatOrIndex, *, steps: SupportsIndex | None = None) -> float: ... + def nextafter(x: _SupportsFloatOrIndex, y: _SupportsFloatOrIndex, /, *, steps: SupportsIndex | None = None) -> float: ... elif sys.version_info >= (3, 9): - def nextafter(__x: _SupportsFloatOrIndex, __y: _SupportsFloatOrIndex) -> float: ... + def nextafter(x: _SupportsFloatOrIndex, y: _SupportsFloatOrIndex, /) -> float: ... -def perm(__n: SupportsIndex, __k: SupportsIndex | None = None) -> int: ... -def pow(__x: _SupportsFloatOrIndex, __y: _SupportsFloatOrIndex) -> float: ... +def perm(n: SupportsIndex, k: SupportsIndex | None = None, /) -> int: ... +def pow(x: _SupportsFloatOrIndex, y: _SupportsFloatOrIndex, /) -> float: ... @overload -def prod(__iterable: Iterable[SupportsIndex], *, start: SupportsIndex = 1) -> int: ... # type: ignore[overload-overlap] +def prod(iterable: Iterable[SupportsIndex], /, *, start: SupportsIndex = 1) -> int: ... # type: ignore[overload-overlap] @overload -def prod(__iterable: Iterable[_SupportsFloatOrIndex], *, start: _SupportsFloatOrIndex = 1) -> float: ... -def radians(__x: _SupportsFloatOrIndex) -> float: ... -def remainder(__x: _SupportsFloatOrIndex, __y: _SupportsFloatOrIndex) -> float: ... -def sin(__x: _SupportsFloatOrIndex) -> float: ... -def sinh(__x: _SupportsFloatOrIndex) -> float: ... +def prod(iterable: Iterable[_SupportsFloatOrIndex], /, *, start: _SupportsFloatOrIndex = 1) -> float: ... +def radians(x: _SupportsFloatOrIndex, /) -> float: ... +def remainder(x: _SupportsFloatOrIndex, y: _SupportsFloatOrIndex, /) -> float: ... +def sin(x: _SupportsFloatOrIndex, /) -> float: ... +def sinh(x: _SupportsFloatOrIndex, /) -> float: ... if sys.version_info >= (3, 12): - def sumprod(__p: Iterable[float], __q: Iterable[float]) -> float: ... + def sumprod(p: Iterable[float], q: Iterable[float], /) -> float: ... -def sqrt(__x: _SupportsFloatOrIndex) -> float: ... -def tan(__x: _SupportsFloatOrIndex) -> float: ... -def tanh(__x: _SupportsFloatOrIndex) -> float: ... +def sqrt(x: _SupportsFloatOrIndex, /) -> float: ... +def tan(x: _SupportsFloatOrIndex, /) -> float: ... +def tanh(x: _SupportsFloatOrIndex, /) -> float: ... # Is different from `_typeshed.SupportsTrunc`, which is not generic class _SupportsTrunc(Protocol[_T_co]): def __trunc__(self) -> _T_co: ... -def trunc(__x: _SupportsTrunc[_T]) -> _T: ... +def trunc(x: _SupportsTrunc[_T], /) -> _T: ... if sys.version_info >= (3, 9): - def ulp(__x: _SupportsFloatOrIndex) -> float: ... + def ulp(x: _SupportsFloatOrIndex, /) -> float: ... diff --git a/mypy/typeshed/stdlib/mmap.pyi b/mypy/typeshed/stdlib/mmap.pyi index 6bbb797f054d..93c4f408e5b6 100644 --- a/mypy/typeshed/stdlib/mmap.pyi +++ b/mypy/typeshed/stdlib/mmap.pyi @@ -58,24 +58,24 @@ class mmap(Iterable[int], Sized): def read(self, n: int | None = ...) -> bytes: ... def write(self, bytes: ReadableBuffer) -> int: ... @overload - def __getitem__(self, __key: int) -> int: ... + def __getitem__(self, key: int, /) -> int: ... @overload - def __getitem__(self, __key: slice) -> bytes: ... - def __delitem__(self, __key: int | slice) -> NoReturn: ... + def __getitem__(self, key: slice, /) -> bytes: ... + def __delitem__(self, key: int | slice, /) -> NoReturn: ... @overload - def __setitem__(self, __key: int, __value: int) -> None: ... + def __setitem__(self, key: int, value: int, /) -> None: ... @overload - def __setitem__(self, __key: slice, __value: ReadableBuffer) -> None: ... + def __setitem__(self, key: slice, value: ReadableBuffer, /) -> None: ... # Doesn't actually exist, but the object actually supports "in" because it has __getitem__, # so we claim that there is also a __contains__ to help type checkers. - def __contains__(self, __o: object) -> bool: ... + def __contains__(self, o: object, /) -> bool: ... # Doesn't actually exist, but the object is actually iterable because it has __getitem__ and __len__, # so we claim that there is also an __iter__ to help type checkers. def __iter__(self) -> Iterator[int]: ... def __enter__(self) -> Self: ... def __exit__(self, *args: Unused) -> None: ... - def __buffer__(self, __flags: int) -> memoryview: ... - def __release_buffer__(self, __buffer: memoryview) -> None: ... + def __buffer__(self, flags: int, /) -> memoryview: ... + def __release_buffer__(self, buffer: memoryview, /) -> None: ... if sys.platform != "win32": MADV_NORMAL: int diff --git a/mypy/typeshed/stdlib/msvcrt.pyi b/mypy/typeshed/stdlib/msvcrt.pyi index bfd7ec62a9be..54b3674a3a46 100644 --- a/mypy/typeshed/stdlib/msvcrt.pyi +++ b/mypy/typeshed/stdlib/msvcrt.pyi @@ -13,20 +13,20 @@ if sys.platform == "win32": SEM_NOALIGNMENTFAULTEXCEPT: int SEM_NOGPFAULTERRORBOX: int SEM_NOOPENFILEERRORBOX: int - def locking(__fd: int, __mode: int, __nbytes: int) -> None: ... - def setmode(__fd: int, __mode: int) -> int: ... - def open_osfhandle(__handle: int, __flags: int) -> int: ... - def get_osfhandle(__fd: int) -> int: ... + def locking(fd: int, mode: int, nbytes: int, /) -> None: ... + def setmode(fd: int, mode: int, /) -> int: ... + def open_osfhandle(handle: int, flags: int, /) -> int: ... + def get_osfhandle(fd: int, /) -> int: ... def kbhit() -> bool: ... def getch() -> bytes: ... def getwch() -> str: ... def getche() -> bytes: ... def getwche() -> str: ... - def putch(__char: bytes | bytearray) -> None: ... - def putwch(__unicode_char: str) -> None: ... - def ungetch(__char: bytes | bytearray) -> None: ... - def ungetwch(__unicode_char: str) -> None: ... + def putch(char: bytes | bytearray, /) -> None: ... + def putwch(unicode_char: str, /) -> None: ... + def ungetch(char: bytes | bytearray, /) -> None: ... + def ungetwch(unicode_char: str, /) -> None: ... def heapmin() -> None: ... - def SetErrorMode(__mode: int) -> int: ... + def SetErrorMode(mode: int, /) -> int: ... if sys.version_info >= (3, 10): def GetErrorMode() -> int: ... # undocumented diff --git a/mypy/typeshed/stdlib/multiprocessing/context.pyi b/mypy/typeshed/stdlib/multiprocessing/context.pyi index 1cc8d03ea436..a3edaa463818 100644 --- a/mypy/typeshed/stdlib/multiprocessing/context.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/context.pyi @@ -7,7 +7,7 @@ from multiprocessing import popen_fork, popen_forkserver, popen_spawn_posix, pop from multiprocessing.managers import SyncManager from multiprocessing.pool import Pool as _Pool from multiprocessing.process import BaseProcess -from multiprocessing.sharedctypes import SynchronizedArray, SynchronizedBase +from multiprocessing.sharedctypes import Synchronized, SynchronizedArray from typing import Any, ClassVar, Literal, TypeVar, overload from typing_extensions import TypeAlias @@ -79,15 +79,17 @@ class BaseContext: @overload def RawArray(self, typecode_or_type: str, size_or_initializer: int | Sequence[Any]) -> Any: ... @overload - def Value(self, typecode_or_type: type[_CT], *args: Any, lock: Literal[False]) -> _CT: ... + def Value(self, typecode_or_type: type[_CT], *args: Any, lock: Literal[False]) -> Synchronized[_CT]: ... @overload - def Value(self, typecode_or_type: type[_CT], *args: Any, lock: Literal[True] | _LockLike = True) -> SynchronizedBase[_CT]: ... + def Value(self, typecode_or_type: type[_CT], *args: Any, lock: Literal[True] | _LockLike = True) -> Synchronized[_CT]: ... @overload - def Value(self, typecode_or_type: str, *args: Any, lock: Literal[True] | _LockLike = True) -> SynchronizedBase[Any]: ... + def Value(self, typecode_or_type: str, *args: Any, lock: Literal[True] | _LockLike = True) -> Synchronized[Any]: ... @overload def Value(self, typecode_or_type: str | type[_CData], *args: Any, lock: bool | _LockLike = True) -> Any: ... @overload - def Array(self, typecode_or_type: type[_CT], size_or_initializer: int | Sequence[Any], *, lock: Literal[False]) -> _CT: ... + def Array( + self, typecode_or_type: type[_CT], size_or_initializer: int | Sequence[Any], *, lock: Literal[False] + ) -> SynchronizedArray[_CT]: ... @overload def Array( self, typecode_or_type: type[_CT], size_or_initializer: int | Sequence[Any], *, lock: Literal[True] | _LockLike = True diff --git a/mypy/typeshed/stdlib/multiprocessing/dummy/__init__.pyi b/mypy/typeshed/stdlib/multiprocessing/dummy/__init__.pyi index 804a56e9cbcf..3cbeeb057791 100644 --- a/mypy/typeshed/stdlib/multiprocessing/dummy/__init__.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/dummy/__init__.pyi @@ -57,8 +57,8 @@ Process = DummyProcess class Namespace: def __init__(self, **kwds: Any) -> None: ... - def __getattr__(self, __name: str) -> Any: ... - def __setattr__(self, __name: str, __value: Any) -> None: ... + def __getattr__(self, name: str, /) -> Any: ... + def __setattr__(self, name: str, value: Any, /) -> None: ... class Value: _typecode: Any diff --git a/mypy/typeshed/stdlib/multiprocessing/managers.pyi b/mypy/typeshed/stdlib/multiprocessing/managers.pyi index eb3ac29b1449..02b5c4bc8c67 100644 --- a/mypy/typeshed/stdlib/multiprocessing/managers.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/managers.pyi @@ -22,8 +22,8 @@ _VT = TypeVar("_VT") class Namespace: def __init__(self, **kwds: Any) -> None: ... - def __getattr__(self, __name: str) -> Any: ... - def __setattr__(self, __name: str, __value: Any) -> None: ... + def __getattr__(self, name: str, /) -> Any: ... + def __setattr__(self, name: str, value: Any, /) -> None: ... _Namespace: TypeAlias = Namespace @@ -63,23 +63,23 @@ class ValueProxy(BaseProxy, Generic[_T]): class DictProxy(BaseProxy, MutableMapping[_KT, _VT]): __builtins__: ClassVar[dict[str, Any]] def __len__(self) -> int: ... - def __getitem__(self, __key: _KT) -> _VT: ... - def __setitem__(self, __key: _KT, __value: _VT) -> None: ... - def __delitem__(self, __key: _KT) -> None: ... + def __getitem__(self, key: _KT, /) -> _VT: ... + def __setitem__(self, key: _KT, value: _VT, /) -> None: ... + def __delitem__(self, key: _KT, /) -> None: ... def __iter__(self) -> Iterator[_KT]: ... def copy(self) -> dict[_KT, _VT]: ... @overload # type: ignore[override] - def get(self, __key: _KT) -> _VT | None: ... + def get(self, key: _KT, /) -> _VT | None: ... @overload - def get(self, __key: _KT, __default: _VT) -> _VT: ... + def get(self, key: _KT, default: _VT, /) -> _VT: ... @overload - def get(self, __key: _KT, __default: _T) -> _VT | _T: ... + def get(self, key: _KT, default: _T, /) -> _VT | _T: ... @overload - def pop(self, __key: _KT) -> _VT: ... + def pop(self, key: _KT, /) -> _VT: ... @overload - def pop(self, __key: _KT, __default: _VT) -> _VT: ... + def pop(self, key: _KT, default: _VT, /) -> _VT: ... @overload - def pop(self, __key: _KT, __default: _T) -> _VT | _T: ... + def pop(self, key: _KT, default: _T, /) -> _VT | _T: ... def keys(self) -> list[_KT]: ... # type: ignore[override] def items(self) -> list[tuple[_KT, _VT]]: ... # type: ignore[override] def values(self) -> list[_VT]: ... # type: ignore[override] @@ -87,26 +87,26 @@ class DictProxy(BaseProxy, MutableMapping[_KT, _VT]): class BaseListProxy(BaseProxy, MutableSequence[_T]): __builtins__: ClassVar[dict[str, Any]] def __len__(self) -> int: ... - def __add__(self, __x: list[_T]) -> list[_T]: ... - def __delitem__(self, __i: SupportsIndex | slice) -> None: ... + def __add__(self, x: list[_T], /) -> list[_T]: ... + def __delitem__(self, i: SupportsIndex | slice, /) -> None: ... @overload - def __getitem__(self, __i: SupportsIndex) -> _T: ... + def __getitem__(self, i: SupportsIndex, /) -> _T: ... @overload - def __getitem__(self, __s: slice) -> list[_T]: ... + def __getitem__(self, s: slice, /) -> list[_T]: ... @overload - def __setitem__(self, __i: SupportsIndex, __o: _T) -> None: ... + def __setitem__(self, i: SupportsIndex, o: _T, /) -> None: ... @overload - def __setitem__(self, __s: slice, __o: Iterable[_T]) -> None: ... - def __mul__(self, __n: SupportsIndex) -> list[_T]: ... - def __rmul__(self, __n: SupportsIndex) -> list[_T]: ... + def __setitem__(self, s: slice, o: Iterable[_T], /) -> None: ... + def __mul__(self, n: SupportsIndex, /) -> list[_T]: ... + def __rmul__(self, n: SupportsIndex, /) -> list[_T]: ... def __reversed__(self) -> Iterator[_T]: ... - def append(self, __object: _T) -> None: ... - def extend(self, __iterable: Iterable[_T]) -> None: ... - def pop(self, __index: SupportsIndex = ...) -> _T: ... - def index(self, __value: _T, __start: SupportsIndex = ..., __stop: SupportsIndex = ...) -> int: ... - def count(self, __value: _T) -> int: ... - def insert(self, __index: SupportsIndex, __object: _T) -> None: ... - def remove(self, __value: _T) -> None: ... + def append(self, object: _T, /) -> None: ... + def extend(self, iterable: Iterable[_T], /) -> None: ... + def pop(self, index: SupportsIndex = ..., /) -> _T: ... + def index(self, value: _T, start: SupportsIndex = ..., stop: SupportsIndex = ..., /) -> int: ... + def count(self, value: _T, /) -> int: ... + def insert(self, index: SupportsIndex, object: _T, /) -> None: ... + def remove(self, value: _T, /) -> None: ... # Use BaseListProxy[SupportsRichComparisonT] for the first overload rather than [SupportsRichComparison] # to work around invariance @overload @@ -115,8 +115,8 @@ class BaseListProxy(BaseProxy, MutableSequence[_T]): def sort(self, *, key: Callable[[_T], SupportsRichComparison], reverse: bool = ...) -> None: ... class ListProxy(BaseListProxy[_T]): - def __iadd__(self, __value: Iterable[_T]) -> Self: ... # type: ignore[override] - def __imul__(self, __value: SupportsIndex) -> Self: ... # type: ignore[override] + def __iadd__(self, value: Iterable[_T], /) -> Self: ... # type: ignore[override] + def __imul__(self, value: SupportsIndex, /) -> Self: ... # type: ignore[override] # Returned by BaseManager.get_server() class Server: @@ -186,19 +186,19 @@ class SyncManager(BaseManager): @overload def dict(self, **kwargs: _VT) -> DictProxy[str, _VT]: ... @overload - def dict(self, __map: SupportsKeysAndGetItem[_KT, _VT]) -> DictProxy[_KT, _VT]: ... + def dict(self, map: SupportsKeysAndGetItem[_KT, _VT], /) -> DictProxy[_KT, _VT]: ... @overload - def dict(self, __map: SupportsKeysAndGetItem[str, _VT], **kwargs: _VT) -> DictProxy[str, _VT]: ... + def dict(self, map: SupportsKeysAndGetItem[str, _VT], /, **kwargs: _VT) -> DictProxy[str, _VT]: ... @overload - def dict(self, __iterable: Iterable[tuple[_KT, _VT]]) -> DictProxy[_KT, _VT]: ... + def dict(self, iterable: Iterable[tuple[_KT, _VT]], /) -> DictProxy[_KT, _VT]: ... @overload - def dict(self, __iterable: Iterable[tuple[str, _VT]], **kwargs: _VT) -> DictProxy[str, _VT]: ... + def dict(self, iterable: Iterable[tuple[str, _VT]], /, **kwargs: _VT) -> DictProxy[str, _VT]: ... @overload - def dict(self, __iterable: Iterable[list[str]]) -> DictProxy[str, str]: ... + def dict(self, iterable: Iterable[list[str]], /) -> DictProxy[str, str]: ... @overload - def dict(self, __iterable: Iterable[list[bytes]]) -> DictProxy[bytes, bytes]: ... + def dict(self, iterable: Iterable[list[bytes]], /) -> DictProxy[bytes, bytes]: ... @overload - def list(self, __sequence: Sequence[_T]) -> ListProxy[_T]: ... + def list(self, sequence: Sequence[_T], /) -> ListProxy[_T]: ... @overload def list(self) -> ListProxy[Any]: ... diff --git a/mypy/typeshed/stdlib/multiprocessing/queues.pyi b/mypy/typeshed/stdlib/multiprocessing/queues.pyi index 8e72d15f25f6..4cedd665552a 100644 --- a/mypy/typeshed/stdlib/multiprocessing/queues.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/queues.pyi @@ -23,7 +23,7 @@ class Queue(Generic[_T]): def join_thread(self) -> None: ... def cancel_join_thread(self) -> None: ... if sys.version_info >= (3, 12): - def __class_getitem__(cls, __item: Any) -> GenericAlias: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... class JoinableQueue(Queue[_T]): def task_done(self) -> None: ... diff --git a/mypy/typeshed/stdlib/multiprocessing/sharedctypes.pyi b/mypy/typeshed/stdlib/multiprocessing/sharedctypes.pyi index 3979f14cf636..4093a97e6ca3 100644 --- a/mypy/typeshed/stdlib/multiprocessing/sharedctypes.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/sharedctypes.pyi @@ -72,7 +72,7 @@ def synchronized(obj: ctypes.Array[_CT], lock: _LockLike | None = None, ctx: Any def synchronized(obj: _CT, lock: _LockLike | None = None, ctx: Any | None = None) -> SynchronizedBase[_CT]: ... class _AcquireFunc(Protocol): - def __call__(self, __block: bool = ..., __timeout: float | None = ...) -> bool: ... + def __call__(self, block: bool = ..., timeout: float | None = ..., /) -> bool: ... class SynchronizedBase(Generic[_CT]): acquire: _AcquireFunc @@ -83,7 +83,7 @@ class SynchronizedBase(Generic[_CT]): def get_lock(self) -> _LockLike: ... def __enter__(self) -> bool: ... def __exit__( - self, __exc_type: type[BaseException] | None, __exc_val: BaseException | None, __exc_tb: TracebackType | None + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None, / ) -> None: ... class Synchronized(SynchronizedBase[_SimpleCData[_T]], Generic[_T]): @@ -91,7 +91,13 @@ class Synchronized(SynchronizedBase[_SimpleCData[_T]], Generic[_T]): class SynchronizedArray(SynchronizedBase[ctypes.Array[_CT]], Generic[_CT]): def __len__(self) -> int: ... + @overload + def __getitem__(self, i: slice) -> list[_CT]: ... + @overload def __getitem__(self, i: int) -> _CT: ... + @overload + def __setitem__(self, i: slice, value: Iterable[_CT]) -> None: ... + @overload def __setitem__(self, i: int, value: _CT) -> None: ... def __getslice__(self, start: int, stop: int) -> list[_CT]: ... def __setslice__(self, start: int, stop: int, values: Iterable[_CT]) -> None: ... diff --git a/mypy/typeshed/stdlib/multiprocessing/synchronize.pyi b/mypy/typeshed/stdlib/multiprocessing/synchronize.pyi index a4e36cfa0b6e..048c6fe8d891 100644 --- a/mypy/typeshed/stdlib/multiprocessing/synchronize.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/synchronize.pyi @@ -23,7 +23,7 @@ class Condition(AbstractContextManager[bool]): def acquire(self, block: bool = ..., timeout: float | None = ...) -> bool: ... def release(self) -> None: ... def __exit__( - self, __exc_type: type[BaseException] | None, __exc_val: BaseException | None, __exc_tb: TracebackType | None + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None, / ) -> None: ... class Event: @@ -38,7 +38,7 @@ class SemLock(AbstractContextManager[bool]): def acquire(self, block: bool = ..., timeout: float | None = ...) -> bool: ... def release(self) -> None: ... def __exit__( - self, __exc_type: type[BaseException] | None, __exc_val: BaseException | None, __exc_tb: TracebackType | None + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None, / ) -> None: ... class Lock(SemLock): diff --git a/mypy/typeshed/stdlib/ntpath.pyi b/mypy/typeshed/stdlib/ntpath.pyi index bfa880ee03a8..079366018bf5 100644 --- a/mypy/typeshed/stdlib/ntpath.pyi +++ b/mypy/typeshed/stdlib/ntpath.pyi @@ -97,11 +97,11 @@ altsep: LiteralString # but must be defined as pos-only in the stub or cross-platform code doesn't type-check, # as the parameter name is different in posixpath.join() @overload -def join(__path: LiteralString, *paths: LiteralString) -> LiteralString: ... +def join(path: LiteralString, /, *paths: LiteralString) -> LiteralString: ... @overload -def join(__path: StrPath, *paths: StrPath) -> str: ... +def join(path: StrPath, /, *paths: StrPath) -> str: ... @overload -def join(__path: BytesPath, *paths: BytesPath) -> bytes: ... +def join(path: BytesPath, /, *paths: BytesPath) -> bytes: ... if sys.platform == "win32": if sys.version_info >= (3, 10): diff --git a/mypy/typeshed/stdlib/opcode.pyi b/mypy/typeshed/stdlib/opcode.pyi index 02da0c9f954a..14bdb7622142 100644 --- a/mypy/typeshed/stdlib/opcode.pyi +++ b/mypy/typeshed/stdlib/opcode.pyi @@ -56,4 +56,4 @@ opmap: dict[str, int] HAVE_ARGUMENT: Literal[90] EXTENDED_ARG: Literal[144] -def stack_effect(__opcode: int, __oparg: int | None = None, *, jump: bool | None = None) -> int: ... +def stack_effect(opcode: int, oparg: int | None = None, /, *, jump: bool | None = None) -> int: ... diff --git a/mypy/typeshed/stdlib/optparse.pyi b/mypy/typeshed/stdlib/optparse.pyi index a8c1c4cfb93e..3474648617c2 100644 --- a/mypy/typeshed/stdlib/optparse.pyi +++ b/mypy/typeshed/stdlib/optparse.pyi @@ -1,6 +1,7 @@ +from _typeshed import Incomplete from abc import abstractmethod from collections.abc import Callable, Iterable, Mapping, Sequence -from typing import IO, Any, AnyStr, overload +from typing import IO, Any, AnyStr, Literal, overload __all__ = [ "Option", @@ -26,8 +27,8 @@ NO_DEFAULT: tuple[str, ...] SUPPRESS_HELP: str SUPPRESS_USAGE: str -def check_builtin(option: Option, opt: Any, value: str) -> Any: ... -def check_choice(option: Option, opt: Any, value: str) -> str: ... +def check_builtin(option: Option, opt, value: str): ... +def check_choice(option: Option, opt, value: str) -> str: ... class OptParseError(Exception): msg: str @@ -54,26 +55,26 @@ class HelpFormatter: _short_opt_fmt: str current_indent: int default_tag: str - help_position: Any - help_width: Any + help_position: int + help_width: int | Any # initialized as None and computed later as int when storing option strings indent_increment: int level: int max_help_position: int option_strings: dict[Option, str] parser: OptionParser - short_first: Any + short_first: Incomplete width: int def __init__(self, indent_increment: int, max_help_position: int, width: int | None, short_first: int) -> None: ... def dedent(self) -> None: ... def expand_default(self, option: Option) -> str: ... - def format_description(self, description: str) -> str: ... - def format_epilog(self, epilog: str) -> str: ... + def format_description(self, description: str | None) -> str: ... + def format_epilog(self, epilog: str | None) -> str: ... @abstractmethod - def format_heading(self, heading: Any) -> str: ... + def format_heading(self, heading: str) -> str: ... def format_option(self, option: Option) -> str: ... def format_option_strings(self, option: Option) -> str: ... @abstractmethod - def format_usage(self, usage: Any) -> str: ... + def format_usage(self, usage: str) -> str: ... def indent(self) -> None: ... def set_long_opt_delimiter(self, delim: str) -> None: ... def set_parser(self, parser: OptionParser) -> None: ... @@ -98,25 +99,25 @@ class Option: ACTIONS: tuple[str, ...] ALWAYS_TYPED_ACTIONS: tuple[str, ...] ATTRS: list[str] - CHECK_METHODS: list[Callable[..., Any]] | None + CHECK_METHODS: list[Callable[..., Incomplete]] | None CONST_ACTIONS: tuple[str, ...] STORE_ACTIONS: tuple[str, ...] TYPED_ACTIONS: tuple[str, ...] TYPES: tuple[str, ...] - TYPE_CHECKER: dict[str, Callable[..., Any]] + TYPE_CHECKER: dict[str, Callable[[Option, str, Incomplete], Any]] _long_opts: list[str] _short_opts: list[str] action: str dest: str | None - default: Any + default: Incomplete nargs: int - type: Any - callback: Callable[..., Any] | None - callback_args: tuple[Any, ...] | None - callback_kwargs: dict[str, Any] | None + type: Incomplete + callback: Callable[..., Incomplete] | None + callback_args: tuple[Incomplete, ...] | None + callback_kwargs: dict[str, Incomplete] | None help: str | None metavar: str | None - def __init__(self, *opts: str | None, **attrs: Any) -> None: ... + def __init__(self, *opts: str | None, **attrs) -> None: ... def _check_action(self) -> None: ... def _check_callback(self) -> None: ... def _check_choice(self) -> None: ... @@ -125,13 +126,13 @@ class Option: def _check_nargs(self) -> None: ... def _check_opt_strings(self, opts: Iterable[str | None]) -> list[str]: ... def _check_type(self) -> None: ... - def _set_attrs(self, attrs: dict[str, Any]) -> None: ... + def _set_attrs(self, attrs: dict[str, Incomplete]) -> None: ... def _set_opt_strings(self, opts: Iterable[str]) -> None: ... - def check_value(self, opt: str, value: Any) -> Any: ... - def convert_value(self, opt: str, value: Any) -> Any: ... + def check_value(self, opt: str, value): ... + def convert_value(self, opt: str, value): ... def get_opt_string(self) -> str: ... - def process(self, opt: Any, value: Any, values: Any, parser: OptionParser) -> int: ... - def take_action(self, action: str, dest: str, opt: Any, value: Any, values: Any, parser: OptionParser) -> int: ... + def process(self, opt, value, values, parser: OptionParser) -> int: ... + def take_action(self, action: str, dest: str, opt, value, values, parser: OptionParser) -> int: ... def takes_value(self) -> bool: ... make_option = Option @@ -140,28 +141,30 @@ class OptionContainer: _long_opt: dict[str, Option] _short_opt: dict[str, Option] conflict_handler: str - defaults: dict[str, Any] - description: Any + defaults: dict[str, Incomplete] + description: str | None option_class: type[Option] - def __init__(self, option_class: type[Option], conflict_handler: Any, description: Any) -> None: ... - def _check_conflict(self, option: Any) -> None: ... + def __init__( + self, option_class: type[Option], conflict_handler: Literal["error", "resolve"], description: str | None + ) -> None: ... + def _check_conflict(self, option: Option) -> None: ... def _create_option_mappings(self) -> None: ... def _share_option_mappings(self, parser: OptionParser) -> None: ... @overload def add_option(self, opt: Option) -> Option: ... @overload - def add_option(self, *args: str | None, **kwargs: Any) -> Any: ... + def add_option(self, arg: str, /, *args: str | None, **kwargs) -> Option: ... def add_options(self, option_list: Iterable[Option]) -> None: ... def destroy(self) -> None: ... - def format_description(self, formatter: HelpFormatter | None) -> Any: ... - def format_help(self, formatter: HelpFormatter | None) -> str: ... - def format_option_help(self, formatter: HelpFormatter | None) -> str: ... - def get_description(self) -> Any: ... + def format_option_help(self, formatter: HelpFormatter) -> str: ... + def format_description(self, formatter: HelpFormatter) -> str: ... + def format_help(self, formatter: HelpFormatter) -> str: ... + def get_description(self) -> str | None: ... def get_option(self, opt_str: str) -> Option | None: ... def has_option(self, opt_str: str) -> bool: ... def remove_option(self, opt_str: str) -> None: ... - def set_conflict_handler(self, handler: Any) -> None: ... - def set_description(self, description: Any) -> None: ... + def set_conflict_handler(self, handler: Literal["error", "resolve"]) -> None: ... + def set_description(self, description: str | None) -> None: ... class OptionGroup(OptionContainer): option_list: list[Option] @@ -172,15 +175,15 @@ class OptionGroup(OptionContainer): def set_title(self, title: str) -> None: ... class Values: - def __init__(self, defaults: Mapping[str, Any] | None = None) -> None: ... - def _update(self, dict: Mapping[str, Any], mode: Any) -> None: ... - def _update_careful(self, dict: Mapping[str, Any]) -> None: ... - def _update_loose(self, dict: Mapping[str, Any]) -> None: ... - def ensure_value(self, attr: str, value: Any) -> Any: ... + def __init__(self, defaults: Mapping[str, Incomplete] | None = None) -> None: ... + def _update(self, dict: Mapping[str, Incomplete], mode) -> None: ... + def _update_careful(self, dict: Mapping[str, Incomplete]) -> None: ... + def _update_loose(self, dict: Mapping[str, Incomplete]) -> None: ... + def ensure_value(self, attr: str, value): ... def read_file(self, filename: str, mode: str = "careful") -> None: ... def read_module(self, modname: str, mode: str = "careful") -> None: ... - def __getattr__(self, name: str) -> Any: ... - def __setattr__(self, __name: str, __value: Any) -> None: ... + def __getattr__(self, name: str): ... + def __setattr__(self, name: str, value, /) -> None: ... def __eq__(self, other: object) -> bool: ... class OptionParser(OptionContainer): @@ -190,9 +193,9 @@ class OptionParser(OptionContainer): largs: list[str] | None option_groups: list[OptionGroup] option_list: list[Option] - process_default_values: Any + process_default_values: bool prog: str | None - rargs: list[Any] | None + rargs: list[str] | None standard_option_list: list[Option] usage: str | None values: Values | None @@ -214,28 +217,28 @@ class OptionParser(OptionContainer): def _add_version_option(self) -> None: ... def _create_option_list(self) -> None: ... def _get_all_options(self) -> list[Option]: ... - def _get_args(self, args: Iterable[Any]) -> list[Any]: ... + def _get_args(self, args: Iterable[Incomplete]) -> list[Incomplete]: ... def _init_parsing_state(self) -> None: ... def _match_long_opt(self, opt: str) -> str: ... def _populate_option_list(self, option_list: Iterable[Option], add_help: bool = True) -> None: ... - def _process_args(self, largs: list[Any], rargs: list[Any], values: Values) -> None: ... - def _process_long_opt(self, rargs: list[Any], values: Any) -> None: ... - def _process_short_opts(self, rargs: list[Any], values: Any) -> None: ... + def _process_args(self, largs: list[Incomplete], rargs: list[Incomplete], values: Values) -> None: ... + def _process_long_opt(self, rargs: list[Incomplete], values) -> None: ... + def _process_short_opts(self, rargs: list[Incomplete], values) -> None: ... @overload - def add_option_group(self, __opt_group: OptionGroup) -> OptionGroup: ... + def add_option_group(self, opt_group: OptionGroup, /) -> OptionGroup: ... @overload - def add_option_group(self, *args: Any, **kwargs: Any) -> OptionGroup: ... + def add_option_group(self, *args, **kwargs) -> OptionGroup: ... def check_values(self, values: Values, args: list[str]) -> tuple[Values, list[str]]: ... def disable_interspersed_args(self) -> None: ... def enable_interspersed_args(self) -> None: ... def error(self, msg: str) -> None: ... def exit(self, status: int = 0, msg: str | None = None) -> None: ... - def expand_prog_name(self, s: str | None) -> Any: ... - def format_epilog(self, formatter: HelpFormatter) -> Any: ... + def expand_prog_name(self, s: str) -> str: ... + def format_epilog(self, formatter: HelpFormatter) -> str: ... def format_help(self, formatter: HelpFormatter | None = None) -> str: ... def format_option_help(self, formatter: HelpFormatter | None = None) -> str: ... def get_default_values(self) -> Values: ... - def get_option_group(self, opt_str: str) -> Any: ... + def get_option_group(self, opt_str: str) -> OptionGroup | None: ... def get_prog_name(self) -> str: ... def get_usage(self) -> str: ... def get_version(self) -> str: ... @@ -246,7 +249,7 @@ class OptionParser(OptionContainer): def print_usage(self, file: IO[str] | None = None) -> None: ... def print_help(self, file: IO[str] | None = None) -> None: ... def print_version(self, file: IO[str] | None = None) -> None: ... - def set_default(self, dest: Any, value: Any) -> None: ... - def set_defaults(self, **kwargs: Any) -> None: ... - def set_process_default_values(self, process: Any) -> None: ... + def set_default(self, dest, value) -> None: ... + def set_defaults(self, **kwargs) -> None: ... + def set_process_default_values(self, process) -> None: ... def set_usage(self, usage: str) -> None: ... diff --git a/mypy/typeshed/stdlib/os/__init__.pyi b/mypy/typeshed/stdlib/os/__init__.pyi index eef52e7a8b3b..89d906d4edfc 100644 --- a/mypy/typeshed/stdlib/os/__init__.pyi +++ b/mypy/typeshed/stdlib/os/__init__.pyi @@ -493,8 +493,8 @@ def get_exec_path(env: Mapping[str, str] | None = None) -> list[str]: ... def getlogin() -> str: ... def getpid() -> int: ... def getppid() -> int: ... -def strerror(__code: int) -> str: ... -def umask(__mask: int) -> int: ... +def strerror(code: int, /) -> str: ... +def umask(mask: int, /) -> int: ... @final class uname_result(structseq[str], tuple[str, str, str, str, str]): if sys.version_info >= (3, 10): @@ -516,9 +516,9 @@ if sys.platform != "win32": def getegid() -> int: ... def geteuid() -> int: ... def getgid() -> int: ... - def getgrouplist(__user: str, __group: int) -> list[int]: ... + def getgrouplist(user: str, group: int, /) -> list[int]: ... def getgroups() -> list[int]: ... # Unix only, behaves differently on Mac - def initgroups(__username: str, __gid: int) -> None: ... + def initgroups(username: str, gid: int, /) -> None: ... def getpgid(pid: int) -> int: ... def getpgrp() -> int: ... def getpriority(which: int, who: int) -> int: ... @@ -528,21 +528,21 @@ if sys.platform != "win32": def getresgid() -> tuple[int, int, int]: ... def getuid() -> int: ... - def setegid(__egid: int) -> None: ... - def seteuid(__euid: int) -> None: ... - def setgid(__gid: int) -> None: ... - def setgroups(__groups: Sequence[int]) -> None: ... + def setegid(egid: int, /) -> None: ... + def seteuid(euid: int, /) -> None: ... + def setgid(gid: int, /) -> None: ... + def setgroups(groups: Sequence[int], /) -> None: ... def setpgrp() -> None: ... - def setpgid(__pid: int, __pgrp: int) -> None: ... - def setregid(__rgid: int, __egid: int) -> None: ... + def setpgid(pid: int, pgrp: int, /) -> None: ... + def setregid(rgid: int, egid: int, /) -> None: ... if sys.platform != "darwin": - def setresgid(__rgid: int, __egid: int, __sgid: int) -> None: ... - def setresuid(__ruid: int, __euid: int, __suid: int) -> None: ... + def setresgid(rgid: int, egid: int, sgid: int, /) -> None: ... + def setresuid(ruid: int, euid: int, suid: int, /) -> None: ... - def setreuid(__ruid: int, __euid: int) -> None: ... - def getsid(__pid: int) -> int: ... + def setreuid(ruid: int, euid: int, /) -> None: ... + def getsid(pid: int, /) -> int: ... def setsid() -> None: ... - def setuid(__uid: int) -> None: ... + def setuid(uid: int, /) -> None: ... def uname() -> uname_result: ... @overload @@ -555,14 +555,14 @@ if sys.platform != "win32": def getenvb(key: bytes) -> bytes | None: ... @overload def getenvb(key: bytes, default: _T) -> bytes | _T: ... - def putenv(__name: StrOrBytesPath, __value: StrOrBytesPath) -> None: ... - def unsetenv(__name: StrOrBytesPath) -> None: ... + def putenv(name: StrOrBytesPath, value: StrOrBytesPath, /) -> None: ... + def unsetenv(name: StrOrBytesPath, /) -> None: ... else: - def putenv(__name: str, __value: str) -> None: ... + def putenv(name: str, value: str, /) -> None: ... if sys.version_info >= (3, 9): - def unsetenv(__name: str) -> None: ... + def unsetenv(name: str, /) -> None: ... _Opener: TypeAlias = Callable[[str, int], int] @@ -644,50 +644,50 @@ def fdopen( opener: _Opener | None = ..., ) -> IO[Any]: ... def close(fd: int) -> None: ... -def closerange(__fd_low: int, __fd_high: int) -> None: ... +def closerange(fd_low: int, fd_high: int, /) -> None: ... def device_encoding(fd: int) -> str | None: ... -def dup(__fd: int) -> int: ... +def dup(fd: int, /) -> int: ... def dup2(fd: int, fd2: int, inheritable: bool = True) -> int: ... def fstat(fd: int) -> stat_result: ... -def ftruncate(__fd: int, __length: int) -> None: ... +def ftruncate(fd: int, length: int, /) -> None: ... def fsync(fd: FileDescriptorLike) -> None: ... -def isatty(__fd: int) -> bool: ... +def isatty(fd: int, /) -> bool: ... if sys.platform != "win32" and sys.version_info >= (3, 11): - def login_tty(__fd: int) -> None: ... + def login_tty(fd: int, /) -> None: ... if sys.version_info >= (3, 11): - def lseek(__fd: int, __position: int, __whence: int) -> int: ... + def lseek(fd: int, position: int, whence: int, /) -> int: ... else: - def lseek(__fd: int, __position: int, __how: int) -> int: ... + def lseek(fd: int, position: int, how: int, /) -> int: ... def open(path: StrOrBytesPath, flags: int, mode: int = 0o777, *, dir_fd: int | None = None) -> int: ... def pipe() -> tuple[int, int]: ... -def read(__fd: int, __length: int) -> bytes: ... +def read(fd: int, length: int, /) -> bytes: ... if sys.version_info >= (3, 12) or sys.platform != "win32": - def get_blocking(__fd: int) -> bool: ... - def set_blocking(__fd: int, __blocking: bool) -> None: ... + def get_blocking(fd: int, /) -> bool: ... + def set_blocking(fd: int, blocking: bool, /) -> None: ... if sys.platform != "win32": def fchmod(fd: int, mode: int) -> None: ... def fchown(fd: int, uid: int, gid: int) -> None: ... - def fpathconf(__fd: int, __name: str | int) -> int: ... - def fstatvfs(__fd: int) -> statvfs_result: ... - def lockf(__fd: int, __command: int, __length: int) -> None: ... + def fpathconf(fd: int, name: str | int, /) -> int: ... + def fstatvfs(fd: int, /) -> statvfs_result: ... + def lockf(fd: int, command: int, length: int, /) -> None: ... def openpty() -> tuple[int, int]: ... # some flavors of Unix if sys.platform != "darwin": def fdatasync(fd: FileDescriptorLike) -> None: ... - def pipe2(__flags: int) -> tuple[int, int]: ... # some flavors of Unix - def posix_fallocate(__fd: int, __offset: int, __length: int) -> None: ... - def posix_fadvise(__fd: int, __offset: int, __length: int, __advice: int) -> None: ... + def pipe2(flags: int, /) -> tuple[int, int]: ... # some flavors of Unix + def posix_fallocate(fd: int, offset: int, length: int, /) -> None: ... + def posix_fadvise(fd: int, offset: int, length: int, advice: int, /) -> None: ... - def pread(__fd: int, __length: int, __offset: int) -> bytes: ... - def pwrite(__fd: int, __buffer: ReadableBuffer, __offset: int) -> int: ... + def pread(fd: int, length: int, offset: int, /) -> bytes: ... + def pwrite(fd: int, buffer: ReadableBuffer, offset: int, /) -> int: ... # In CI, stubtest sometimes reports that these are available on MacOS, sometimes not - def preadv(__fd: int, __buffers: SupportsLenAndGetItem[WriteableBuffer], __offset: int, __flags: int = 0) -> int: ... - def pwritev(__fd: int, __buffers: SupportsLenAndGetItem[ReadableBuffer], __offset: int, __flags: int = 0) -> int: ... + def preadv(fd: int, buffers: SupportsLenAndGetItem[WriteableBuffer], offset: int, flags: int = 0, /) -> int: ... + def pwritev(fd: int, buffers: SupportsLenAndGetItem[ReadableBuffer], offset: int, flags: int = 0, /) -> int: ... if sys.platform != "darwin": if sys.version_info >= (3, 10): RWF_APPEND: int # docs say available on 3.7+, stubtest says otherwise @@ -709,8 +709,8 @@ if sys.platform != "win32": flags: int = 0, ) -> int: ... # FreeBSD and Mac OS X only - def readv(__fd: int, __buffers: SupportsLenAndGetItem[WriteableBuffer]) -> int: ... - def writev(__fd: int, __buffers: SupportsLenAndGetItem[ReadableBuffer]) -> int: ... + def readv(fd: int, buffers: SupportsLenAndGetItem[WriteableBuffer], /) -> int: ... + def writev(fd: int, buffers: SupportsLenAndGetItem[ReadableBuffer], /) -> int: ... @final class terminal_size(structseq[int], tuple[int, int]): @@ -722,21 +722,21 @@ class terminal_size(structseq[int], tuple[int, int]): @property def lines(self) -> int: ... -def get_terminal_size(__fd: int = ...) -> terminal_size: ... -def get_inheritable(__fd: int) -> bool: ... -def set_inheritable(__fd: int, __inheritable: bool) -> None: ... +def get_terminal_size(fd: int = ..., /) -> terminal_size: ... +def get_inheritable(fd: int, /) -> bool: ... +def set_inheritable(fd: int, inheritable: bool, /) -> None: ... if sys.platform == "win32": - def get_handle_inheritable(__handle: int) -> bool: ... - def set_handle_inheritable(__handle: int, __inheritable: bool) -> None: ... + def get_handle_inheritable(handle: int, /) -> bool: ... + def set_handle_inheritable(handle: int, inheritable: bool, /) -> None: ... if sys.platform != "win32": # Unix only - def tcgetpgrp(__fd: int) -> int: ... - def tcsetpgrp(__fd: int, __pgid: int) -> None: ... - def ttyname(__fd: int) -> str: ... + def tcgetpgrp(fd: int, /) -> int: ... + def tcsetpgrp(fd: int, pgid: int, /) -> None: ... + def ttyname(fd: int, /) -> str: ... -def write(__fd: int, __data: ReadableBuffer) -> int: ... +def write(fd: int, data: ReadableBuffer, /) -> int: ... def access( path: FileDescriptorOrPath, mode: int, *, dir_fd: int | None = None, effective_ids: bool = False, follow_symlinks: bool = True ) -> bool: ... @@ -779,9 +779,9 @@ def makedirs(name: StrOrBytesPath, mode: int = 0o777, exist_ok: bool = False) -> if sys.platform != "win32": def mknod(path: StrOrBytesPath, mode: int = 0o600, device: int = 0, *, dir_fd: int | None = None) -> None: ... - def major(__device: int) -> int: ... - def minor(__device: int) -> int: ... - def makedev(__major: int, __minor: int) -> int: ... + def major(device: int, /) -> int: ... + def minor(device: int, /) -> int: ... + def makedev(major: int, minor: int, /) -> int: ... def pathconf(path: FileDescriptorOrPath, name: str | int) -> int: ... # Unix only def readlink(path: GenericPath[AnyStr], *, dir_fd: int | None = None) -> AnyStr: ... @@ -901,21 +901,21 @@ _ExecVArgs: TypeAlias = ( # we limit to str | bytes. _ExecEnv: TypeAlias = Mapping[bytes, bytes | str] | Mapping[str, bytes | str] -def execv(__path: StrOrBytesPath, __argv: _ExecVArgs) -> NoReturn: ... +def execv(path: StrOrBytesPath, argv: _ExecVArgs, /) -> NoReturn: ... def execve(path: FileDescriptorOrPath, argv: _ExecVArgs, env: _ExecEnv) -> NoReturn: ... def execvp(file: StrOrBytesPath, args: _ExecVArgs) -> NoReturn: ... def execvpe(file: StrOrBytesPath, args: _ExecVArgs, env: _ExecEnv) -> NoReturn: ... def _exit(status: int) -> NoReturn: ... -def kill(__pid: int, __signal: int) -> None: ... +def kill(pid: int, signal: int, /) -> None: ... if sys.platform != "win32": # Unix only def fork() -> int: ... def forkpty() -> tuple[int, int]: ... # some flavors of Unix - def killpg(__pgid: int, __signal: int) -> None: ... - def nice(__increment: int) -> int: ... + def killpg(pgid: int, signal: int, /) -> None: ... + def nice(increment: int, /) -> int: ... if sys.platform != "darwin": - def plock(__op: int) -> None: ... # ???op is int? + def plock(op: int, /) -> None: ... # ???op is int? class _wrap_close(_TextIOWrapper): def __init__(self, stream: _TextIOWrapper, proc: Popen[str]) -> None: ... @@ -930,8 +930,8 @@ if sys.platform != "win32": def spawnve(mode: int, file: StrOrBytesPath, args: _ExecVArgs, env: _ExecEnv) -> int: ... else: - def spawnv(__mode: int, __path: StrOrBytesPath, __argv: _ExecVArgs) -> int: ... - def spawnve(__mode: int, __path: StrOrBytesPath, __argv: _ExecVArgs, __env: _ExecEnv) -> int: ... + def spawnv(mode: int, path: StrOrBytesPath, argv: _ExecVArgs, /) -> int: ... + def spawnve(mode: int, path: StrOrBytesPath, argv: _ExecVArgs, env: _ExecEnv, /) -> int: ... def system(command: StrOrBytesPath) -> int: ... @final @@ -951,7 +951,7 @@ class times_result(structseq[float], tuple[float, float, float, float, float]): def elapsed(self) -> float: ... def times() -> times_result: ... -def waitpid(__pid: int, __options: int) -> tuple[int, int]: ... +def waitpid(pid: int, options: int, /) -> tuple[int, int]: ... if sys.platform == "win32": if sys.version_info >= (3, 10): @@ -988,13 +988,13 @@ else: @property def si_code(self) -> int: ... - def waitid(__idtype: int, __ident: int, __options: int) -> waitid_result | None: ... + def waitid(idtype: int, ident: int, options: int, /) -> waitid_result | None: ... from resource import struct_rusage def wait3(options: int) -> tuple[int, int, struct_rusage]: ... def wait4(pid: int, options: int) -> tuple[int, int, struct_rusage]: ... - def WCOREDUMP(__status: int) -> bool: ... + def WCOREDUMP(status: int, /) -> bool: ... def WIFCONTINUED(status: int) -> bool: ... def WIFSTOPPED(status: int) -> bool: ... def WIFSIGNALED(status: int) -> bool: ... @@ -1003,9 +1003,10 @@ else: def WSTOPSIG(status: int) -> int: ... def WTERMSIG(status: int) -> int: ... def posix_spawn( - __path: StrOrBytesPath, - __argv: _ExecVArgs, - __env: _ExecEnv, + path: StrOrBytesPath, + argv: _ExecVArgs, + env: _ExecEnv, + /, *, file_actions: Sequence[tuple[Any, ...]] | None = ..., setpgroup: int | None = ..., @@ -1016,9 +1017,10 @@ else: scheduler: tuple[Any, sched_param] | None = ..., ) -> int: ... def posix_spawnp( - __path: StrOrBytesPath, - __argv: _ExecVArgs, - __env: _ExecEnv, + path: StrOrBytesPath, + argv: _ExecVArgs, + env: _ExecEnv, + /, *, file_actions: Sequence[tuple[Any, ...]] | None = ..., setpgroup: int | None = ..., @@ -1046,26 +1048,26 @@ if sys.platform != "win32": def sched_get_priority_max(policy: int) -> int: ... # some flavors of Unix def sched_yield() -> None: ... # some flavors of Unix if sys.platform != "darwin": - def sched_setscheduler(__pid: int, __policy: int, __param: sched_param) -> None: ... # some flavors of Unix - def sched_getscheduler(__pid: int) -> int: ... # some flavors of Unix - def sched_rr_get_interval(__pid: int) -> float: ... # some flavors of Unix - def sched_setparam(__pid: int, __param: sched_param) -> None: ... # some flavors of Unix - def sched_getparam(__pid: int) -> sched_param: ... # some flavors of Unix - def sched_setaffinity(__pid: int, __mask: Iterable[int]) -> None: ... # some flavors of Unix - def sched_getaffinity(__pid: int) -> set[int]: ... # some flavors of Unix + def sched_setscheduler(pid: int, policy: int, param: sched_param, /) -> None: ... # some flavors of Unix + def sched_getscheduler(pid: int, /) -> int: ... # some flavors of Unix + def sched_rr_get_interval(pid: int, /) -> float: ... # some flavors of Unix + def sched_setparam(pid: int, param: sched_param, /) -> None: ... # some flavors of Unix + def sched_getparam(pid: int, /) -> sched_param: ... # some flavors of Unix + def sched_setaffinity(pid: int, mask: Iterable[int], /) -> None: ... # some flavors of Unix + def sched_getaffinity(pid: int, /) -> set[int]: ... # some flavors of Unix def cpu_count() -> int | None: ... if sys.platform != "win32": # Unix only - def confstr(__name: str | int) -> str | None: ... + def confstr(name: str | int, /) -> str | None: ... def getloadavg() -> tuple[float, float, float]: ... - def sysconf(__name: str | int) -> int: ... + def sysconf(name: str | int, /) -> int: ... if sys.platform == "linux": def getrandom(size: int, flags: int = 0) -> bytes: ... -def urandom(__size: int) -> bytes: ... +def urandom(size: int, /) -> bytes: ... if sys.platform != "win32": def register_at_fork( diff --git a/mypy/typeshed/stdlib/pathlib.pyi b/mypy/typeshed/stdlib/pathlib.pyi index c3b0b7ad6337..5ea025095f68 100644 --- a/mypy/typeshed/stdlib/pathlib.pyi +++ b/mypy/typeshed/stdlib/pathlib.pyi @@ -59,7 +59,7 @@ class PurePath(PathLike[str]): def is_absolute(self) -> bool: ... def is_reserved(self) -> bool: ... if sys.version_info >= (3, 12): - def is_relative_to(self, __other: StrPath, *_deprecated: StrPath) -> bool: ... + def is_relative_to(self, other: StrPath, /, *_deprecated: StrPath) -> bool: ... elif sys.version_info >= (3, 9): def is_relative_to(self, *other: StrPath) -> bool: ... @@ -69,7 +69,7 @@ class PurePath(PathLike[str]): def match(self, path_pattern: str) -> bool: ... if sys.version_info >= (3, 12): - def relative_to(self, __other: StrPath, *_deprecated: StrPath, walk_up: bool = False) -> Self: ... + def relative_to(self, other: StrPath, /, *_deprecated: StrPath, walk_up: bool = False) -> Self: ... else: def relative_to(self, *other: StrPath) -> Self: ... diff --git a/mypy/typeshed/stdlib/pickle.pyi b/mypy/typeshed/stdlib/pickle.pyi index 0a4d439976ff..98ec80b0f14e 100644 --- a/mypy/typeshed/stdlib/pickle.pyi +++ b/mypy/typeshed/stdlib/pickle.pyi @@ -94,7 +94,7 @@ DEFAULT_PROTOCOL: int bytes_types: tuple[type[Any], ...] # undocumented class _ReadableFileobj(Protocol): - def read(self, __n: int) -> bytes: ... + def read(self, n: int, /) -> bytes: ... def readline(self) -> bytes: ... @final @@ -102,8 +102,8 @@ class PickleBuffer: def __init__(self, buffer: ReadableBuffer) -> None: ... def raw(self) -> memoryview: ... def release(self) -> None: ... - def __buffer__(self, __flags: int) -> memoryview: ... - def __release_buffer__(self, __buffer: memoryview) -> None: ... + def __buffer__(self, flags: int, /) -> memoryview: ... + def __release_buffer__(self, buffer: memoryview, /) -> None: ... _BufferCallback: TypeAlias = Callable[[PickleBuffer], Any] | None @@ -127,7 +127,8 @@ def load( buffers: Iterable[Any] | None = (), ) -> Any: ... def loads( - __data: ReadableBuffer, + data: ReadableBuffer, + /, *, fix_imports: bool = True, encoding: str = "ASCII", @@ -162,7 +163,7 @@ class Pickler: buffer_callback: _BufferCallback = ..., ) -> None: ... def reducer_override(self, obj: Any) -> Any: ... - def dump(self, __obj: Any) -> None: ... + def dump(self, obj: Any, /) -> None: ... def clear_memo(self) -> None: ... def persistent_id(self, obj: Any) -> Any: ... @@ -179,7 +180,7 @@ class Unpickler: buffers: Iterable[Any] | None = ..., ) -> None: ... def load(self) -> Any: ... - def find_class(self, __module_name: str, __global_name: str) -> Any: ... + def find_class(self, module_name: str, global_name: str, /) -> Any: ... def persistent_load(self, pid: Any) -> Any: ... MARK: bytes diff --git a/mypy/typeshed/stdlib/posixpath.pyi b/mypy/typeshed/stdlib/posixpath.pyi index 29e7c0f01017..1fc471ac7d0b 100644 --- a/mypy/typeshed/stdlib/posixpath.pyi +++ b/mypy/typeshed/stdlib/posixpath.pyi @@ -112,11 +112,11 @@ def commonpath(paths: Iterable[BytesPath]) -> bytes: ... # but must be defined as pos-only in the stub or cross-platform code doesn't type-check, # as the parameter name is different in ntpath.join() @overload -def join(__a: LiteralString, *paths: LiteralString) -> LiteralString: ... +def join(a: LiteralString, /, *paths: LiteralString) -> LiteralString: ... @overload -def join(__a: StrPath, *paths: StrPath) -> str: ... +def join(a: StrPath, /, *paths: StrPath) -> str: ... @overload -def join(__a: BytesPath, *paths: BytesPath) -> bytes: ... +def join(a: BytesPath, /, *paths: BytesPath) -> bytes: ... if sys.version_info >= (3, 10): @overload diff --git a/mypy/typeshed/stdlib/profile.pyi b/mypy/typeshed/stdlib/profile.pyi index 6ae375004158..73eba36344fe 100644 --- a/mypy/typeshed/stdlib/profile.pyi +++ b/mypy/typeshed/stdlib/profile.pyi @@ -27,5 +27,5 @@ class Profile: def snapshot_stats(self) -> None: ... def run(self, cmd: str) -> Self: ... def runctx(self, cmd: str, globals: dict[str, Any], locals: dict[str, Any]) -> Self: ... - def runcall(self, __func: Callable[_P, _T], *args: _P.args, **kw: _P.kwargs) -> _T: ... + def runcall(self, func: Callable[_P, _T], /, *args: _P.args, **kw: _P.kwargs) -> _T: ... def calibrate(self, m: int, verbose: int = 0) -> float: ... diff --git a/mypy/typeshed/stdlib/pstats.pyi b/mypy/typeshed/stdlib/pstats.pyi index 86f88da9e712..d1571fd94be5 100644 --- a/mypy/typeshed/stdlib/pstats.pyi +++ b/mypy/typeshed/stdlib/pstats.pyi @@ -48,7 +48,8 @@ class Stats: sort_arg_dict_default: _SortArgDict def __init__( self, - __arg: None | str | Profile | _cProfile = ..., + arg: None | str | Profile | _cProfile = ..., + /, *args: None | str | Profile | _cProfile | Self, stream: IO[Any] | None = None, ) -> None: ... diff --git a/mypy/typeshed/stdlib/pwd.pyi b/mypy/typeshed/stdlib/pwd.pyi index 9a8e1036e550..a84ba324718a 100644 --- a/mypy/typeshed/stdlib/pwd.pyi +++ b/mypy/typeshed/stdlib/pwd.pyi @@ -24,5 +24,5 @@ if sys.platform != "win32": def pw_shell(self) -> str: ... def getpwall() -> list[struct_passwd]: ... - def getpwuid(__uid: int) -> struct_passwd: ... - def getpwnam(__name: str) -> struct_passwd: ... + def getpwuid(uid: int, /) -> struct_passwd: ... + def getpwnam(name: str, /) -> struct_passwd: ... diff --git a/mypy/typeshed/stdlib/pyexpat/__init__.pyi b/mypy/typeshed/stdlib/pyexpat/__init__.pyi index 2188e458474c..10011b437b6a 100644 --- a/mypy/typeshed/stdlib/pyexpat/__init__.pyi +++ b/mypy/typeshed/stdlib/pyexpat/__init__.pyi @@ -24,14 +24,14 @@ _Model: TypeAlias = tuple[int, int, str | None, tuple[Any, ...]] @final class XMLParserType: - def Parse(self, __data: str | ReadableBuffer, __isfinal: bool = False) -> int: ... - def ParseFile(self, __file: SupportsRead[bytes]) -> int: ... - def SetBase(self, __base: str) -> None: ... + def Parse(self, data: str | ReadableBuffer, isfinal: bool = False, /) -> int: ... + def ParseFile(self, file: SupportsRead[bytes], /) -> int: ... + def SetBase(self, base: str, /) -> None: ... def GetBase(self) -> str | None: ... def GetInputContext(self) -> bytes | None: ... - def ExternalEntityParserCreate(self, __context: str | None, __encoding: str = ...) -> XMLParserType: ... - def SetParamEntityParsing(self, __flag: int) -> int: ... - def UseForeignDTD(self, __flag: bool = True) -> None: ... + def ExternalEntityParserCreate(self, context: str | None, encoding: str = ..., /) -> XMLParserType: ... + def SetParamEntityParsing(self, flag: int, /) -> int: ... + def UseForeignDTD(self, flag: bool = True, /) -> None: ... @property def intern(self) -> dict[str, str]: ... buffer_size: int @@ -75,7 +75,7 @@ class XMLParserType: ExternalEntityRefHandler: Callable[[str, str | None, str | None, str | None], int] | None SkippedEntityHandler: Callable[[str, bool], Any] | None -def ErrorString(__code: int) -> str: ... +def ErrorString(code: int, /) -> str: ... # intern is undocumented def ParserCreate( diff --git a/mypy/typeshed/stdlib/re.pyi b/mypy/typeshed/stdlib/re.pyi index 84c6cfceb1de..7945c5f46cdc 100644 --- a/mypy/typeshed/stdlib/re.pyi +++ b/mypy/typeshed/stdlib/re.pyi @@ -72,11 +72,11 @@ class Match(Generic[AnyStr]): def expand(self, template: AnyStr) -> AnyStr: ... # group() returns "AnyStr" or "AnyStr | None", depending on the pattern. @overload - def group(self, __group: Literal[0] = 0) -> AnyStr: ... + def group(self, group: Literal[0] = 0, /) -> AnyStr: ... @overload - def group(self, __group: str | int) -> AnyStr | Any: ... + def group(self, group: str | int, /) -> AnyStr | Any: ... @overload - def group(self, __group1: str | int, __group2: str | int, *groups: str | int) -> tuple[AnyStr | Any, ...]: ... + def group(self, group1: str | int, group2: str | int, /, *groups: str | int) -> tuple[AnyStr | Any, ...]: ... # Each item of groups()'s return tuple is either "AnyStr" or # "AnyStr | None", depending on the pattern. @overload @@ -89,18 +89,18 @@ class Match(Generic[AnyStr]): def groupdict(self) -> dict[str, AnyStr | Any]: ... @overload def groupdict(self, default: _T) -> dict[str, AnyStr | _T]: ... - def start(self, __group: int | str = 0) -> int: ... - def end(self, __group: int | str = 0) -> int: ... - def span(self, __group: int | str = 0) -> tuple[int, int]: ... + def start(self, group: int | str = 0, /) -> int: ... + def end(self, group: int | str = 0, /) -> int: ... + def span(self, group: int | str = 0, /) -> tuple[int, int]: ... @property def regs(self) -> tuple[tuple[int, int], ...]: ... # undocumented # __getitem__() returns "AnyStr" or "AnyStr | None", depending on the pattern. @overload - def __getitem__(self, __key: Literal[0]) -> AnyStr: ... + def __getitem__(self, key: Literal[0], /) -> AnyStr: ... @overload - def __getitem__(self, __key: int | str) -> AnyStr | Any: ... + def __getitem__(self, key: int | str, /) -> AnyStr | Any: ... def __copy__(self) -> Match[AnyStr]: ... - def __deepcopy__(self, __memo: Any) -> Match[AnyStr]: ... + def __deepcopy__(self, memo: Any, /) -> Match[AnyStr]: ... if sys.version_info >= (3, 9): def __class_getitem__(cls, item: Any) -> GenericAlias: ... @@ -174,8 +174,8 @@ class Pattern(Generic[AnyStr]): @overload def subn(self, repl: AnyStr | Callable[[Match[AnyStr]], AnyStr], string: AnyStr, count: int = 0) -> tuple[AnyStr, int]: ... def __copy__(self) -> Pattern[AnyStr]: ... - def __deepcopy__(self, __memo: Any) -> Pattern[AnyStr]: ... - def __eq__(self, __value: object) -> bool: ... + def __deepcopy__(self, memo: Any, /) -> Pattern[AnyStr]: ... + def __eq__(self, value: object, /) -> bool: ... def __hash__(self) -> int: ... if sys.version_info >= (3, 9): def __class_getitem__(cls, item: Any) -> GenericAlias: ... diff --git a/mypy/typeshed/stdlib/readline.pyi b/mypy/typeshed/stdlib/readline.pyi index 14c01a986351..688ae48d9f92 100644 --- a/mypy/typeshed/stdlib/readline.pyi +++ b/mypy/typeshed/stdlib/readline.pyi @@ -7,30 +7,30 @@ if sys.platform != "win32": _Completer: TypeAlias = Callable[[str, int], str | None] _CompDisp: TypeAlias = Callable[[str, Sequence[str], int], None] - def parse_and_bind(__string: str) -> None: ... - def read_init_file(__filename: StrOrBytesPath | None = None) -> None: ... + def parse_and_bind(string: str, /) -> None: ... + def read_init_file(filename: StrOrBytesPath | None = None, /) -> None: ... def get_line_buffer() -> str: ... - def insert_text(__string: str) -> None: ... + def insert_text(string: str, /) -> None: ... def redisplay() -> None: ... - def read_history_file(__filename: StrOrBytesPath | None = None) -> None: ... - def write_history_file(__filename: StrOrBytesPath | None = None) -> None: ... - def append_history_file(__nelements: int, __filename: StrOrBytesPath | None = None) -> None: ... + def read_history_file(filename: StrOrBytesPath | None = None, /) -> None: ... + def write_history_file(filename: StrOrBytesPath | None = None, /) -> None: ... + def append_history_file(nelements: int, filename: StrOrBytesPath | None = None, /) -> None: ... def get_history_length() -> int: ... - def set_history_length(__length: int) -> None: ... + def set_history_length(length: int, /) -> None: ... def clear_history() -> None: ... def get_current_history_length() -> int: ... - def get_history_item(__index: int) -> str: ... - def remove_history_item(__pos: int) -> None: ... - def replace_history_item(__pos: int, __line: str) -> None: ... - def add_history(__string: str) -> None: ... - def set_auto_history(__enabled: bool) -> None: ... - def set_startup_hook(__function: Callable[[], object] | None = None) -> None: ... - def set_pre_input_hook(__function: Callable[[], object] | None = None) -> None: ... - def set_completer(__function: _Completer | None = None) -> None: ... + def get_history_item(index: int, /) -> str: ... + def remove_history_item(pos: int, /) -> None: ... + def replace_history_item(pos: int, line: str, /) -> None: ... + def add_history(string: str, /) -> None: ... + def set_auto_history(enabled: bool, /) -> None: ... + def set_startup_hook(function: Callable[[], object] | None = None, /) -> None: ... + def set_pre_input_hook(function: Callable[[], object] | None = None, /) -> None: ... + def set_completer(function: _Completer | None = None, /) -> None: ... def get_completer() -> _Completer | None: ... def get_completion_type() -> int: ... def get_begidx() -> int: ... def get_endidx() -> int: ... - def set_completer_delims(__string: str) -> None: ... + def set_completer_delims(string: str, /) -> None: ... def get_completer_delims() -> str: ... - def set_completion_display_matches_hook(__function: _CompDisp | None = None) -> None: ... + def set_completion_display_matches_hook(function: _CompDisp | None = None, /) -> None: ... diff --git a/mypy/typeshed/stdlib/resource.pyi b/mypy/typeshed/stdlib/resource.pyi index f40e5ec1ea55..5e468c2cead5 100644 --- a/mypy/typeshed/stdlib/resource.pyi +++ b/mypy/typeshed/stdlib/resource.pyi @@ -83,12 +83,12 @@ if sys.platform != "win32": def ru_nivcsw(self) -> int: ... def getpagesize() -> int: ... - def getrlimit(__resource: int) -> tuple[int, int]: ... - def getrusage(__who: int) -> struct_rusage: ... - def setrlimit(__resource: int, __limits: tuple[int, int]) -> None: ... + def getrlimit(resource: int, /) -> tuple[int, int]: ... + def getrusage(who: int, /) -> struct_rusage: ... + def setrlimit(resource: int, limits: tuple[int, int], /) -> None: ... if sys.platform == "linux": if sys.version_info >= (3, 12): - def prlimit(__pid: int, __resource: int, __limits: tuple[int, int] | None = None) -> tuple[int, int]: ... + def prlimit(pid: int, resource: int, limits: tuple[int, int] | None = None, /) -> tuple[int, int]: ... else: - def prlimit(__pid: int, __resource: int, __limits: tuple[int, int] = ...) -> tuple[int, int]: ... + def prlimit(pid: int, resource: int, limits: tuple[int, int] = ..., /) -> tuple[int, int]: ... error = OSError diff --git a/mypy/typeshed/stdlib/select.pyi b/mypy/typeshed/stdlib/select.pyi index afab88e18453..6d4c8d8f4c15 100644 --- a/mypy/typeshed/stdlib/select.pyi +++ b/mypy/typeshed/stdlib/select.pyi @@ -28,7 +28,7 @@ class poll: def poll(self, timeout: float | None = ...) -> list[tuple[int, int]]: ... def select( - __rlist: Iterable[Any], __wlist: Iterable[Any], __xlist: Iterable[Any], __timeout: float | None = None + rlist: Iterable[Any], wlist: Iterable[Any], xlist: Iterable[Any], timeout: float | None = None, / ) -> tuple[list[Any], list[Any], list[Any]]: ... error = OSError @@ -60,11 +60,11 @@ if sys.platform != "linux" and sys.platform != "win32": def __init__(self) -> None: ... def close(self) -> None: ... def control( - self, __changelist: Iterable[kevent] | None, __maxevents: int, __timeout: float | None = None + self, changelist: Iterable[kevent] | None, maxevents: int, timeout: float | None = None, / ) -> list[kevent]: ... def fileno(self) -> int: ... @classmethod - def fromfd(cls, __fd: FileDescriptorLike) -> kqueue: ... + def fromfd(cls, fd: FileDescriptorLike, /) -> kqueue: ... KQ_EV_ADD: int KQ_EV_CLEAR: int @@ -112,9 +112,10 @@ if sys.platform == "linux": def __enter__(self) -> Self: ... def __exit__( self, - __exc_type: type[BaseException] | None = None, - __exc_value: BaseException | None = ..., - __exc_tb: TracebackType | None = None, + exc_type: type[BaseException] | None = None, + exc_value: BaseException | None = ..., + exc_tb: TracebackType | None = None, + /, ) -> None: ... def close(self) -> None: ... closed: bool @@ -124,7 +125,7 @@ if sys.platform == "linux": def unregister(self, fd: FileDescriptorLike) -> None: ... def poll(self, timeout: float | None = None, maxevents: int = -1) -> list[tuple[int, int]]: ... @classmethod - def fromfd(cls, __fd: FileDescriptorLike) -> epoll: ... + def fromfd(cls, fd: FileDescriptorLike, /) -> epoll: ... EPOLLERR: int EPOLLEXCLUSIVE: int diff --git a/mypy/typeshed/stdlib/signal.pyi b/mypy/typeshed/stdlib/signal.pyi index 544473df9932..d1fb3ba963d4 100644 --- a/mypy/typeshed/stdlib/signal.pyi +++ b/mypy/typeshed/stdlib/signal.pyi @@ -67,15 +67,15 @@ SIG_IGN: Handlers _SIGNUM: TypeAlias = int | Signals _HANDLER: TypeAlias = Callable[[int, FrameType | None], Any] | int | Handlers | None -def default_int_handler(__signalnum: int, __frame: FrameType | None) -> Never: ... +def default_int_handler(signalnum: int, frame: FrameType | None, /) -> Never: ... if sys.version_info >= (3, 10): # arguments changed in 3.10.2 def getsignal(signalnum: _SIGNUM) -> _HANDLER: ... def signal(signalnum: _SIGNUM, handler: _HANDLER) -> _HANDLER: ... else: - def getsignal(__signalnum: _SIGNUM) -> _HANDLER: ... - def signal(__signalnum: _SIGNUM, __handler: _HANDLER) -> _HANDLER: ... + def getsignal(signalnum: _SIGNUM, /) -> _HANDLER: ... + def signal(signalnum: _SIGNUM, handler: _HANDLER, /) -> _HANDLER: ... SIGABRT: Signals SIGFPE: Signals @@ -130,22 +130,22 @@ else: SIG_BLOCK = Sigmasks.SIG_BLOCK SIG_UNBLOCK = Sigmasks.SIG_UNBLOCK SIG_SETMASK = Sigmasks.SIG_SETMASK - def alarm(__seconds: int) -> int: ... - def getitimer(__which: int) -> tuple[float, float]: ... + def alarm(seconds: int, /) -> int: ... + def getitimer(which: int, /) -> tuple[float, float]: ... def pause() -> None: ... - def pthread_kill(__thread_id: int, __signalnum: int) -> None: ... + def pthread_kill(thread_id: int, signalnum: int, /) -> None: ... if sys.version_info >= (3, 10): # arguments changed in 3.10.2 def pthread_sigmask(how: int, mask: Iterable[int]) -> set[_SIGNUM]: ... else: - def pthread_sigmask(__how: int, __mask: Iterable[int]) -> set[_SIGNUM]: ... + def pthread_sigmask(how: int, mask: Iterable[int], /) -> set[_SIGNUM]: ... - def setitimer(__which: int, __seconds: float, __interval: float = 0.0) -> tuple[float, float]: ... - def siginterrupt(__signalnum: int, __flag: bool) -> None: ... + def setitimer(which: int, seconds: float, interval: float = 0.0, /) -> tuple[float, float]: ... + def siginterrupt(signalnum: int, flag: bool, /) -> None: ... def sigpending() -> Any: ... if sys.version_info >= (3, 10): # argument changed in 3.10.2 def sigwait(sigset: Iterable[int]) -> _SIGNUM: ... else: - def sigwait(__sigset: Iterable[int]) -> _SIGNUM: ... + def sigwait(sigset: Iterable[int], /) -> _SIGNUM: ... if sys.platform != "darwin": SIGCLD: Signals SIGPOLL: Signals @@ -176,17 +176,17 @@ else: def si_band(self) -> int: ... if sys.version_info >= (3, 10): - def sigtimedwait(__sigset: Iterable[int], __timeout: float) -> struct_siginfo | None: ... - def sigwaitinfo(__sigset: Iterable[int]) -> struct_siginfo: ... + def sigtimedwait(sigset: Iterable[int], timeout: float, /) -> struct_siginfo | None: ... + def sigwaitinfo(sigset: Iterable[int], /) -> struct_siginfo: ... else: def sigtimedwait(sigset: Iterable[int], timeout: float) -> struct_siginfo | None: ... def sigwaitinfo(sigset: Iterable[int]) -> struct_siginfo: ... -def strsignal(__signalnum: _SIGNUM) -> str | None: ... +def strsignal(signalnum: _SIGNUM, /) -> str | None: ... def valid_signals() -> set[Signals]: ... -def raise_signal(__signalnum: _SIGNUM) -> None: ... +def raise_signal(signalnum: _SIGNUM, /) -> None: ... def set_wakeup_fd(fd: int, *, warn_on_full_buffer: bool = ...) -> int: ... if sys.version_info >= (3, 9): if sys.platform == "linux": - def pidfd_send_signal(__pidfd: int, __sig: int, __siginfo: None = None, __flags: int = ...) -> None: ... + def pidfd_send_signal(pidfd: int, sig: int, siginfo: None = None, flags: int = ..., /) -> None: ... diff --git a/mypy/typeshed/stdlib/smtplib.pyi b/mypy/typeshed/stdlib/smtplib.pyi index 6db7daebbb41..a762427bcab3 100644 --- a/mypy/typeshed/stdlib/smtplib.pyi +++ b/mypy/typeshed/stdlib/smtplib.pyi @@ -68,9 +68,9 @@ def quotedata(data: str) -> str: ... class _AuthObject(Protocol): @overload - def __call__(self, __challenge: None = None) -> str | None: ... + def __call__(self, challenge: None = None, /) -> str | None: ... @overload - def __call__(self, __challenge: bytes) -> str: ... + def __call__(self, challenge: bytes, /) -> str: ... class SMTP: debuglevel: int diff --git a/mypy/typeshed/stdlib/socket.pyi b/mypy/typeshed/stdlib/socket.pyi index ce5e35228fe4..cdbd70533714 100644 --- a/mypy/typeshed/stdlib/socket.pyi +++ b/mypy/typeshed/stdlib/socket.pyi @@ -682,8 +682,8 @@ if sys.platform == "win32": errorTab: dict[int, str] # undocumented class _SendableFile(Protocol): - def read(self, __size: int) -> bytes: ... - def seek(self, __offset: int) -> object: ... + def read(self, size: int, /) -> bytes: ... + def seek(self, offset: int, /) -> object: ... # optional fields: # @@ -803,7 +803,7 @@ def getfqdn(name: str = "") -> str: ... if sys.version_info >= (3, 11): def create_connection( address: tuple[str | None, int], - timeout: float | None = ..., # noqa: F811 + timeout: float | None = ..., source_address: _Address | None = None, *, all_errors: bool = False, @@ -811,7 +811,7 @@ if sys.version_info >= (3, 11): else: def create_connection( - address: tuple[str | None, int], timeout: float | None = ..., source_address: _Address | None = None # noqa: F811 + address: tuple[str | None, int], timeout: float | None = ..., source_address: _Address | None = None ) -> socket: ... def has_dualstack_ipv6() -> bool: ... diff --git a/mypy/typeshed/stdlib/spwd.pyi b/mypy/typeshed/stdlib/spwd.pyi index d362a0b77573..67ad3bfc751b 100644 --- a/mypy/typeshed/stdlib/spwd.pyi +++ b/mypy/typeshed/stdlib/spwd.pyi @@ -38,4 +38,4 @@ if sys.platform != "win32": def sp_flag(self) -> int: ... def getspall() -> list[struct_spwd]: ... - def getspnam(__arg: str) -> struct_spwd: ... + def getspnam(arg: str, /) -> struct_spwd: ... diff --git a/mypy/typeshed/stdlib/sqlite3/dbapi2.pyi b/mypy/typeshed/stdlib/sqlite3/dbapi2.pyi index 7cf75bbc33c5..068ce1514c3c 100644 --- a/mypy/typeshed/stdlib/sqlite3/dbapi2.pyi +++ b/mypy/typeshed/stdlib/sqlite3/dbapi2.pyi @@ -8,6 +8,7 @@ from typing import Any, Literal, Protocol, SupportsIndex, TypeVar, final, overlo from typing_extensions import Self, TypeAlias _T = TypeVar("_T") +_ConnectionT = TypeVar("_ConnectionT", bound=Connection) _CursorT = TypeVar("_CursorT", bound=Cursor) _SqliteData: TypeAlias = str | ReadableBuffer | int | float | None # Data that is passed through adapters can be of any type accepted by an adapter. @@ -217,57 +218,107 @@ if sys.version_info >= (3, 12): # Can take or return anything depending on what's in the registry. @overload -def adapt(__obj: Any, __proto: Any) -> Any: ... +def adapt(obj: Any, proto: Any, /) -> Any: ... @overload -def adapt(__obj: Any, __proto: Any, __alt: _T) -> Any | _T: ... +def adapt(obj: Any, proto: Any, alt: _T, /) -> Any | _T: ... def complete_statement(statement: str) -> bool: ... if sys.version_info >= (3, 12): + @overload def connect( database: StrOrBytesPath, - timeout: float = ..., - detect_types: int = ..., - isolation_level: str | None = ..., - check_same_thread: bool = ..., - factory: type[Connection] | None = ..., - cached_statements: int = ..., - uri: bool = ..., + timeout: float = 5.0, + detect_types: int = 0, + isolation_level: Literal["DEFERRED", "EXCLUSIVE", "IMMEDIATE"] | None = "DEFERRED", + check_same_thread: bool = True, + cached_statements: int = 128, + uri: bool = False, + *, autocommit: bool = ..., ) -> Connection: ... + @overload + def connect( + database: StrOrBytesPath, + timeout: float, + detect_types: int, + isolation_level: Literal["DEFERRED", "EXCLUSIVE", "IMMEDIATE"] | None, + check_same_thread: bool, + factory: type[_ConnectionT], + cached_statements: int = 128, + uri: bool = False, + *, + autocommit: bool = ..., + ) -> _ConnectionT: ... + @overload + def connect( + database: StrOrBytesPath, + timeout: float = 5.0, + detect_types: int = 0, + isolation_level: Literal["DEFERRED", "EXCLUSIVE", "IMMEDIATE"] | None = "DEFERRED", + check_same_thread: bool = True, + *, + factory: type[_ConnectionT], + cached_statements: int = 128, + uri: bool = False, + autocommit: bool = ..., + ) -> _ConnectionT: ... else: + @overload def connect( database: StrOrBytesPath, - timeout: float = ..., - detect_types: int = ..., - isolation_level: str | None = ..., - check_same_thread: bool = ..., - factory: type[Connection] | None = ..., - cached_statements: int = ..., - uri: bool = ..., + timeout: float = 5.0, + detect_types: int = 0, + isolation_level: Literal["DEFERRED", "EXCLUSIVE", "IMMEDIATE"] | None = "DEFERRED", + check_same_thread: bool = True, + cached_statements: int = 128, + uri: bool = False, ) -> Connection: ... + @overload + def connect( + database: StrOrBytesPath, + timeout: float, + detect_types: int, + isolation_level: Literal["DEFERRED", "EXCLUSIVE", "IMMEDIATE"] | None, + check_same_thread: bool, + factory: type[_ConnectionT], + cached_statements: int = 128, + uri: bool = False, + ) -> _ConnectionT: ... + @overload + def connect( + database: StrOrBytesPath, + timeout: float = 5.0, + detect_types: int = 0, + isolation_level: Literal["DEFERRED", "EXCLUSIVE", "IMMEDIATE"] | None = "DEFERRED", + check_same_thread: bool = True, + *, + factory: type[_ConnectionT], + cached_statements: int = 128, + uri: bool = False, + ) -> _ConnectionT: ... -def enable_callback_tracebacks(__enable: bool) -> None: ... +def enable_callback_tracebacks(enable: bool, /) -> None: ... if sys.version_info < (3, 12): # takes a pos-or-keyword argument because there is a C wrapper def enable_shared_cache(enable: int) -> None: ... if sys.version_info >= (3, 10): - def register_adapter(__type: type[_T], __adapter: _Adapter[_T]) -> None: ... - def register_converter(__typename: str, __converter: _Converter) -> None: ... + def register_adapter(type: type[_T], adapter: _Adapter[_T], /) -> None: ... + def register_converter(typename: str, converter: _Converter, /) -> None: ... else: - def register_adapter(__type: type[_T], __caster: _Adapter[_T]) -> None: ... - def register_converter(__name: str, __converter: _Converter) -> None: ... + def register_adapter(type: type[_T], caster: _Adapter[_T], /) -> None: ... + def register_converter(name: str, converter: _Converter, /) -> None: ... class _AggregateProtocol(Protocol): - def step(self, __value: int) -> object: ... + def step(self, value: int, /) -> object: ... def finalize(self) -> int: ... class _SingleParamWindowAggregateClass(Protocol): - def step(self, __param: Any) -> object: ... - def inverse(self, __param: Any) -> object: ... + def step(self, param: Any, /) -> object: ... + def inverse(self, param: Any, /) -> object: ... def value(self) -> _SqliteData: ... def finalize(self) -> _SqliteData: ... @@ -344,7 +395,7 @@ class Connection: def close(self) -> None: ... if sys.version_info >= (3, 11): - def blobopen(self, __table: str, __column: str, __row: int, *, readonly: bool = False, name: str = "main") -> Blob: ... + def blobopen(self, table: str, column: str, row: int, /, *, readonly: bool = False, name: str = "main") -> Blob: ... def commit(self) -> None: ... def create_aggregate(self, name: str, n_arg: int, aggregate_class: Callable[[], _AggregateProtocol]) -> None: ... @@ -353,19 +404,19 @@ class Connection: # for the case where num_params = 1, which is expected to be the common case. @overload def create_window_function( - self, __name: str, __num_params: Literal[1], __aggregate_class: Callable[[], _SingleParamWindowAggregateClass] | None + self, name: str, num_params: Literal[1], aggregate_class: Callable[[], _SingleParamWindowAggregateClass] | None, / ) -> None: ... # And for num_params = -1, which means the aggregate must accept any number of parameters. @overload def create_window_function( - self, __name: str, __num_params: Literal[-1], __aggregate_class: Callable[[], _AnyParamWindowAggregateClass] | None + self, name: str, num_params: Literal[-1], aggregate_class: Callable[[], _AnyParamWindowAggregateClass] | None, / ) -> None: ... @overload def create_window_function( - self, __name: str, __num_params: int, __aggregate_class: Callable[[], _WindowAggregateClass] | None + self, name: str, num_params: int, aggregate_class: Callable[[], _WindowAggregateClass] | None, / ) -> None: ... - def create_collation(self, __name: str, __callback: Callable[[str, str], int | SupportsIndex] | None) -> None: ... + def create_collation(self, name: str, callback: Callable[[str, str], int | SupportsIndex] | None, /) -> None: ... def create_function( self, name: str, narg: int, func: Callable[..., _SqliteData] | None, *, deterministic: bool = False ) -> None: ... @@ -373,9 +424,9 @@ class Connection: def cursor(self, factory: None = None) -> Cursor: ... @overload def cursor(self, factory: Callable[[Connection], _CursorT]) -> _CursorT: ... - def execute(self, __sql: str, __parameters: _Parameters = ...) -> Cursor: ... - def executemany(self, __sql: str, __parameters: Iterable[_Parameters]) -> Cursor: ... - def executescript(self, __sql_script: str) -> Cursor: ... + def execute(self, sql: str, parameters: _Parameters = ..., /) -> Cursor: ... + def executemany(self, sql: str, parameters: Iterable[_Parameters], /) -> Cursor: ... + def executescript(self, sql_script: str, /) -> Cursor: ... def interrupt(self) -> None: ... def iterdump(self) -> Generator[str, None, None]: ... def rollback(self) -> None: ... @@ -386,8 +437,8 @@ class Connection: def set_trace_callback(self, trace_callback: Callable[[str], object] | None) -> None: ... # enable_load_extension and load_extension is not available on python distributions compiled # without sqlite3 loadable extension support. see footnotes https://docs.python.org/3/library/sqlite3.html#f1 - def enable_load_extension(self, __enable: bool) -> None: ... - def load_extension(self, __name: str) -> None: ... + def enable_load_extension(self, enable: bool, /) -> None: ... + def load_extension(self, name: str, /) -> None: ... def backup( self, target: Connection, @@ -398,18 +449,18 @@ class Connection: sleep: float = 0.25, ) -> None: ... if sys.version_info >= (3, 11): - def setlimit(self, __category: int, __limit: int) -> int: ... - def getlimit(self, __category: int) -> int: ... + def setlimit(self, category: int, limit: int, /) -> int: ... + def getlimit(self, category: int, /) -> int: ... def serialize(self, *, name: str = "main") -> bytes: ... - def deserialize(self, __data: ReadableBuffer, *, name: str = "main") -> None: ... + def deserialize(self, data: ReadableBuffer, /, *, name: str = "main") -> None: ... if sys.version_info >= (3, 12): - def getconfig(self, __op: int) -> bool: ... - def setconfig(self, __op: int, __enable: bool = True) -> bool: ... + def getconfig(self, op: int, /) -> bool: ... + def setconfig(self, op: int, enable: bool = True, /) -> bool: ... - def __call__(self, __sql: str) -> _Statement: ... + def __call__(self, sql: str, /) -> _Statement: ... def __enter__(self) -> Self: ... def __exit__( - self, __type: type[BaseException] | None, __value: BaseException | None, __traceback: TracebackType | None + self, type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None, / ) -> Literal[False]: ... class Cursor(Iterator[Any]): @@ -424,18 +475,18 @@ class Cursor(Iterator[Any]): row_factory: Callable[[Cursor, Row], object] | None @property def rowcount(self) -> int: ... - def __init__(self, __cursor: Connection) -> None: ... + def __init__(self, cursor: Connection, /) -> None: ... def close(self) -> None: ... - def execute(self, __sql: str, __parameters: _Parameters = ()) -> Self: ... - def executemany(self, __sql: str, __seq_of_parameters: Iterable[_Parameters]) -> Self: ... - def executescript(self, __sql_script: str) -> Cursor: ... + def execute(self, sql: str, parameters: _Parameters = (), /) -> Self: ... + def executemany(self, sql: str, seq_of_parameters: Iterable[_Parameters], /) -> Self: ... + def executescript(self, sql_script: str, /) -> Cursor: ... def fetchall(self) -> list[Any]: ... def fetchmany(self, size: int | None = 1) -> list[Any]: ... # Returns either a row (as created by the row_factory) or None, but # putting None in the return annotation causes annoying false positives. def fetchone(self) -> Any: ... - def setinputsizes(self, __sizes: Unused) -> None: ... # does nothing - def setoutputsize(self, __size: Unused, __column: Unused = None) -> None: ... # does nothing + def setinputsizes(self, sizes: Unused, /) -> None: ... # does nothing + def setoutputsize(self, size: Unused, column: Unused = None, /) -> None: ... # does nothing def __iter__(self) -> Self: ... def __next__(self) -> Any: ... @@ -462,22 +513,22 @@ class PrepareProtocol: class ProgrammingError(DatabaseError): ... class Row: - def __init__(self, __cursor: Cursor, __data: tuple[Any, ...]) -> None: ... + def __init__(self, cursor: Cursor, data: tuple[Any, ...], /) -> None: ... def keys(self) -> list[str]: ... @overload - def __getitem__(self, __key: int | str) -> Any: ... + def __getitem__(self, key: int | str, /) -> Any: ... @overload - def __getitem__(self, __key: slice) -> tuple[Any, ...]: ... + def __getitem__(self, key: slice, /) -> tuple[Any, ...]: ... def __hash__(self) -> int: ... def __iter__(self) -> Iterator[Any]: ... def __len__(self) -> int: ... # These return NotImplemented for anything that is not a Row. - def __eq__(self, __value: object) -> bool: ... - def __ge__(self, __value: object) -> bool: ... - def __gt__(self, __value: object) -> bool: ... - def __le__(self, __value: object) -> bool: ... - def __lt__(self, __value: object) -> bool: ... - def __ne__(self, __value: object) -> bool: ... + def __eq__(self, value: object, /) -> bool: ... + def __ge__(self, value: object, /) -> bool: ... + def __gt__(self, value: object, /) -> bool: ... + def __le__(self, value: object, /) -> bool: ... + def __lt__(self, value: object, /) -> bool: ... + def __ne__(self, value: object, /) -> bool: ... @final class _Statement: ... @@ -488,13 +539,13 @@ if sys.version_info >= (3, 11): @final class Blob: def close(self) -> None: ... - def read(self, __length: int = -1) -> bytes: ... - def write(self, __data: ReadableBuffer) -> None: ... + def read(self, length: int = -1, /) -> bytes: ... + def write(self, data: ReadableBuffer, /) -> None: ... def tell(self) -> int: ... # whence must be one of os.SEEK_SET, os.SEEK_CUR, os.SEEK_END - def seek(self, __offset: int, __origin: int = 0) -> None: ... + def seek(self, offset: int, origin: int = 0, /) -> None: ... def __len__(self) -> int: ... def __enter__(self) -> Self: ... - def __exit__(self, __type: object, __val: object, __tb: object) -> Literal[False]: ... - def __getitem__(self, __key: SupportsIndex | slice) -> int: ... - def __setitem__(self, __key: SupportsIndex | slice, __value: int) -> None: ... + def __exit__(self, type: object, val: object, tb: object, /) -> Literal[False]: ... + def __getitem__(self, key: SupportsIndex | slice, /) -> int: ... + def __setitem__(self, key: SupportsIndex | slice, value: int, /) -> None: ... diff --git a/mypy/typeshed/stdlib/ssl.pyi b/mypy/typeshed/stdlib/ssl.pyi index 583ac82750ac..b2263df1337d 100644 --- a/mypy/typeshed/stdlib/ssl.pyi +++ b/mypy/typeshed/stdlib/ssl.pyi @@ -15,6 +15,8 @@ _PasswordType: TypeAlias = Callable[[], str | bytes | bytearray] | str | bytes | _SrvnmeCbType: TypeAlias = Callable[[SSLSocket | SSLObject, str | None, SSLSocket], int | None] +socket_error = OSError + class _Cipher(TypedDict): aead: bool alg_bits: int @@ -96,14 +98,14 @@ else: _create_default_https_context: Callable[..., SSLContext] -def RAND_bytes(__n: int) -> bytes: ... +def RAND_bytes(n: int, /) -> bytes: ... if sys.version_info < (3, 12): - def RAND_pseudo_bytes(__n: int) -> tuple[bytes, bool]: ... + def RAND_pseudo_bytes(n: int, /) -> tuple[bytes, bool]: ... def RAND_status() -> bool: ... def RAND_egd(path: str) -> None: ... -def RAND_add(__string: str | ReadableBuffer, __entropy: float) -> None: ... +def RAND_add(string: str | ReadableBuffer, entropy: float, /) -> None: ... if sys.version_info < (3, 12): def match_hostname(cert: _PeerCertRetDictType, hostname: str) -> None: ... @@ -420,12 +422,12 @@ class SSLContext: def get_ca_certs(self, binary_form: bool = False) -> Any: ... def get_ciphers(self) -> list[_Cipher]: ... def set_default_verify_paths(self) -> None: ... - def set_ciphers(self, __cipherlist: str) -> None: ... + def set_ciphers(self, cipherlist: str, /) -> None: ... def set_alpn_protocols(self, alpn_protocols: Iterable[str]) -> None: ... def set_npn_protocols(self, npn_protocols: Iterable[str]) -> None: ... def set_servername_callback(self, server_name_callback: _SrvnmeCbType | None) -> None: ... - def load_dh_params(self, __path: str) -> None: ... - def set_ecdh_curve(self, __name: str) -> None: ... + def load_dh_params(self, path: str, /) -> None: ... + def set_ecdh_curve(self, name: str, /) -> None: ... def wrap_socket( self, sock: socket.socket, @@ -479,8 +481,8 @@ class SSLObject: class MemoryBIO: pending: int eof: bool - def read(self, __size: int = -1) -> bytes: ... - def write(self, __b: ReadableBuffer) -> int: ... + def read(self, size: int = -1, /) -> bytes: ... + def write(self, b: ReadableBuffer, /) -> int: ... def write_eof(self) -> None: ... @final @@ -495,7 +497,7 @@ class SSLSession: def time(self) -> int: ... @property def timeout(self) -> int: ... - def __eq__(self, __value: object) -> bool: ... + def __eq__(self, value: object, /) -> bool: ... class SSLErrorNumber(enum.IntEnum): SSL_ERROR_EOF: int diff --git a/mypy/typeshed/stdlib/statistics.pyi b/mypy/typeshed/stdlib/statistics.pyi index f3f013fc93e7..c5f5ed64b328 100644 --- a/mypy/typeshed/stdlib/statistics.pyi +++ b/mypy/typeshed/stdlib/statistics.pyi @@ -110,14 +110,14 @@ class NormalDist: if sys.version_info >= (3, 12): def correlation( - __x: Sequence[_Number], __y: Sequence[_Number], *, method: Literal["linear", "ranked"] = "linear" + x: Sequence[_Number], y: Sequence[_Number], /, *, method: Literal["linear", "ranked"] = "linear" ) -> float: ... elif sys.version_info >= (3, 10): - def correlation(__x: Sequence[_Number], __y: Sequence[_Number]) -> float: ... + def correlation(x: Sequence[_Number], y: Sequence[_Number], /) -> float: ... if sys.version_info >= (3, 10): - def covariance(__x: Sequence[_Number], __y: Sequence[_Number]) -> float: ... + def covariance(x: Sequence[_Number], y: Sequence[_Number], /) -> float: ... class LinearRegression(NamedTuple): slope: float @@ -125,8 +125,8 @@ if sys.version_info >= (3, 10): if sys.version_info >= (3, 11): def linear_regression( - __regressor: Sequence[_Number], __dependent_variable: Sequence[_Number], *, proportional: bool = False + regressor: Sequence[_Number], dependent_variable: Sequence[_Number], /, *, proportional: bool = False ) -> LinearRegression: ... elif sys.version_info >= (3, 10): - def linear_regression(__regressor: Sequence[_Number], __dependent_variable: Sequence[_Number]) -> LinearRegression: ... + def linear_regression(regressor: Sequence[_Number], dependent_variable: Sequence[_Number], /) -> LinearRegression: ... diff --git a/mypy/typeshed/stdlib/string.pyi b/mypy/typeshed/stdlib/string.pyi index 8b60243f2333..35a76e9c8628 100644 --- a/mypy/typeshed/stdlib/string.pyi +++ b/mypy/typeshed/stdlib/string.pyi @@ -47,17 +47,17 @@ class Template(metaclass=_TemplateMetaclass): flags: ClassVar[RegexFlag] pattern: ClassVar[Pattern[str]] def __init__(self, template: str) -> None: ... - def substitute(self, __mapping: Mapping[str, object] = {}, **kwds: object) -> str: ... - def safe_substitute(self, __mapping: Mapping[str, object] = {}, **kwds: object) -> str: ... + def substitute(self, mapping: Mapping[str, object] = {}, /, **kwds: object) -> str: ... + def safe_substitute(self, mapping: Mapping[str, object] = {}, /, **kwds: object) -> str: ... if sys.version_info >= (3, 11): def get_identifiers(self) -> list[str]: ... def is_valid(self) -> bool: ... class Formatter: @overload - def format(self, __format_string: LiteralString, *args: LiteralString, **kwargs: LiteralString) -> LiteralString: ... + def format(self, format_string: LiteralString, /, *args: LiteralString, **kwargs: LiteralString) -> LiteralString: ... @overload - def format(self, __format_string: str, *args: Any, **kwargs: Any) -> str: ... + def format(self, format_string: str, /, *args: Any, **kwargs: Any) -> str: ... @overload def vformat( self, format_string: LiteralString, args: Sequence[LiteralString], kwargs: Mapping[LiteralString, LiteralString] diff --git a/mypy/typeshed/stdlib/struct.pyi b/mypy/typeshed/stdlib/struct.pyi index 4220cd825b76..e684632489ea 100644 --- a/mypy/typeshed/stdlib/struct.pyi +++ b/mypy/typeshed/stdlib/struct.pyi @@ -6,12 +6,12 @@ __all__ = ["calcsize", "pack", "pack_into", "unpack", "unpack_from", "iter_unpac class error(Exception): ... -def pack(__fmt: str | bytes, *v: Any) -> bytes: ... -def pack_into(__fmt: str | bytes, __buffer: WriteableBuffer, __offset: int, *v: Any) -> None: ... -def unpack(__format: str | bytes, __buffer: ReadableBuffer) -> tuple[Any, ...]: ... -def unpack_from(__format: str | bytes, buffer: ReadableBuffer, offset: int = 0) -> tuple[Any, ...]: ... -def iter_unpack(__format: str | bytes, __buffer: ReadableBuffer) -> Iterator[tuple[Any, ...]]: ... -def calcsize(__format: str | bytes) -> int: ... +def pack(fmt: str | bytes, /, *v: Any) -> bytes: ... +def pack_into(fmt: str | bytes, buffer: WriteableBuffer, offset: int, /, *v: Any) -> None: ... +def unpack(format: str | bytes, buffer: ReadableBuffer, /) -> tuple[Any, ...]: ... +def unpack_from(format: str | bytes, /, buffer: ReadableBuffer, offset: int = 0) -> tuple[Any, ...]: ... +def iter_unpack(format: str | bytes, buffer: ReadableBuffer, /) -> Iterator[tuple[Any, ...]]: ... +def calcsize(format: str | bytes, /) -> int: ... class Struct: @property @@ -21,6 +21,6 @@ class Struct: def __init__(self, format: str | bytes) -> None: ... def pack(self, *v: Any) -> bytes: ... def pack_into(self, buffer: WriteableBuffer, offset: int, *v: Any) -> None: ... - def unpack(self, __buffer: ReadableBuffer) -> tuple[Any, ...]: ... + def unpack(self, buffer: ReadableBuffer, /) -> tuple[Any, ...]: ... def unpack_from(self, buffer: ReadableBuffer, offset: int = 0) -> tuple[Any, ...]: ... - def iter_unpack(self, __buffer: ReadableBuffer) -> Iterator[tuple[Any, ...]]: ... + def iter_unpack(self, buffer: ReadableBuffer, /) -> Iterator[tuple[Any, ...]]: ... diff --git a/mypy/typeshed/stdlib/sys/__init__.pyi b/mypy/typeshed/stdlib/sys/__init__.pyi index bb1d244bdac9..353e20c4b2e1 100644 --- a/mypy/typeshed/stdlib/sys/__init__.pyi +++ b/mypy/typeshed/stdlib/sys/__init__.pyi @@ -17,9 +17,7 @@ _OptExcInfo: TypeAlias = OptExcInfo # noqa: Y047 # TODO: obsolete, remove fall # Intentionally omits one deprecated and one optional method of `importlib.abc.MetaPathFinder` class _MetaPathFinder(Protocol): - def find_spec( - self, __fullname: str, __path: Sequence[str] | None, __target: ModuleType | None = ... - ) -> ModuleSpec | None: ... + def find_spec(self, fullname: str, path: Sequence[str] | None, target: ModuleType | None = ..., /) -> ModuleSpec | None: ... # ----- sys variables ----- if sys.platform != "win32": @@ -245,19 +243,19 @@ class _version_info(_UninstantiableStructseq, tuple[int, int, int, _ReleaseLevel version_info: _version_info -def call_tracing(__func: Callable[..., _T], __args: Any) -> _T: ... +def call_tracing(func: Callable[..., _T], args: Any, /) -> _T: ... def _clear_type_cache() -> None: ... def _current_frames() -> dict[int, FrameType]: ... -def _getframe(__depth: int = 0) -> FrameType: ... +def _getframe(depth: int = 0, /) -> FrameType: ... def _debugmallocstats() -> None: ... -def __displayhook__(__object: object) -> None: ... -def __excepthook__(__exctype: type[BaseException], __value: BaseException, __traceback: TracebackType | None) -> None: ... +def __displayhook__(object: object, /) -> None: ... +def __excepthook__(exctype: type[BaseException], value: BaseException, traceback: TracebackType | None, /) -> None: ... def exc_info() -> OptExcInfo: ... if sys.version_info >= (3, 11): def exception() -> BaseException | None: ... -def exit(__status: _ExitCode = None) -> NoReturn: ... +def exit(status: _ExitCode = None, /) -> NoReturn: ... def getallocatedblocks() -> int: ... def getdefaultencoding() -> str: ... @@ -266,7 +264,7 @@ if sys.platform != "win32": def getfilesystemencoding() -> str: ... def getfilesystemencodeerrors() -> str: ... -def getrefcount(__object: Any) -> int: ... +def getrefcount(object: Any, /) -> int: ... def getrecursionlimit() -> int: ... def getsizeof(obj: object, default: int = ...) -> int: ... def getswitchinterval() -> float: ... @@ -302,22 +300,22 @@ if sys.platform == "win32": def getwindowsversion() -> _WinVersion: ... -def intern(__string: str) -> str: ... +def intern(string: str, /) -> str: ... def is_finalizing() -> bool: ... def breakpointhook(*args: Any, **kwargs: Any) -> Any: ... __breakpointhook__ = breakpointhook # Contains the original value of breakpointhook if sys.platform != "win32": - def setdlopenflags(__flags: int) -> None: ... + def setdlopenflags(flags: int, /) -> None: ... -def setrecursionlimit(__limit: int) -> None: ... -def setswitchinterval(__interval: float) -> None: ... +def setrecursionlimit(limit: int, /) -> None: ... +def setswitchinterval(interval: float, /) -> None: ... def gettotalrefcount() -> int: ... # Debug builds only if sys.version_info < (3, 9): def getcheckinterval() -> int: ... # deprecated - def setcheckinterval(__n: int) -> None: ... # deprecated + def setcheckinterval(n: int, /) -> None: ... # deprecated if sys.version_info < (3, 9): # An 11-tuple or None @@ -333,9 +331,9 @@ class UnraisableHookArgs(Protocol): unraisablehook: Callable[[UnraisableHookArgs], Any] -def __unraisablehook__(__unraisable: UnraisableHookArgs) -> Any: ... +def __unraisablehook__(unraisable: UnraisableHookArgs, /) -> Any: ... def addaudithook(hook: Callable[[str, tuple[Any, ...]], Any]) -> None: ... -def audit(__event: str, *args: Any) -> None: ... +def audit(event: str, /, *args: Any) -> None: ... _AsyncgenHook: TypeAlias = Callable[[AsyncGenerator[Any, Any]], None] | None @@ -366,9 +364,9 @@ if sys.version_info >= (3, 12): def is_stack_trampoline_active() -> bool: ... # It always exists, but raises on non-linux platforms: if sys.platform == "linux": - def activate_stack_trampoline(__backend: str) -> None: ... + def activate_stack_trampoline(backend: str, /) -> None: ... else: - def activate_stack_trampoline(__backend: str) -> NoReturn: ... + def activate_stack_trampoline(backend: str, /) -> NoReturn: ... from . import _monitoring diff --git a/mypy/typeshed/stdlib/sys/_monitoring.pyi b/mypy/typeshed/stdlib/sys/_monitoring.pyi index 40aeb9cb5bdb..0507eeedc26d 100644 --- a/mypy/typeshed/stdlib/sys/_monitoring.pyi +++ b/mypy/typeshed/stdlib/sys/_monitoring.pyi @@ -14,9 +14,9 @@ COVERAGE_ID: int PROFILER_ID: int OPTIMIZER_ID: int -def use_tool_id(__tool_id: int, __name: str) -> None: ... -def free_tool_id(__tool_id: int) -> None: ... -def get_tool(__tool_id: int) -> str | None: ... +def use_tool_id(tool_id: int, name: str, /) -> None: ... +def free_tool_id(tool_id: int, /) -> None: ... +def get_tool(tool_id: int, /) -> str | None: ... events: _events @@ -40,13 +40,13 @@ class _events: RERAISE: int STOP_ITERATION: int -def get_events(__tool_id: int) -> int: ... -def set_events(__tool_id: int, __event_set: int) -> None: ... -def get_local_events(__tool_id: int, __code: CodeType) -> int: ... -def set_local_events(__tool_id: int, __code: CodeType, __event_set: int) -> int: ... +def get_events(tool_id: int, /) -> int: ... +def set_events(tool_id: int, event_set: int, /) -> None: ... +def get_local_events(tool_id: int, code: CodeType, /) -> int: ... +def set_local_events(tool_id: int, code: CodeType, event_set: int, /) -> int: ... def restart_events() -> None: ... DISABLE: object MISSING: object -def register_callback(__tool_id: int, __event: int, __func: Callable[..., Any] | None) -> Callable[..., Any] | None: ... +def register_callback(tool_id: int, event: int, func: Callable[..., Any] | None, /) -> Callable[..., Any] | None: ... diff --git a/mypy/typeshed/stdlib/syslog.pyi b/mypy/typeshed/stdlib/syslog.pyi index 164334f60a6f..02876e0b7e85 100644 --- a/mypy/typeshed/stdlib/syslog.pyi +++ b/mypy/typeshed/stdlib/syslog.pyi @@ -35,11 +35,11 @@ if sys.platform != "win32": LOG_USER: Literal[8] LOG_UUCP: Literal[64] LOG_WARNING: Literal[4] - def LOG_MASK(__pri: int) -> int: ... - def LOG_UPTO(__pri: int) -> int: ... + def LOG_MASK(pri: int, /) -> int: ... + def LOG_UPTO(pri: int, /) -> int: ... def closelog() -> None: ... def openlog(ident: str = ..., logoption: int = ..., facility: int = ...) -> None: ... - def setlogmask(__maskpri: int) -> int: ... + def setlogmask(maskpri: int, /) -> int: ... @overload def syslog(priority: int, message: str) -> None: ... @overload diff --git a/mypy/typeshed/stdlib/tarfile.pyi b/mypy/typeshed/stdlib/tarfile.pyi index 47c831190286..b6fe454eff78 100644 --- a/mypy/typeshed/stdlib/tarfile.pyi +++ b/mypy/typeshed/stdlib/tarfile.pyi @@ -43,10 +43,10 @@ _FilterFunction: TypeAlias = Callable[[TarInfo, str], TarInfo | None] _TarfileFilter: TypeAlias = Literal["fully_trusted", "tar", "data"] | _FilterFunction class _Fileobj(Protocol): - def read(self, __size: int) -> bytes: ... - def write(self, __b: bytes) -> object: ... + def read(self, size: int, /) -> bytes: ... + def write(self, b: bytes, /) -> object: ... def tell(self) -> int: ... - def seek(self, __pos: int) -> object: ... + def seek(self, pos: int, /) -> object: ... def close(self) -> object: ... # Optional fields: # name: str | bytes diff --git a/mypy/typeshed/stdlib/tempfile.pyi b/mypy/typeshed/stdlib/tempfile.pyi index 2c4b548458ea..ce8f2f1f5929 100644 --- a/mypy/typeshed/stdlib/tempfile.pyi +++ b/mypy/typeshed/stdlib/tempfile.pyi @@ -364,14 +364,14 @@ class SpooledTemporaryFile(IO[AnyStr], _SpooledTemporaryFileBase): if sys.version_info >= (3, 11): # These three work only if the SpooledTemporaryFile is opened in binary mode, # because the underlying object in text mode does not have these methods. - def read1(self, __size: int = ...) -> AnyStr: ... + def read1(self, size: int = ..., /) -> AnyStr: ... def readinto(self, b: WriteableBuffer) -> int: ... def readinto1(self, b: WriteableBuffer) -> int: ... def detach(self) -> io.RawIOBase: ... - def read(self, __n: int = ...) -> AnyStr: ... - def readline(self, __limit: int | None = ...) -> AnyStr: ... # type: ignore[override] - def readlines(self, __hint: int = ...) -> list[AnyStr]: ... # type: ignore[override] + def read(self, n: int = ..., /) -> AnyStr: ... + def readline(self, limit: int | None = ..., /) -> AnyStr: ... # type: ignore[override] + def readlines(self, hint: int = ..., /) -> list[AnyStr]: ... # type: ignore[override] def seek(self, offset: int, whence: int = ...) -> int: ... def tell(self) -> int: ... def truncate(self, size: int | None = None) -> None: ... # type: ignore[override] diff --git a/mypy/typeshed/stdlib/termios.pyi b/mypy/typeshed/stdlib/termios.pyi index 776396cce407..a5378e40fdf2 100644 --- a/mypy/typeshed/stdlib/termios.pyi +++ b/mypy/typeshed/stdlib/termios.pyi @@ -254,14 +254,14 @@ if sys.platform != "win32": XCASE: int XTABS: int - def tcgetattr(__fd: FileDescriptorLike) -> _AttrReturn: ... - def tcsetattr(__fd: FileDescriptorLike, __when: int, __attributes: _Attr) -> None: ... - def tcsendbreak(__fd: FileDescriptorLike, __duration: int) -> None: ... - def tcdrain(__fd: FileDescriptorLike) -> None: ... - def tcflush(__fd: FileDescriptorLike, __queue: int) -> None: ... - def tcflow(__fd: FileDescriptorLike, __action: int) -> None: ... + def tcgetattr(fd: FileDescriptorLike, /) -> _AttrReturn: ... + def tcsetattr(fd: FileDescriptorLike, when: int, attributes: _Attr, /) -> None: ... + def tcsendbreak(fd: FileDescriptorLike, duration: int, /) -> None: ... + def tcdrain(fd: FileDescriptorLike, /) -> None: ... + def tcflush(fd: FileDescriptorLike, queue: int, /) -> None: ... + def tcflow(fd: FileDescriptorLike, action: int, /) -> None: ... if sys.version_info >= (3, 11): - def tcgetwinsize(__fd: FileDescriptorLike) -> tuple[int, int]: ... - def tcsetwinsize(__fd: FileDescriptorLike, __winsize: tuple[int, int]) -> None: ... + def tcgetwinsize(fd: FileDescriptorLike, /) -> tuple[int, int]: ... + def tcsetwinsize(fd: FileDescriptorLike, winsize: tuple[int, int], /) -> None: ... class error(Exception): ... diff --git a/mypy/typeshed/stdlib/tkinter/__init__.pyi b/mypy/typeshed/stdlib/tkinter/__init__.pyi index 3f65eb2c8fe4..80bc56ef53f3 100644 --- a/mypy/typeshed/stdlib/tkinter/__init__.pyi +++ b/mypy/typeshed/stdlib/tkinter/__init__.pyi @@ -618,18 +618,18 @@ class Wm: @overload def wm_attributes(self) -> tuple[Any, ...]: ... @overload - def wm_attributes(self, __option: str): ... + def wm_attributes(self, option: str, /): ... @overload - def wm_attributes(self, __option: str, __value, *__other_option_value_pairs: Any) -> None: ... + def wm_attributes(self, option: str, value, /, *__other_option_value_pairs: Any) -> None: ... attributes = wm_attributes def wm_client(self, name: str | None = None) -> str: ... client = wm_client @overload def wm_colormapwindows(self) -> list[Misc]: ... @overload - def wm_colormapwindows(self, __wlist: list[Misc] | tuple[Misc, ...]) -> None: ... + def wm_colormapwindows(self, wlist: list[Misc] | tuple[Misc, ...], /) -> None: ... @overload - def wm_colormapwindows(self, __first_wlist_item: Misc, *other_wlist_items: Misc) -> None: ... + def wm_colormapwindows(self, first_wlist_item: Misc, /, *other_wlist_items: Misc) -> None: ... colormapwindows = wm_colormapwindows def wm_command(self, value: str | None = None) -> str: ... command = wm_command @@ -767,31 +767,31 @@ class Tk(Misc, Wm): # Tk has __getattr__ so that tk_instance.foo falls back to tk_instance.tk.foo # Please keep in sync with _tkinter.TkappType. # Some methods are intentionally missing because they are inherited from Misc instead. - def adderrorinfo(self, __msg): ... - def call(self, __command: Any, *args: Any) -> Any: ... - def createcommand(self, __name, __func): ... + def adderrorinfo(self, msg, /): ... + def call(self, command: Any, /, *args: Any) -> Any: ... + def createcommand(self, name, func, /): ... if sys.platform != "win32": - def createfilehandler(self, __file, __mask, __func): ... - def deletefilehandler(self, __file): ... - - def createtimerhandler(self, __milliseconds, __func): ... - def dooneevent(self, __flags: int = ...): ... - def eval(self, __script: str) -> str: ... - def evalfile(self, __fileName): ... - def exprboolean(self, __s): ... - def exprdouble(self, __s): ... - def exprlong(self, __s): ... - def exprstring(self, __s): ... + def createfilehandler(self, file, mask, func, /): ... + def deletefilehandler(self, file, /): ... + + def createtimerhandler(self, milliseconds, func, /): ... + def dooneevent(self, flags: int = ..., /): ... + def eval(self, script: str, /) -> str: ... + def evalfile(self, fileName, /): ... + def exprboolean(self, s, /): ... + def exprdouble(self, s, /): ... + def exprlong(self, s, /): ... + def exprstring(self, s, /): ... def globalgetvar(self, *args, **kwargs): ... def globalsetvar(self, *args, **kwargs): ... def globalunsetvar(self, *args, **kwargs): ... def interpaddr(self): ... def loadtk(self) -> None: ... - def record(self, __script): ... + def record(self, script, /): ... if sys.version_info < (3, 11): - def split(self, __arg): ... + def split(self, arg, /): ... - def splitlist(self, __arg): ... + def splitlist(self, arg, /): ... def unsetvar(self, *args, **kwargs): ... def wantobjects(self, *args, **kwargs): ... def willdispatch(self): ... @@ -1214,11 +1214,11 @@ class Canvas(Widget, XView, YView): def canvasx(self, screenx, gridspacing: Incomplete | None = None): ... def canvasy(self, screeny, gridspacing: Incomplete | None = None): ... @overload - def coords(self, __tagOrId: str | int) -> list[float]: ... + def coords(self, tagOrId: str | int, /) -> list[float]: ... @overload - def coords(self, __tagOrId: str | int, __args: list[int] | list[float] | tuple[float, ...]) -> None: ... + def coords(self, tagOrId: str | int, args: list[int] | list[float] | tuple[float, ...], /) -> None: ... @overload - def coords(self, __tagOrId: str | int, __x1: float, __y1: float, *args: float) -> None: ... + def coords(self, tagOrId: str | int, x1: float, y1: float, /, *args: float) -> None: ... # create_foo() methods accept coords as a list or tuple, or as separate arguments. # Lists and tuples can be flat as in [1, 2, 3, 4], or nested as in [(1, 2), (3, 4)]. # Keyword arguments should be the same in all overloads of each method. @@ -1228,10 +1228,11 @@ class Canvas(Widget, XView, YView): @overload def create_line( self, - __x0: float, - __y0: float, - __x1: float, - __y1: float, + x0: float, + y0: float, + x1: float, + y1: float, + /, *, activedash: str | int | list[int] | tuple[int, ...] = ..., activefill: str = ..., @@ -1259,8 +1260,9 @@ class Canvas(Widget, XView, YView): @overload def create_line( self, - __xy_pair_0: tuple[float, float], - __xy_pair_1: tuple[float, float], + xy_pair_0: tuple[float, float], + xy_pair_1: tuple[float, float], + /, *, activedash: str | int | list[int] | tuple[int, ...] = ..., activefill: str = ..., @@ -1288,7 +1290,7 @@ class Canvas(Widget, XView, YView): @overload def create_line( self, - __coords: ( + coords: ( tuple[float, float, float, float] | tuple[tuple[float, float], tuple[float, float]] | list[int] @@ -1296,6 +1298,7 @@ class Canvas(Widget, XView, YView): | list[tuple[int, int]] | list[tuple[float, float]] ), + /, *, activedash: str | int | list[int] | tuple[int, ...] = ..., activefill: str = ..., @@ -1323,10 +1326,11 @@ class Canvas(Widget, XView, YView): @overload def create_oval( self, - __x0: float, - __y0: float, - __x1: float, - __y1: float, + x0: float, + y0: float, + x1: float, + y1: float, + /, *, activedash: str | int | list[int] | tuple[int, ...] = ..., activefill: str = ..., @@ -1355,8 +1359,9 @@ class Canvas(Widget, XView, YView): @overload def create_oval( self, - __xy_pair_0: tuple[float, float], - __xy_pair_1: tuple[float, float], + xy_pair_0: tuple[float, float], + xy_pair_1: tuple[float, float], + /, *, activedash: str | int | list[int] | tuple[int, ...] = ..., activefill: str = ..., @@ -1385,7 +1390,7 @@ class Canvas(Widget, XView, YView): @overload def create_oval( self, - __coords: ( + coords: ( tuple[float, float, float, float] | tuple[tuple[float, float], tuple[float, float]] | list[int] @@ -1393,6 +1398,7 @@ class Canvas(Widget, XView, YView): | list[tuple[int, int]] | list[tuple[float, float]] ), + /, *, activedash: str | int | list[int] | tuple[int, ...] = ..., activefill: str = ..., @@ -1421,10 +1427,11 @@ class Canvas(Widget, XView, YView): @overload def create_polygon( self, - __x0: float, - __y0: float, - __x1: float, - __y1: float, + x0: float, + y0: float, + x1: float, + y1: float, + /, *xy_pairs: float, activedash: str | int | list[int] | tuple[int, ...] = ..., activefill: str = ..., @@ -1456,8 +1463,9 @@ class Canvas(Widget, XView, YView): @overload def create_polygon( self, - __xy_pair_0: tuple[float, float], - __xy_pair_1: tuple[float, float], + xy_pair_0: tuple[float, float], + xy_pair_1: tuple[float, float], + /, *xy_pairs: tuple[float, float], activedash: str | int | list[int] | tuple[int, ...] = ..., activefill: str = ..., @@ -1489,7 +1497,7 @@ class Canvas(Widget, XView, YView): @overload def create_polygon( self, - __coords: ( + coords: ( tuple[float, ...] | tuple[tuple[float, float], ...] | list[int] @@ -1497,6 +1505,7 @@ class Canvas(Widget, XView, YView): | list[tuple[int, int]] | list[tuple[float, float]] ), + /, *, activedash: str | int | list[int] | tuple[int, ...] = ..., activefill: str = ..., @@ -1528,10 +1537,11 @@ class Canvas(Widget, XView, YView): @overload def create_rectangle( self, - __x0: float, - __y0: float, - __x1: float, - __y1: float, + x0: float, + y0: float, + x1: float, + y1: float, + /, *, activedash: str | int | list[int] | tuple[int, ...] = ..., activefill: str = ..., @@ -1560,8 +1570,9 @@ class Canvas(Widget, XView, YView): @overload def create_rectangle( self, - __xy_pair_0: tuple[float, float], - __xy_pair_1: tuple[float, float], + xy_pair_0: tuple[float, float], + xy_pair_1: tuple[float, float], + /, *, activedash: str | int | list[int] | tuple[int, ...] = ..., activefill: str = ..., @@ -1590,7 +1601,7 @@ class Canvas(Widget, XView, YView): @overload def create_rectangle( self, - __coords: ( + coords: ( tuple[float, float, float, float] | tuple[tuple[float, float], tuple[float, float]] | list[int] @@ -1598,6 +1609,7 @@ class Canvas(Widget, XView, YView): | list[tuple[int, int]] | list[tuple[float, float]] ), + /, *, activedash: str | int | list[int] | tuple[int, ...] = ..., activefill: str = ..., @@ -1626,8 +1638,9 @@ class Canvas(Widget, XView, YView): @overload def create_text( self, - __x: float, - __y: float, + x: float, + y: float, + /, *, activefill: str = ..., activestipple: str = ..., @@ -1648,7 +1661,8 @@ class Canvas(Widget, XView, YView): @overload def create_text( self, - __coords: tuple[float, float] | list[int] | list[float], + coords: tuple[float, float] | list[int] | list[float], + /, *, activefill: str = ..., activestipple: str = ..., @@ -1669,8 +1683,9 @@ class Canvas(Widget, XView, YView): @overload def create_window( self, - __x: float, - __y: float, + x: float, + y: float, + /, *, anchor: _Anchor = ..., height: _ScreenUnits = ..., @@ -1682,7 +1697,8 @@ class Canvas(Widget, XView, YView): @overload def create_window( self, - __coords: tuple[float, float] | list[int] | list[float], + coords: tuple[float, float] | list[int] | list[float], + /, *, anchor: _Anchor = ..., height: _ScreenUnits = ..., @@ -1694,11 +1710,11 @@ class Canvas(Widget, XView, YView): def dchars(self, *args) -> None: ... def delete(self, *tagsOrCanvasIds: str | int) -> None: ... @overload - def dtag(self, __tag: str, __tag_to_delete: str | None = ...) -> None: ... + def dtag(self, tag: str, tag_to_delete: str | None = ..., /) -> None: ... @overload - def dtag(self, __id: int, __tag_to_delete: str) -> None: ... + def dtag(self, id: int, tag_to_delete: str, /) -> None: ... def focus(self, *args): ... - def gettags(self, __tagOrId: str | int) -> tuple[str, ...]: ... + def gettags(self, tagOrId: str | int, /) -> tuple[str, ...]: ... def icursor(self, *args) -> None: ... def index(self, *args): ... def insert(self, *args) -> None: ... @@ -1716,13 +1732,13 @@ class Canvas(Widget, XView, YView): # lift = tkraise = tag_raise # # But mypy doesn't like aliasing here (maybe because Misc defines the same names) - def tag_lower(self, __first: str | int, __second: str | int | None = ...) -> None: ... - def lower(self, __first: str | int, __second: str | int | None = ...) -> None: ... # type: ignore[override] - def tag_raise(self, __first: str | int, __second: str | int | None = ...) -> None: ... - def tkraise(self, __first: str | int, __second: str | int | None = ...) -> None: ... # type: ignore[override] - def lift(self, __first: str | int, __second: str | int | None = ...) -> None: ... # type: ignore[override] + def tag_lower(self, first: str | int, second: str | int | None = ..., /) -> None: ... + def lower(self, first: str | int, second: str | int | None = ..., /) -> None: ... # type: ignore[override] + def tag_raise(self, first: str | int, second: str | int | None = ..., /) -> None: ... + def tkraise(self, first: str | int, second: str | int | None = ..., /) -> None: ... # type: ignore[override] + def lift(self, first: str | int, second: str | int | None = ..., /) -> None: ... # type: ignore[override] def scale( - self, __tagOrId: str | int, __xOrigin: _ScreenUnits, __yOrigin: _ScreenUnits, __xScale: float, __yScale: float + self, tagOrId: str | int, xOrigin: _ScreenUnits, yOrigin: _ScreenUnits, xScale: float, yScale: float, / ) -> None: ... def scan_mark(self, x, y) -> None: ... def scan_dragto(self, x, y, gain: int = 10) -> None: ... @@ -3182,7 +3198,7 @@ class Text(Widget, XView, YView): @overload def tag_configure(self, tagName: str, cnf: str) -> tuple[str, str, str, Any, Any]: ... tag_config = tag_configure - def tag_delete(self, __first_tag_name: str, *tagNames: str) -> None: ... # error if no tag names given + def tag_delete(self, first_tag_name: str, /, *tagNames: str) -> None: ... # error if no tag names given def tag_lower(self, tagName: str, belowThis: str | None = None) -> None: ... def tag_names(self, index: _TextIndex | None = None) -> tuple[str, ...]: ... def tag_nextrange( diff --git a/mypy/typeshed/stdlib/tkinter/dnd.pyi b/mypy/typeshed/stdlib/tkinter/dnd.pyi index 5a83bb56679f..d806be74068e 100644 --- a/mypy/typeshed/stdlib/tkinter/dnd.pyi +++ b/mypy/typeshed/stdlib/tkinter/dnd.pyi @@ -6,7 +6,7 @@ if sys.version_info >= (3, 9): __all__ = ["dnd_start", "DndHandler"] class _DndSource(Protocol): - def dnd_end(self, __target: Widget | None, __event: Event[Misc] | None) -> None: ... + def dnd_end(self, target: Widget | None, event: Event[Misc] | None, /) -> None: ... class DndHandler: root: ClassVar[Tk | None] diff --git a/mypy/typeshed/stdlib/tkinter/font.pyi b/mypy/typeshed/stdlib/tkinter/font.pyi index 448e2b0054a5..46625014d4ac 100644 --- a/mypy/typeshed/stdlib/tkinter/font.pyi +++ b/mypy/typeshed/stdlib/tkinter/font.pyi @@ -97,9 +97,9 @@ class Font: configure = config def copy(self) -> Font: ... @overload - def metrics(self, __option: Literal["ascent", "descent", "linespace"], *, displayof: tkinter.Misc | None = ...) -> int: ... + def metrics(self, option: Literal["ascent", "descent", "linespace"], /, *, displayof: tkinter.Misc | None = ...) -> int: ... @overload - def metrics(self, __option: Literal["fixed"], *, displayof: tkinter.Misc | None = ...) -> bool: ... + def metrics(self, option: Literal["fixed"], /, *, displayof: tkinter.Misc | None = ...) -> bool: ... @overload def metrics(self, *, displayof: tkinter.Misc | None = ...) -> _MetricsDict: ... def measure(self, text: str, displayof: tkinter.Misc | None = None) -> int: ... diff --git a/mypy/typeshed/stdlib/tkinter/ttk.pyi b/mypy/typeshed/stdlib/tkinter/ttk.pyi index f1b132b33657..86a23ce82211 100644 --- a/mypy/typeshed/stdlib/tkinter/ttk.pyi +++ b/mypy/typeshed/stdlib/tkinter/ttk.pyi @@ -1105,19 +1105,19 @@ class Treeview(Widget, tkinter.XView, tkinter.YView): def see(self, item: str | int) -> None: ... def selection(self) -> tuple[str, ...]: ... @overload - def selection_set(self, __items: list[str] | tuple[str, ...] | list[int] | tuple[int, ...]) -> None: ... + def selection_set(self, items: list[str] | tuple[str, ...] | list[int] | tuple[int, ...], /) -> None: ... @overload def selection_set(self, *items: str | int) -> None: ... @overload - def selection_add(self, __items: list[str] | tuple[str, ...] | list[int] | tuple[int, ...]) -> None: ... + def selection_add(self, items: list[str] | tuple[str, ...] | list[int] | tuple[int, ...], /) -> None: ... @overload def selection_add(self, *items: str | int) -> None: ... @overload - def selection_remove(self, __items: list[str] | tuple[str, ...] | list[int] | tuple[int, ...]) -> None: ... + def selection_remove(self, items: list[str] | tuple[str, ...] | list[int] | tuple[int, ...], /) -> None: ... @overload def selection_remove(self, *items: str | int) -> None: ... @overload - def selection_toggle(self, __items: list[str] | tuple[str, ...] | list[int] | tuple[int, ...]) -> None: ... + def selection_toggle(self, items: list[str] | tuple[str, ...] | list[int] | tuple[int, ...], /) -> None: ... @overload def selection_toggle(self, *items: str | int) -> None: ... @overload diff --git a/mypy/typeshed/stdlib/tomllib.pyi b/mypy/typeshed/stdlib/tomllib.pyi index 3a6ce93f87e1..d559568b912b 100644 --- a/mypy/typeshed/stdlib/tomllib.pyi +++ b/mypy/typeshed/stdlib/tomllib.pyi @@ -6,5 +6,5 @@ __all__ = ("loads", "load", "TOMLDecodeError") class TOMLDecodeError(ValueError): ... -def load(__fp: SupportsRead[bytes], *, parse_float: Callable[[str], Any] = ...) -> dict[str, Any]: ... -def loads(__s: str, *, parse_float: Callable[[str], Any] = ...) -> dict[str, Any]: ... +def load(fp: SupportsRead[bytes], /, *, parse_float: Callable[[str], Any] = ...) -> dict[str, Any]: ... +def loads(s: str, /, *, parse_float: Callable[[str], Any] = ...) -> dict[str, Any]: ... diff --git a/mypy/typeshed/stdlib/trace.pyi b/mypy/typeshed/stdlib/trace.pyi index 14a921c5e6cc..d32647a55cb5 100644 --- a/mypy/typeshed/stdlib/trace.pyi +++ b/mypy/typeshed/stdlib/trace.pyi @@ -65,7 +65,7 @@ class Trace: self, cmd: str | types.CodeType, globals: Mapping[str, Any] | None = None, locals: Mapping[str, Any] | None = None ) -> None: ... if sys.version_info >= (3, 9): - def runfunc(self, __func: Callable[_P, _T], *args: _P.args, **kw: _P.kwargs) -> _T: ... + def runfunc(self, func: Callable[_P, _T], /, *args: _P.args, **kw: _P.kwargs) -> _T: ... else: def runfunc(self, func: Callable[_P, _T], *args: _P.args, **kw: _P.kwargs) -> _T: ... diff --git a/mypy/typeshed/stdlib/traceback.pyi b/mypy/typeshed/stdlib/traceback.pyi index f6720155936f..928858f81d1c 100644 --- a/mypy/typeshed/stdlib/traceback.pyi +++ b/mypy/typeshed/stdlib/traceback.pyi @@ -34,7 +34,8 @@ def print_tb(tb: TracebackType | None, limit: int | None = None, file: SupportsW if sys.version_info >= (3, 10): @overload def print_exception( - __exc: type[BaseException] | None, + exc: type[BaseException] | None, + /, value: BaseException | None = ..., tb: TracebackType | None = ..., limit: int | None = None, @@ -43,18 +44,19 @@ if sys.version_info >= (3, 10): ) -> None: ... @overload def print_exception( - __exc: BaseException, *, limit: int | None = None, file: SupportsWrite[str] | None = None, chain: bool = True + exc: BaseException, /, *, limit: int | None = None, file: SupportsWrite[str] | None = None, chain: bool = True ) -> None: ... @overload def format_exception( - __exc: type[BaseException] | None, + exc: type[BaseException] | None, + /, value: BaseException | None = ..., tb: TracebackType | None = ..., limit: int | None = None, chain: bool = True, ) -> list[str]: ... @overload - def format_exception(__exc: BaseException, *, limit: int | None = None, chain: bool = True) -> list[str]: ... + def format_exception(exc: BaseException, /, *, limit: int | None = None, chain: bool = True) -> list[str]: ... else: def print_exception( @@ -85,9 +87,9 @@ def print_list(extracted_list: list[FrameSummary], file: SupportsWrite[str] | No if sys.version_info >= (3, 10): @overload - def format_exception_only(__exc: BaseException | None) -> list[str]: ... + def format_exception_only(exc: BaseException | None, /) -> list[str]: ... @overload - def format_exception_only(__exc: Unused, value: BaseException | None) -> list[str]: ... + def format_exception_only(exc: Unused, /, value: BaseException | None) -> list[str]: ... else: def format_exception_only(etype: type[BaseException] | None, value: BaseException | None) -> list[str]: ... diff --git a/mypy/typeshed/stdlib/types.pyi b/mypy/typeshed/stdlib/types.pyi index 05c5e85e4a9e..f2d79b7f3ade 100644 --- a/mypy/typeshed/stdlib/types.pyi +++ b/mypy/typeshed/stdlib/types.pyi @@ -66,8 +66,8 @@ _VT_co = TypeVar("_VT_co", covariant=True) @final class _Cell: - def __new__(cls, __contents: object = ...) -> Self: ... - def __eq__(self, __value: object) -> bool: ... + def __new__(cls, contents: object = ..., /) -> Self: ... + def __eq__(self, value: object, /) -> bool: ... __hash__: ClassVar[None] # type: ignore[assignment] cell_contents: Any @@ -102,15 +102,15 @@ class FunctionType: ) -> Self: ... def __call__(self, *args: Any, **kwargs: Any) -> Any: ... @overload - def __get__(self, __instance: None, __owner: type) -> FunctionType: ... + def __get__(self, instance: None, owner: type, /) -> FunctionType: ... @overload - def __get__(self, __instance: object, __owner: type | None = None) -> MethodType: ... + def __get__(self, instance: object, owner: type | None = None, /) -> MethodType: ... LambdaType = FunctionType @final class CodeType: - def __eq__(self, __value: object) -> bool: ... + def __eq__(self, value: object, /) -> bool: ... def __hash__(self) -> int: ... @property def co_argcount(self) -> int: ... @@ -164,64 +164,67 @@ class CodeType: if sys.version_info >= (3, 11): def __new__( cls, - __argcount: int, - __posonlyargcount: int, - __kwonlyargcount: int, - __nlocals: int, - __stacksize: int, - __flags: int, - __codestring: bytes, - __constants: tuple[object, ...], - __names: tuple[str, ...], - __varnames: tuple[str, ...], - __filename: str, - __name: str, - __qualname: str, - __firstlineno: int, - __linetable: bytes, - __exceptiontable: bytes, - __freevars: tuple[str, ...] = ..., - __cellvars: tuple[str, ...] = ..., + argcount: int, + posonlyargcount: int, + kwonlyargcount: int, + nlocals: int, + stacksize: int, + flags: int, + codestring: bytes, + constants: tuple[object, ...], + names: tuple[str, ...], + varnames: tuple[str, ...], + filename: str, + name: str, + qualname: str, + firstlineno: int, + linetable: bytes, + exceptiontable: bytes, + freevars: tuple[str, ...] = ..., + cellvars: tuple[str, ...] = ..., + /, ) -> Self: ... elif sys.version_info >= (3, 10): def __new__( cls, - __argcount: int, - __posonlyargcount: int, - __kwonlyargcount: int, - __nlocals: int, - __stacksize: int, - __flags: int, - __codestring: bytes, - __constants: tuple[object, ...], - __names: tuple[str, ...], - __varnames: tuple[str, ...], - __filename: str, - __name: str, - __firstlineno: int, - __linetable: bytes, - __freevars: tuple[str, ...] = ..., - __cellvars: tuple[str, ...] = ..., + argcount: int, + posonlyargcount: int, + kwonlyargcount: int, + nlocals: int, + stacksize: int, + flags: int, + codestring: bytes, + constants: tuple[object, ...], + names: tuple[str, ...], + varnames: tuple[str, ...], + filename: str, + name: str, + firstlineno: int, + linetable: bytes, + freevars: tuple[str, ...] = ..., + cellvars: tuple[str, ...] = ..., + /, ) -> Self: ... else: def __new__( cls, - __argcount: int, - __posonlyargcount: int, - __kwonlyargcount: int, - __nlocals: int, - __stacksize: int, - __flags: int, - __codestring: bytes, - __constants: tuple[object, ...], - __names: tuple[str, ...], - __varnames: tuple[str, ...], - __filename: str, - __name: str, - __firstlineno: int, - __lnotab: bytes, - __freevars: tuple[str, ...] = ..., - __cellvars: tuple[str, ...] = ..., + argcount: int, + posonlyargcount: int, + kwonlyargcount: int, + nlocals: int, + stacksize: int, + flags: int, + codestring: bytes, + constants: tuple[object, ...], + names: tuple[str, ...], + varnames: tuple[str, ...], + filename: str, + name: str, + firstlineno: int, + lnotab: bytes, + freevars: tuple[str, ...] = ..., + cellvars: tuple[str, ...] = ..., + /, ) -> Self: ... if sys.version_info >= (3, 11): def replace( @@ -293,10 +296,10 @@ class CodeType: class MappingProxyType(Mapping[_KT, _VT_co]): __hash__: ClassVar[None] # type: ignore[assignment] def __new__(cls, mapping: SupportsKeysAndGetItem[_KT, _VT_co]) -> Self: ... - def __getitem__(self, __key: _KT) -> _VT_co: ... + def __getitem__(self, key: _KT, /) -> _VT_co: ... def __iter__(self) -> Iterator[_KT]: ... def __len__(self) -> int: ... - def __eq__(self, __value: object) -> bool: ... + def __eq__(self, value: object, /) -> bool: ... def copy(self) -> dict[_KT, _VT_co]: ... def keys(self) -> KeysView[_KT]: ... def values(self) -> ValuesView[_VT_co]: ... @@ -304,19 +307,19 @@ class MappingProxyType(Mapping[_KT, _VT_co]): if sys.version_info >= (3, 9): def __class_getitem__(cls, item: Any) -> GenericAlias: ... def __reversed__(self) -> Iterator[_KT]: ... - def __or__(self, __value: Mapping[_T1, _T2]) -> dict[_KT | _T1, _VT_co | _T2]: ... - def __ror__(self, __value: Mapping[_T1, _T2]) -> dict[_KT | _T1, _VT_co | _T2]: ... + def __or__(self, value: Mapping[_T1, _T2], /) -> dict[_KT | _T1, _VT_co | _T2]: ... + def __ror__(self, value: Mapping[_T1, _T2], /) -> dict[_KT | _T1, _VT_co | _T2]: ... class SimpleNamespace: __hash__: ClassVar[None] # type: ignore[assignment] def __init__(self, **kwargs: Any) -> None: ... - def __eq__(self, __value: object) -> bool: ... - def __getattribute__(self, __name: str) -> Any: ... - def __setattr__(self, __name: str, __value: Any) -> None: ... - def __delattr__(self, __name: str) -> None: ... + def __eq__(self, value: object, /) -> bool: ... + def __getattribute__(self, name: str, /) -> Any: ... + def __setattr__(self, name: str, value: Any, /) -> None: ... + def __delattr__(self, name: str, /) -> None: ... class _LoaderProtocol(Protocol): - def load_module(self, __fullname: str) -> ModuleType: ... + def load_module(self, fullname: str, /) -> ModuleType: ... class ModuleType: __name__: str @@ -348,13 +351,13 @@ class GeneratorType(Generator[_YieldT_co, _SendT_contra, _ReturnT_co]): __qualname__: str def __iter__(self) -> Self: ... def __next__(self) -> _YieldT_co: ... - def send(self, __arg: _SendT_contra) -> _YieldT_co: ... + def send(self, arg: _SendT_contra, /) -> _YieldT_co: ... @overload def throw( - self, __typ: type[BaseException], __val: BaseException | object = ..., __tb: TracebackType | None = ... + self, typ: type[BaseException], val: BaseException | object = ..., tb: TracebackType | None = ..., / ) -> _YieldT_co: ... @overload - def throw(self, __typ: BaseException, __val: None = None, __tb: TracebackType | None = ...) -> _YieldT_co: ... + def throw(self, typ: BaseException, val: None = None, tb: TracebackType | None = ..., /) -> _YieldT_co: ... @final class AsyncGeneratorType(AsyncGenerator[_YieldT_co, _SendT_contra]): @@ -368,16 +371,16 @@ class AsyncGeneratorType(AsyncGenerator[_YieldT_co, _SendT_contra]): def __aiter__(self) -> Self: ... def __anext__(self) -> Coroutine[Any, Any, _YieldT_co]: ... - def asend(self, __val: _SendT_contra) -> Coroutine[Any, Any, _YieldT_co]: ... + def asend(self, val: _SendT_contra, /) -> Coroutine[Any, Any, _YieldT_co]: ... @overload async def athrow( - self, __typ: type[BaseException], __val: BaseException | object = ..., __tb: TracebackType | None = ... + self, typ: type[BaseException], val: BaseException | object = ..., tb: TracebackType | None = ..., / ) -> _YieldT_co: ... @overload - async def athrow(self, __typ: BaseException, __val: None = None, __tb: TracebackType | None = ...) -> _YieldT_co: ... + async def athrow(self, typ: BaseException, val: None = None, tb: TracebackType | None = ..., /) -> _YieldT_co: ... def aclose(self) -> Coroutine[Any, Any, None]: ... if sys.version_info >= (3, 9): - def __class_getitem__(cls, __item: Any) -> GenericAlias: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... @final class CoroutineType(Coroutine[_YieldT_co, _SendT_contra, _ReturnT_co]): @@ -391,13 +394,13 @@ class CoroutineType(Coroutine[_YieldT_co, _SendT_contra, _ReturnT_co]): def close(self) -> None: ... def __await__(self) -> Generator[Any, None, _ReturnT_co]: ... - def send(self, __arg: _SendT_contra) -> _YieldT_co: ... + def send(self, arg: _SendT_contra, /) -> _YieldT_co: ... @overload def throw( - self, __typ: type[BaseException], __val: BaseException | object = ..., __tb: TracebackType | None = ... + self, typ: type[BaseException], val: BaseException | object = ..., tb: TracebackType | None = ..., / ) -> _YieldT_co: ... @overload - def throw(self, __typ: BaseException, __val: None = None, __tb: TracebackType | None = ...) -> _YieldT_co: ... + def throw(self, typ: BaseException, val: None = None, tb: TracebackType | None = ..., /) -> _YieldT_co: ... @final class MethodType: @@ -413,9 +416,9 @@ class MethodType: def __name__(self) -> str: ... # inherited from the added function @property def __qualname__(self) -> str: ... # inherited from the added function - def __new__(cls, __func: Callable[..., Any], __obj: object) -> Self: ... + def __new__(cls, func: Callable[..., Any], obj: object, /) -> Self: ... def __call__(self, *args: Any, **kwargs: Any) -> Any: ... - def __eq__(self, __value: object) -> bool: ... + def __eq__(self, value: object, /) -> bool: ... def __hash__(self) -> int: ... @final @@ -427,7 +430,7 @@ class BuiltinFunctionType: @property def __qualname__(self) -> str: ... def __call__(self, *args: Any, **kwargs: Any) -> Any: ... - def __eq__(self, __value: object) -> bool: ... + def __eq__(self, value: object, /) -> bool: ... def __hash__(self) -> int: ... BuiltinMethodType = BuiltinFunctionType @@ -441,7 +444,7 @@ class WrapperDescriptorType: @property def __objclass__(self) -> type: ... def __call__(self, *args: Any, **kwargs: Any) -> Any: ... - def __get__(self, __instance: Any, __owner: type | None = None) -> Any: ... + def __get__(self, instance: Any, owner: type | None = None, /) -> Any: ... @final class MethodWrapperType: @@ -454,8 +457,8 @@ class MethodWrapperType: @property def __objclass__(self) -> type: ... def __call__(self, *args: Any, **kwargs: Any) -> Any: ... - def __eq__(self, __value: object) -> bool: ... - def __ne__(self, __value: object) -> bool: ... + def __eq__(self, value: object, /) -> bool: ... + def __ne__(self, value: object, /) -> bool: ... def __hash__(self) -> int: ... @final @@ -467,7 +470,7 @@ class MethodDescriptorType: @property def __objclass__(self) -> type: ... def __call__(self, *args: Any, **kwargs: Any) -> Any: ... - def __get__(self, __instance: Any, __owner: type | None = None) -> Any: ... + def __get__(self, instance: Any, owner: type | None = None, /) -> Any: ... @final class ClassMethodDescriptorType: @@ -478,7 +481,7 @@ class ClassMethodDescriptorType: @property def __objclass__(self) -> type: ... def __call__(self, *args: Any, **kwargs: Any) -> Any: ... - def __get__(self, __instance: Any, __owner: type | None = None) -> Any: ... + def __get__(self, instance: Any, owner: type | None = None, /) -> Any: ... @final class TracebackType: @@ -524,9 +527,9 @@ class GetSetDescriptorType: def __qualname__(self) -> str: ... @property def __objclass__(self) -> type: ... - def __get__(self, __instance: Any, __owner: type | None = None) -> Any: ... - def __set__(self, __instance: Any, __value: Any) -> None: ... - def __delete__(self, __instance: Any) -> None: ... + def __get__(self, instance: Any, owner: type | None = None, /) -> Any: ... + def __set__(self, instance: Any, value: Any, /) -> None: ... + def __delete__(self, instance: Any, /) -> None: ... @final class MemberDescriptorType: @@ -536,9 +539,9 @@ class MemberDescriptorType: def __qualname__(self) -> str: ... @property def __objclass__(self) -> type: ... - def __get__(self, __instance: Any, __owner: type | None = None) -> Any: ... - def __set__(self, __instance: Any, __value: Any) -> None: ... - def __delete__(self, __instance: Any) -> None: ... + def __get__(self, instance: Any, owner: type | None = None, /) -> Any: ... + def __set__(self, instance: Any, value: Any, /) -> None: ... + def __delete__(self, instance: Any, /) -> None: ... def new_class( name: str, @@ -552,7 +555,7 @@ def prepare_class( ) -> tuple[type, dict[str, Any], dict[str, Any]]: ... if sys.version_info >= (3, 12): - def get_original_bases(__cls: type) -> tuple[Any, ...]: ... + def get_original_bases(cls: type, /) -> tuple[Any, ...]: ... # Actually a different type, but `property` is special and we want that too. DynamicClassAttribute = property @@ -578,8 +581,8 @@ if sys.version_info >= (3, 9): @property def __parameters__(self) -> tuple[Any, ...]: ... def __new__(cls, origin: type, args: Any) -> Self: ... - def __getitem__(self, __typeargs: Any) -> GenericAlias: ... - def __eq__(self, __value: object) -> bool: ... + def __getitem__(self, typeargs: Any, /) -> GenericAlias: ... + def __eq__(self, value: object, /) -> bool: ... def __hash__(self) -> int: ... if sys.version_info >= (3, 11): @property @@ -605,7 +608,7 @@ if sys.version_info >= (3, 10): class UnionType: @property def __args__(self) -> tuple[Any, ...]: ... - def __or__(self, __value: Any) -> UnionType: ... - def __ror__(self, __value: Any) -> UnionType: ... - def __eq__(self, __value: object) -> bool: ... + def __or__(self, value: Any, /) -> UnionType: ... + def __ror__(self, value: Any, /) -> UnionType: ... + def __eq__(self, value: object, /) -> bool: ... def __hash__(self) -> int: ... diff --git a/mypy/typeshed/stdlib/typing.pyi b/mypy/typeshed/stdlib/typing.pyi index 5d01be539016..be0c29c89f8d 100644 --- a/mypy/typeshed/stdlib/typing.pyi +++ b/mypy/typeshed/stdlib/typing.pyi @@ -1,3 +1,5 @@ +# Since this module defines "overload" it is not recognized by Ruff as typing.overload +# ruff: noqa: F811 # TODO: The collections import is required, otherwise mypy crashes. # https://github.com/python/mypy/issues/16744 import collections # noqa: F401 # pyright: ignore @@ -282,7 +284,7 @@ if sys.version_info >= (3, 10): def __init__(self, name: str, tp: Any) -> None: ... if sys.version_info >= (3, 11): @staticmethod - def __call__(__x: _T) -> _T: ... + def __call__(x: _T, /) -> _T: ... else: def __call__(self, x: _T) -> _T: ... @@ -372,7 +374,7 @@ class SupportsRound(Protocol[_T_co]): def __round__(self) -> int: ... @overload @abstractmethod - def __round__(self, __ndigits: int) -> _T_co: ... + def __round__(self, ndigits: int, /) -> _T_co: ... @runtime_checkable class Sized(Protocol, metaclass=ABCMeta): @@ -410,15 +412,15 @@ _ReturnT_co = TypeVar("_ReturnT_co", covariant=True) class Generator(Iterator[_YieldT_co], Generic[_YieldT_co, _SendT_contra, _ReturnT_co]): def __next__(self) -> _YieldT_co: ... @abstractmethod - def send(self, __value: _SendT_contra) -> _YieldT_co: ... + def send(self, value: _SendT_contra, /) -> _YieldT_co: ... @overload @abstractmethod def throw( - self, __typ: type[BaseException], __val: BaseException | object = None, __tb: TracebackType | None = None + self, typ: type[BaseException], val: BaseException | object = None, tb: TracebackType | None = None, / ) -> _YieldT_co: ... @overload @abstractmethod - def throw(self, __typ: BaseException, __val: None = None, __tb: TracebackType | None = None) -> _YieldT_co: ... + def throw(self, typ: BaseException, val: None = None, tb: TracebackType | None = None, /) -> _YieldT_co: ... def close(self) -> None: ... def __iter__(self) -> Generator[_YieldT_co, _SendT_contra, _ReturnT_co]: ... @property @@ -447,15 +449,15 @@ class Coroutine(Awaitable[_ReturnT_co], Generic[_YieldT_co, _SendT_contra, _Retu @property def cr_running(self) -> bool: ... @abstractmethod - def send(self, __value: _SendT_contra) -> _YieldT_co: ... + def send(self, value: _SendT_contra, /) -> _YieldT_co: ... @overload @abstractmethod def throw( - self, __typ: type[BaseException], __val: BaseException | object = None, __tb: TracebackType | None = None + self, typ: type[BaseException], val: BaseException | object = None, tb: TracebackType | None = None, / ) -> _YieldT_co: ... @overload @abstractmethod - def throw(self, __typ: BaseException, __val: None = None, __tb: TracebackType | None = None) -> _YieldT_co: ... + def throw(self, typ: BaseException, val: None = None, tb: TracebackType | None = None, /) -> _YieldT_co: ... @abstractmethod def close(self) -> None: ... @@ -483,15 +485,15 @@ class AsyncIterator(AsyncIterable[_T_co], Protocol[_T_co]): class AsyncGenerator(AsyncIterator[_YieldT_co], Generic[_YieldT_co, _SendT_contra]): def __anext__(self) -> Awaitable[_YieldT_co]: ... @abstractmethod - def asend(self, __value: _SendT_contra) -> Awaitable[_YieldT_co]: ... + def asend(self, value: _SendT_contra, /) -> Awaitable[_YieldT_co]: ... @overload @abstractmethod def athrow( - self, __typ: type[BaseException], __val: BaseException | object = None, __tb: TracebackType | None = None + self, typ: type[BaseException], val: BaseException | object = None, tb: TracebackType | None = None, / ) -> Awaitable[_YieldT_co]: ... @overload @abstractmethod - def athrow(self, __typ: BaseException, __val: None = None, __tb: TracebackType | None = None) -> Awaitable[_YieldT_co]: ... + def athrow(self, typ: BaseException, val: None = None, tb: TracebackType | None = None, /) -> Awaitable[_YieldT_co]: ... def aclose(self) -> Awaitable[None]: ... @property def ag_await(self) -> Any: ... @@ -506,7 +508,7 @@ class AsyncGenerator(AsyncIterator[_YieldT_co], Generic[_YieldT_co, _SendT_contr class Container(Protocol[_T_co]): # This is generic more on vibes than anything else @abstractmethod - def __contains__(self, __x: object) -> bool: ... + def __contains__(self, x: object, /) -> bool: ... @runtime_checkable class Collection(Iterable[_T_co], Container[_T_co], Protocol[_T_co]): @@ -630,30 +632,30 @@ class Mapping(Collection[_KT], Generic[_KT, _VT_co]): # TODO: We wish the key type could also be covariant, but that doesn't work, # see discussion in https://github.com/python/typing/pull/273. @abstractmethod - def __getitem__(self, __key: _KT) -> _VT_co: ... + def __getitem__(self, key: _KT, /) -> _VT_co: ... # Mixin methods @overload - def get(self, __key: _KT) -> _VT_co | None: ... + def get(self, key: _KT, /) -> _VT_co | None: ... @overload - def get(self, __key: _KT, default: _VT_co | _T) -> _VT_co | _T: ... + def get(self, key: _KT, /, default: _VT_co | _T) -> _VT_co | _T: ... def items(self) -> ItemsView[_KT, _VT_co]: ... def keys(self) -> KeysView[_KT]: ... def values(self) -> ValuesView[_VT_co]: ... - def __contains__(self, __key: object) -> bool: ... - def __eq__(self, __other: object) -> bool: ... + def __contains__(self, key: object, /) -> bool: ... + def __eq__(self, other: object, /) -> bool: ... class MutableMapping(Mapping[_KT, _VT]): @abstractmethod - def __setitem__(self, __key: _KT, __value: _VT) -> None: ... + def __setitem__(self, key: _KT, value: _VT, /) -> None: ... @abstractmethod - def __delitem__(self, __key: _KT) -> None: ... + def __delitem__(self, key: _KT, /) -> None: ... def clear(self) -> None: ... @overload - def pop(self, __key: _KT) -> _VT: ... + def pop(self, key: _KT, /) -> _VT: ... @overload - def pop(self, __key: _KT, default: _VT) -> _VT: ... + def pop(self, key: _KT, /, default: _VT) -> _VT: ... @overload - def pop(self, __key: _KT, default: _T) -> _VT | _T: ... + def pop(self, key: _KT, /, default: _T) -> _VT | _T: ... def popitem(self) -> tuple[_KT, _VT]: ... # This overload should be allowed only if the value type is compatible with None. # @@ -662,9 +664,9 @@ class MutableMapping(Mapping[_KT, _VT]): # -- collections.ChainMap.setdefault # -- weakref.WeakKeyDictionary.setdefault @overload - def setdefault(self: MutableMapping[_KT, _T | None], __key: _KT, __default: None = None) -> _T | None: ... + def setdefault(self: MutableMapping[_KT, _T | None], key: _KT, default: None = None, /) -> _T | None: ... @overload - def setdefault(self, __key: _KT, __default: _VT) -> _VT: ... + def setdefault(self, key: _KT, default: _VT, /) -> _VT: ... # 'update' used to take a Union, but using overloading is better. # The second overloaded type here is a bit too general, because # Mapping[tuple[_KT, _VT], W] is a subclass of Iterable[tuple[_KT, _VT]], @@ -686,9 +688,9 @@ class MutableMapping(Mapping[_KT, _VT]): # -- weakref.WeakValueDictionary.__ior__ # -- weakref.WeakKeyDictionary.__ior__ @overload - def update(self, __m: SupportsKeysAndGetItem[_KT, _VT], **kwargs: _VT) -> None: ... + def update(self, m: SupportsKeysAndGetItem[_KT, _VT], /, **kwargs: _VT) -> None: ... @overload - def update(self, __m: Iterable[tuple[_KT, _VT]], **kwargs: _VT) -> None: ... + def update(self, m: Iterable[tuple[_KT, _VT]], /, **kwargs: _VT) -> None: ... @overload def update(self, **kwargs: _VT) -> None: ... @@ -720,41 +722,41 @@ class IO(Iterator[AnyStr]): @abstractmethod def isatty(self) -> bool: ... @abstractmethod - def read(self, __n: int = -1) -> AnyStr: ... + def read(self, n: int = -1, /) -> AnyStr: ... @abstractmethod def readable(self) -> bool: ... @abstractmethod - def readline(self, __limit: int = -1) -> AnyStr: ... + def readline(self, limit: int = -1, /) -> AnyStr: ... @abstractmethod - def readlines(self, __hint: int = -1) -> list[AnyStr]: ... + def readlines(self, hint: int = -1, /) -> list[AnyStr]: ... @abstractmethod - def seek(self, __offset: int, __whence: int = 0) -> int: ... + def seek(self, offset: int, whence: int = 0, /) -> int: ... @abstractmethod def seekable(self) -> bool: ... @abstractmethod def tell(self) -> int: ... @abstractmethod - def truncate(self, __size: int | None = None) -> int: ... + def truncate(self, size: int | None = None, /) -> int: ... @abstractmethod def writable(self) -> bool: ... @abstractmethod @overload - def write(self: IO[str], __s: str) -> int: ... + def write(self: IO[str], s: str, /) -> int: ... @abstractmethod @overload - def write(self: IO[bytes], __s: ReadableBuffer) -> int: ... + def write(self: IO[bytes], s: ReadableBuffer, /) -> int: ... @abstractmethod @overload - def write(self, __s: AnyStr) -> int: ... + def write(self, s: AnyStr, /) -> int: ... @abstractmethod @overload - def writelines(self: IO[str], __lines: Iterable[str]) -> None: ... + def writelines(self: IO[str], lines: Iterable[str], /) -> None: ... @abstractmethod @overload - def writelines(self: IO[bytes], __lines: Iterable[ReadableBuffer]) -> None: ... + def writelines(self: IO[bytes], lines: Iterable[ReadableBuffer], /) -> None: ... @abstractmethod @overload - def writelines(self, __lines: Iterable[AnyStr]) -> None: ... + def writelines(self, lines: Iterable[AnyStr], /) -> None: ... @abstractmethod def __next__(self) -> AnyStr: ... @abstractmethod @@ -763,7 +765,7 @@ class IO(Iterator[AnyStr]): def __enter__(self) -> IO[AnyStr]: ... @abstractmethod def __exit__( - self, __type: type[BaseException] | None, __value: BaseException | None, __traceback: TracebackType | None + self, type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None, / ) -> None: ... class BinaryIO(IO[bytes]): @@ -839,9 +841,9 @@ def cast(typ: str, val: Any) -> Any: ... def cast(typ: object, val: Any) -> Any: ... if sys.version_info >= (3, 11): - def reveal_type(__obj: _T) -> _T: ... - def assert_never(__arg: Never) -> Never: ... - def assert_type(__val: _T, __typ: Any) -> _T: ... + def reveal_type(obj: _T, /) -> _T: ... + def assert_never(arg: Never, /) -> Never: ... + def assert_type(val: _T, typ: Any, /) -> _T: ... def clear_overloads() -> None: ... def get_overloads(func: Callable[..., object]) -> Sequence[Callable[..., object]]: ... def dataclass_transform( @@ -867,9 +869,12 @@ class NamedTuple(tuple[Any, ...]): __orig_bases__: ClassVar[tuple[Any, ...]] @overload - def __init__(self, __typename: str, __fields: Iterable[tuple[str, Any]]) -> None: ... + def __init__(self, typename: str, fields: Iterable[tuple[str, Any]], /) -> None: ... @overload - def __init__(self, __typename: str, __fields: None = None, **kwargs: Any) -> None: ... + @typing_extensions.deprecated( + "Creating a typing.NamedTuple using keyword arguments is deprecated and support will be removed in Python 3.15" + ) + def __init__(self, typename: str, fields: None = None, /, **kwargs: Any) -> None: ... @classmethod def _make(cls, iterable: Iterable[Any]) -> typing_extensions.Self: ... def _asdict(self) -> dict[str, Any]: ... @@ -894,22 +899,22 @@ class _TypedDict(Mapping[str, object], metaclass=ABCMeta): def setdefault(self, k: _Never, default: object) -> object: ... # Mypy plugin hook for 'pop' expects that 'default' has a type variable type. def pop(self, k: _Never, default: _T = ...) -> object: ... # pyright: ignore[reportInvalidTypeVarUse] - def update(self: _T, __m: _T) -> None: ... + def update(self: _T, m: _T, /) -> None: ... def __delitem__(self, k: _Never) -> None: ... def items(self) -> dict_items[str, object]: ... def keys(self) -> dict_keys[str, object]: ... def values(self) -> dict_values[str, object]: ... if sys.version_info >= (3, 9): @overload - def __or__(self, __value: typing_extensions.Self) -> typing_extensions.Self: ... + def __or__(self, value: typing_extensions.Self, /) -> typing_extensions.Self: ... @overload - def __or__(self, __value: dict[str, Any]) -> dict[str, object]: ... + def __or__(self, value: dict[str, Any], /) -> dict[str, object]: ... @overload - def __ror__(self, __value: typing_extensions.Self) -> typing_extensions.Self: ... + def __ror__(self, value: typing_extensions.Self, /) -> typing_extensions.Self: ... @overload - def __ror__(self, __value: dict[str, Any]) -> dict[str, object]: ... + def __ror__(self, value: dict[str, Any], /) -> dict[str, object]: ... # supposedly incompatible definitions of __or__ and __ior__ - def __ior__(self, __value: typing_extensions.Self) -> typing_extensions.Self: ... # type: ignore[misc] + def __ior__(self, value: typing_extensions.Self, /) -> typing_extensions.Self: ... # type: ignore[misc] @final class ForwardRef: @@ -945,7 +950,7 @@ if sys.version_info >= (3, 10): def _type_repr(obj: object) -> str: ... if sys.version_info >= (3, 12): - def override(__method: _F) -> _F: ... + def override(method: _F, /) -> _F: ... @final class TypeAliasType: def __init__( @@ -967,5 +972,5 @@ if sys.version_info >= (3, 12): def __ror__(self, left: Any) -> _SpecialForm: ... if sys.version_info >= (3, 13): - def is_protocol(__tp: type) -> bool: ... - def get_protocol_members(__tp: type) -> frozenset[str]: ... + def is_protocol(tp: type, /) -> bool: ... + def get_protocol_members(tp: type, /) -> frozenset[str]: ... diff --git a/mypy/typeshed/stdlib/typing_extensions.pyi b/mypy/typeshed/stdlib/typing_extensions.pyi index 921c1334cfe4..f9e94ca683d6 100644 --- a/mypy/typeshed/stdlib/typing_extensions.pyi +++ b/mypy/typeshed/stdlib/typing_extensions.pyi @@ -235,22 +235,22 @@ class _TypedDict(Mapping[str, object], metaclass=abc.ABCMeta): def setdefault(self, k: Never, default: object) -> object: ... # Mypy plugin hook for 'pop' expects that 'default' has a type variable type. def pop(self, k: Never, default: _T = ...) -> object: ... # pyright: ignore[reportInvalidTypeVarUse] - def update(self: _T, __m: _T) -> None: ... + def update(self: _T, m: _T, /) -> None: ... def items(self) -> dict_items[str, object]: ... def keys(self) -> dict_keys[str, object]: ... def values(self) -> dict_values[str, object]: ... def __delitem__(self, k: Never) -> None: ... if sys.version_info >= (3, 9): @overload - def __or__(self, __value: Self) -> Self: ... + def __or__(self, value: Self, /) -> Self: ... @overload - def __or__(self, __value: dict[str, Any]) -> dict[str, object]: ... + def __or__(self, value: dict[str, Any], /) -> dict[str, object]: ... @overload - def __ror__(self, __value: Self) -> Self: ... + def __ror__(self, value: Self, /) -> Self: ... @overload - def __ror__(self, __value: dict[str, Any]) -> dict[str, object]: ... + def __ror__(self, value: dict[str, Any], /) -> dict[str, object]: ... # supposedly incompatible definitions of `__ior__` and `__or__`: - def __ior__(self, __value: Self) -> Self: ... # type: ignore[misc] + def __ior__(self, value: Self, /) -> Self: ... # type: ignore[misc] # TypedDict is a (non-subscriptable) special form. TypedDict: object @@ -335,9 +335,9 @@ if sys.version_info >= (3, 11): else: Self: _SpecialForm Never: _SpecialForm - def reveal_type(__obj: _T) -> _T: ... - def assert_never(__arg: Never) -> Never: ... - def assert_type(__val: _T, __typ: Any) -> _T: ... + def reveal_type(obj: _T, /) -> _T: ... + def assert_never(arg: Never, /) -> Never: ... + def assert_type(val: _T, typ: Any, /) -> _T: ... def clear_overloads() -> None: ... def get_overloads(func: Callable[..., object]) -> Sequence[Callable[..., object]]: ... @@ -373,7 +373,7 @@ else: class NewType: def __init__(self, name: str, tp: Any) -> None: ... - def __call__(self, __obj: _T) -> _T: ... + def __call__(self, obj: _T, /) -> _T: ... __supertype__: type if sys.version_info >= (3, 10): def __or__(self, other: Any) -> _SpecialForm: ... @@ -456,16 +456,16 @@ class deprecated: message: str category: type[Warning] | None stacklevel: int - def __init__(self, __message: str, *, category: type[Warning] | None = ..., stacklevel: int = 1) -> None: ... - def __call__(self, __arg: _T) -> _T: ... + def __init__(self, message: str, /, *, category: type[Warning] | None = ..., stacklevel: int = 1) -> None: ... + def __call__(self, arg: _T, /) -> _T: ... if sys.version_info >= (3, 12): from collections.abc import Buffer as Buffer from types import get_original_bases as get_original_bases from typing import TypeAliasType as TypeAliasType, override as override else: - def override(__arg: _F) -> _F: ... - def get_original_bases(__cls: type) -> tuple[Any, ...]: ... + def override(arg: _F, /) -> _F: ... + def get_original_bases(cls: type, /) -> tuple[Any, ...]: ... @final class TypeAliasType: def __init__( @@ -491,17 +491,17 @@ else: class Buffer(Protocol): # Not actually a Protocol at runtime; see # https://github.com/python/typeshed/issues/10224 for why we're defining it this way - def __buffer__(self, __flags: int) -> memoryview: ... + def __buffer__(self, flags: int, /) -> memoryview: ... if sys.version_info >= (3, 13): from typing import get_protocol_members as get_protocol_members, is_protocol as is_protocol else: - def is_protocol(__tp: type) -> bool: ... - def get_protocol_members(__tp: type) -> frozenset[str]: ... + def is_protocol(tp: type, /) -> bool: ... + def get_protocol_members(tp: type, /) -> frozenset[str]: ... class Doc: documentation: str - def __init__(self, __documentation: str) -> None: ... + def __init__(self, documentation: str, /) -> None: ... def __hash__(self) -> int: ... def __eq__(self, other: object) -> bool: ... diff --git a/mypy/typeshed/stdlib/unicodedata.pyi b/mypy/typeshed/stdlib/unicodedata.pyi index 5c6749c8a1ae..77d69edf06af 100644 --- a/mypy/typeshed/stdlib/unicodedata.pyi +++ b/mypy/typeshed/stdlib/unicodedata.pyi @@ -13,61 +13,61 @@ _T = TypeVar("_T") _NormalizationForm: TypeAlias = Literal["NFC", "NFD", "NFKC", "NFKD"] -def bidirectional(__chr: str) -> str: ... -def category(__chr: str) -> str: ... -def combining(__chr: str) -> int: ... +def bidirectional(chr: str, /) -> str: ... +def category(chr: str, /) -> str: ... +def combining(chr: str, /) -> int: ... @overload -def decimal(__chr: str) -> int: ... +def decimal(chr: str, /) -> int: ... @overload -def decimal(__chr: str, __default: _T) -> int | _T: ... -def decomposition(__chr: str) -> str: ... +def decimal(chr: str, default: _T, /) -> int | _T: ... +def decomposition(chr: str, /) -> str: ... @overload -def digit(__chr: str) -> int: ... +def digit(chr: str, /) -> int: ... @overload -def digit(__chr: str, __default: _T) -> int | _T: ... +def digit(chr: str, default: _T, /) -> int | _T: ... _EastAsianWidth: TypeAlias = Literal["F", "H", "W", "Na", "A", "N"] -def east_asian_width(__chr: str) -> _EastAsianWidth: ... -def is_normalized(__form: _NormalizationForm, __unistr: str) -> bool: ... -def lookup(__name: str | ReadOnlyBuffer) -> str: ... -def mirrored(__chr: str) -> int: ... +def east_asian_width(chr: str, /) -> _EastAsianWidth: ... +def is_normalized(form: _NormalizationForm, unistr: str, /) -> bool: ... +def lookup(name: str | ReadOnlyBuffer, /) -> str: ... +def mirrored(chr: str, /) -> int: ... @overload -def name(__chr: str) -> str: ... +def name(chr: str, /) -> str: ... @overload -def name(__chr: str, __default: _T) -> str | _T: ... -def normalize(__form: _NormalizationForm, __unistr: str) -> str: ... +def name(chr: str, default: _T, /) -> str | _T: ... +def normalize(form: _NormalizationForm, unistr: str, /) -> str: ... @overload -def numeric(__chr: str) -> float: ... +def numeric(chr: str, /) -> float: ... @overload -def numeric(__chr: str, __default: _T) -> float | _T: ... +def numeric(chr: str, default: _T, /) -> float | _T: ... @final class UCD: # The methods below are constructed from the same array in C # (unicodedata_functions) and hence identical to the functions above. unidata_version: str - def bidirectional(self, __chr: str) -> str: ... - def category(self, __chr: str) -> str: ... - def combining(self, __chr: str) -> int: ... + def bidirectional(self, chr: str, /) -> str: ... + def category(self, chr: str, /) -> str: ... + def combining(self, chr: str, /) -> int: ... @overload - def decimal(self, __chr: str) -> int: ... + def decimal(self, chr: str, /) -> int: ... @overload - def decimal(self, __chr: str, __default: _T) -> int | _T: ... - def decomposition(self, __chr: str) -> str: ... + def decimal(self, chr: str, default: _T, /) -> int | _T: ... + def decomposition(self, chr: str, /) -> str: ... @overload - def digit(self, __chr: str) -> int: ... + def digit(self, chr: str, /) -> int: ... @overload - def digit(self, __chr: str, __default: _T) -> int | _T: ... - def east_asian_width(self, __chr: str) -> _EastAsianWidth: ... - def is_normalized(self, __form: _NormalizationForm, __unistr: str) -> bool: ... - def lookup(self, __name: str | ReadOnlyBuffer) -> str: ... - def mirrored(self, __chr: str) -> int: ... + def digit(self, chr: str, default: _T, /) -> int | _T: ... + def east_asian_width(self, chr: str, /) -> _EastAsianWidth: ... + def is_normalized(self, form: _NormalizationForm, unistr: str, /) -> bool: ... + def lookup(self, name: str | ReadOnlyBuffer, /) -> str: ... + def mirrored(self, chr: str, /) -> int: ... @overload - def name(self, __chr: str) -> str: ... + def name(self, chr: str, /) -> str: ... @overload - def name(self, __chr: str, __default: _T) -> str | _T: ... - def normalize(self, __form: _NormalizationForm, __unistr: str) -> str: ... + def name(self, chr: str, default: _T, /) -> str | _T: ... + def normalize(self, form: _NormalizationForm, unistr: str, /) -> str: ... @overload - def numeric(self, __chr: str) -> float: ... + def numeric(self, chr: str, /) -> float: ... @overload - def numeric(self, __chr: str, __default: _T) -> float | _T: ... + def numeric(self, chr: str, default: _T, /) -> float | _T: ... diff --git a/mypy/typeshed/stdlib/unittest/async_case.pyi b/mypy/typeshed/stdlib/unittest/async_case.pyi index b71eec2e0644..12d6ef49e828 100644 --- a/mypy/typeshed/stdlib/unittest/async_case.pyi +++ b/mypy/typeshed/stdlib/unittest/async_case.pyi @@ -14,7 +14,7 @@ _P = ParamSpec("_P") class IsolatedAsyncioTestCase(TestCase): async def asyncSetUp(self) -> None: ... async def asyncTearDown(self) -> None: ... - def addAsyncCleanup(self, __func: Callable[_P, Awaitable[object]], *args: _P.args, **kwargs: _P.kwargs) -> None: ... + def addAsyncCleanup(self, func: Callable[_P, Awaitable[object]], /, *args: _P.args, **kwargs: _P.kwargs) -> None: ... if sys.version_info >= (3, 11): async def enterAsyncContext(self, cm: AbstractAsyncContextManager[_T]) -> _T: ... if sys.version_info >= (3, 9): diff --git a/mypy/typeshed/stdlib/unittest/case.pyi b/mypy/typeshed/stdlib/unittest/case.pyi index 120bb96d761b..bd1c064f0270 100644 --- a/mypy/typeshed/stdlib/unittest/case.pyi +++ b/mypy/typeshed/stdlib/unittest/case.pyi @@ -68,7 +68,7 @@ else: self, exc_type: type[BaseException] | None, exc_value: BaseException | None, tb: TracebackType | None ) -> bool | None: ... -def addModuleCleanup(__function: Callable[_P, object], *args: _P.args, **kwargs: _P.kwargs) -> None: ... +def addModuleCleanup(function: Callable[_P, object], /, *args: _P.args, **kwargs: _P.kwargs) -> None: ... def doModuleCleanups() -> None: ... if sys.version_info >= (3, 11): @@ -273,14 +273,14 @@ class TestCase: def defaultTestResult(self) -> unittest.result.TestResult: ... def id(self) -> str: ... def shortDescription(self) -> str | None: ... - def addCleanup(self, __function: Callable[_P, object], *args: _P.args, **kwargs: _P.kwargs) -> None: ... + def addCleanup(self, function: Callable[_P, object], /, *args: _P.args, **kwargs: _P.kwargs) -> None: ... if sys.version_info >= (3, 11): def enterContext(self, cm: AbstractContextManager[_T]) -> _T: ... def doCleanups(self) -> None: ... @classmethod - def addClassCleanup(cls, __function: Callable[_P, object], *args: _P.args, **kwargs: _P.kwargs) -> None: ... + def addClassCleanup(cls, function: Callable[_P, object], /, *args: _P.args, **kwargs: _P.kwargs) -> None: ... @classmethod def doClassCleanups(cls) -> None: ... diff --git a/mypy/typeshed/stdlib/unittest/main.pyi b/mypy/typeshed/stdlib/unittest/main.pyi index 3e8cb7b764c2..55bc1ec741db 100644 --- a/mypy/typeshed/stdlib/unittest/main.pyi +++ b/mypy/typeshed/stdlib/unittest/main.pyi @@ -11,7 +11,7 @@ MAIN_EXAMPLES: str MODULE_EXAMPLES: str class _TestRunner(Protocol): - def run(self, __test: unittest.suite.TestSuite | unittest.case.TestCase) -> unittest.result.TestResult: ... + def run(self, test: unittest.suite.TestSuite | unittest.case.TestCase, /) -> unittest.result.TestResult: ... # not really documented class TestProgram: diff --git a/mypy/typeshed/stdlib/unittest/mock.pyi b/mypy/typeshed/stdlib/unittest/mock.pyi index c6014d4bb886..6e64e7a85560 100644 --- a/mypy/typeshed/stdlib/unittest/mock.pyi +++ b/mypy/typeshed/stdlib/unittest/mock.pyi @@ -65,7 +65,7 @@ class _Call(tuple[Any, ...]): from_kall: bool = True, ) -> None: ... def __eq__(self, other: object) -> bool: ... - def __ne__(self, __value: object) -> bool: ... + def __ne__(self, value: object, /) -> bool: ... def __call__(self, *args: Any, **kwargs: Any) -> _Call: ... def __getattr__(self, attr: str) -> Any: ... def __getattribute__(self, attr: str) -> Any: ... @@ -103,7 +103,7 @@ class NonCallableMock(Base, Any): **kwargs: Any, ) -> Self: ... else: - def __new__(__cls, *args: Any, **kw: Any) -> Self: ... + def __new__(cls, /, *args: Any, **kw: Any) -> Self: ... def __init__( self, @@ -234,7 +234,7 @@ class _patch(Generic[_T]): is_local: bool def __enter__(self) -> _T: ... 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 start(self) -> _T: ... def stop(self) -> None: ... diff --git a/mypy/typeshed/stdlib/urllib/request.pyi b/mypy/typeshed/stdlib/urllib/request.pyi index ca3feaea262a..3442be8b8ea4 100644 --- a/mypy/typeshed/stdlib/urllib/request.pyi +++ b/mypy/typeshed/stdlib/urllib/request.pyi @@ -227,7 +227,8 @@ class ProxyDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler): class _HTTPConnectionProtocol(Protocol): def __call__( self, - __host: str, + host: str, + /, *, port: int | None = ..., timeout: float = ..., diff --git a/mypy/typeshed/stdlib/weakref.pyi b/mypy/typeshed/stdlib/weakref.pyi index 1bb2eacfb46a..8f3ad0631c10 100644 --- a/mypy/typeshed/stdlib/weakref.pyi +++ b/mypy/typeshed/stdlib/weakref.pyi @@ -51,10 +51,10 @@ class WeakValueDictionary(MutableMapping[_KT, _VT]): @overload def __init__(self) -> None: ... @overload - def __init__(self: WeakValueDictionary[_KT, _VT], __other: Mapping[_KT, _VT] | Iterable[tuple[_KT, _VT]]) -> None: ... + def __init__(self: WeakValueDictionary[_KT, _VT], other: Mapping[_KT, _VT] | Iterable[tuple[_KT, _VT]], /) -> None: ... @overload def __init__( - self: WeakValueDictionary[str, _VT], __other: Mapping[str, _VT] | Iterable[tuple[str, _VT]] = (), **kwargs: _VT + self: WeakValueDictionary[str, _VT], other: Mapping[str, _VT] | Iterable[tuple[str, _VT]] = (), /, **kwargs: _VT ) -> None: ... def __len__(self) -> int: ... def __getitem__(self, key: _KT) -> _VT: ... @@ -93,7 +93,6 @@ class WeakValueDictionary(MutableMapping[_KT, _VT]): class KeyedRef(ref[_T], Generic[_KT, _T]): key: _KT - # This __new__ method uses a non-standard name for the "cls" parameter def __new__(type, ob: _T, callback: Callable[[_T], Any], key: _KT) -> Self: ... def __init__(self, ob: _T, callback: Callable[[_T], Any], key: _KT) -> None: ... @@ -141,7 +140,7 @@ class WeakKeyDictionary(MutableMapping[_KT, _VT]): def __ior__(self, other: Iterable[tuple[_KT, _VT]]) -> Self: ... class finalize: # TODO: This is a good candidate for to be a `Generic[_P, _T]` class - def __init__(self, __obj: object, __func: Callable[_P, Any], *args: _P.args, **kwargs: _P.kwargs) -> None: ... + def __init__(self, obj: object, func: Callable[_P, Any], /, *args: _P.args, **kwargs: _P.kwargs) -> None: ... def __call__(self, _: Any = None) -> Any | None: ... def detach(self) -> tuple[Any, Any, tuple[Any, ...], dict[str, Any]] | None: ... def peek(self) -> tuple[Any, Any, tuple[Any, ...], dict[str, Any]] | None: ... diff --git a/mypy/typeshed/stdlib/winreg.pyi b/mypy/typeshed/stdlib/winreg.pyi index 897177547c71..ffb0a4cb8094 100644 --- a/mypy/typeshed/stdlib/winreg.pyi +++ b/mypy/typeshed/stdlib/winreg.pyi @@ -5,31 +5,31 @@ from typing_extensions import Self, TypeAlias if sys.platform == "win32": _KeyType: TypeAlias = HKEYType | int - def CloseKey(__hkey: _KeyType) -> None: ... - def ConnectRegistry(__computer_name: str | None, __key: _KeyType) -> HKEYType: ... - def CreateKey(__key: _KeyType, __sub_key: str | None) -> HKEYType: ... + def CloseKey(hkey: _KeyType, /) -> None: ... + def ConnectRegistry(computer_name: str | None, key: _KeyType, /) -> HKEYType: ... + def CreateKey(key: _KeyType, sub_key: str | None, /) -> HKEYType: ... def CreateKeyEx(key: _KeyType, sub_key: str | None, reserved: int = 0, access: int = 131078) -> HKEYType: ... - def DeleteKey(__key: _KeyType, __sub_key: str) -> None: ... + def DeleteKey(key: _KeyType, sub_key: str, /) -> None: ... def DeleteKeyEx(key: _KeyType, sub_key: str, access: int = 256, reserved: int = 0) -> None: ... - def DeleteValue(__key: _KeyType, __value: str) -> None: ... - def EnumKey(__key: _KeyType, __index: int) -> str: ... - def EnumValue(__key: _KeyType, __index: int) -> tuple[str, Any, int]: ... - def ExpandEnvironmentStrings(__string: str) -> str: ... - def FlushKey(__key: _KeyType) -> None: ... - def LoadKey(__key: _KeyType, __sub_key: str, __file_name: str) -> None: ... + def DeleteValue(key: _KeyType, value: str, /) -> None: ... + def EnumKey(key: _KeyType, index: int, /) -> str: ... + def EnumValue(key: _KeyType, index: int, /) -> tuple[str, Any, int]: ... + def ExpandEnvironmentStrings(string: str, /) -> str: ... + def FlushKey(key: _KeyType, /) -> None: ... + def LoadKey(key: _KeyType, sub_key: str, file_name: str, /) -> None: ... def OpenKey(key: _KeyType, sub_key: str, reserved: int = 0, access: int = 131097) -> HKEYType: ... def OpenKeyEx(key: _KeyType, sub_key: str, reserved: int = 0, access: int = 131097) -> HKEYType: ... - def QueryInfoKey(__key: _KeyType) -> tuple[int, int, int]: ... - def QueryValue(__key: _KeyType, __sub_key: str | None) -> str: ... - def QueryValueEx(__key: _KeyType, __name: str) -> tuple[Any, int]: ... - def SaveKey(__key: _KeyType, __file_name: str) -> None: ... - def SetValue(__key: _KeyType, __sub_key: str, __type: int, __value: str) -> None: ... + def QueryInfoKey(key: _KeyType, /) -> tuple[int, int, int]: ... + def QueryValue(key: _KeyType, sub_key: str | None, /) -> str: ... + def QueryValueEx(key: _KeyType, name: str, /) -> tuple[Any, int]: ... + def SaveKey(key: _KeyType, file_name: str, /) -> None: ... + def SetValue(key: _KeyType, sub_key: str, type: int, value: str, /) -> None: ... def SetValueEx( - __key: _KeyType, __value_name: str | None, __reserved: Any, __type: int, __value: str | int + key: _KeyType, value_name: str | None, reserved: Any, type: int, value: str | int, / ) -> None: ... # reserved is ignored - def DisableReflectionKey(__key: _KeyType) -> None: ... - def EnableReflectionKey(__key: _KeyType) -> None: ... - def QueryReflectionKey(__key: _KeyType) -> bool: ... + def DisableReflectionKey(key: _KeyType, /) -> None: ... + def EnableReflectionKey(key: _KeyType, /) -> None: ... + def QueryReflectionKey(key: _KeyType, /) -> bool: ... HKEY_CLASSES_ROOT: int HKEY_CURRENT_USER: int HKEY_LOCAL_MACHINE: int diff --git a/mypy/typeshed/stdlib/wsgiref/types.pyi b/mypy/typeshed/stdlib/wsgiref/types.pyi index 4e8f47264f3a..86212df8ccdc 100644 --- a/mypy/typeshed/stdlib/wsgiref/types.pyi +++ b/mypy/typeshed/stdlib/wsgiref/types.pyi @@ -7,26 +7,26 @@ __all__ = ["StartResponse", "WSGIEnvironment", "WSGIApplication", "InputStream", class StartResponse(Protocol): def __call__( - self, __status: str, __headers: list[tuple[str, str]], __exc_info: _OptExcInfo | None = ... + self, status: str, headers: list[tuple[str, str]], exc_info: _OptExcInfo | None = ..., / ) -> Callable[[bytes], object]: ... WSGIEnvironment: TypeAlias = dict[str, Any] WSGIApplication: TypeAlias = Callable[[WSGIEnvironment, StartResponse], Iterable[bytes]] class InputStream(Protocol): - def read(self, __size: int = ...) -> bytes: ... - def readline(self, __size: int = ...) -> bytes: ... - def readlines(self, __hint: int = ...) -> list[bytes]: ... + def read(self, size: int = ..., /) -> bytes: ... + def readline(self, size: int = ..., /) -> bytes: ... + def readlines(self, hint: int = ..., /) -> list[bytes]: ... def __iter__(self) -> Iterator[bytes]: ... class ErrorStream(Protocol): def flush(self) -> object: ... - def write(self, __s: str) -> object: ... - def writelines(self, __seq: list[str]) -> object: ... + def write(self, s: str, /) -> object: ... + def writelines(self, seq: list[str], /) -> object: ... class _Readable(Protocol): - def read(self, __size: int = ...) -> bytes: ... + def read(self, size: int = ..., /) -> bytes: ... # Optional: def close(self) -> object: ... class FileWrapper(Protocol): - def __call__(self, __file: _Readable, __block_size: int = ...) -> Iterable[bytes]: ... + def __call__(self, file: _Readable, block_size: int = ..., /) -> Iterable[bytes]: ... diff --git a/mypy/typeshed/stdlib/xml/etree/ElementTree.pyi b/mypy/typeshed/stdlib/xml/etree/ElementTree.pyi index 2a363a504dec..a8af66938344 100644 --- a/mypy/typeshed/stdlib/xml/etree/ElementTree.pyi +++ b/mypy/typeshed/stdlib/xml/etree/ElementTree.pyi @@ -84,9 +84,9 @@ class Element: text: str | None tail: str | None def __init__(self, tag: str, attrib: dict[str, str] = ..., **extra: str) -> None: ... - def append(self, __subelement: Element) -> None: ... + def append(self, subelement: Element, /) -> None: ... def clear(self) -> None: ... - def extend(self, __elements: Iterable[Element]) -> None: ... + def extend(self, elements: Iterable[Element], /) -> None: ... def find(self, path: str, namespaces: dict[str, str] | None = None) -> Element | None: ... def findall(self, path: str, namespaces: dict[str, str] | None = None) -> list[Element]: ... @overload @@ -97,30 +97,30 @@ class Element: def get(self, key: str, default: None = None) -> str | None: ... @overload def get(self, key: str, default: _T) -> str | _T: ... - def insert(self, __index: int, __subelement: Element) -> None: ... + def insert(self, index: int, subelement: Element, /) -> None: ... def items(self) -> ItemsView[str, str]: ... def iter(self, tag: str | None = None) -> Generator[Element, None, None]: ... def iterfind(self, path: str, namespaces: dict[str, str] | None = None) -> Generator[Element, None, None]: ... def itertext(self) -> Generator[str, None, None]: ... def keys(self) -> dict_keys[str, str]: ... # makeelement returns the type of self in Python impl, but not in C impl - def makeelement(self, __tag: str, __attrib: dict[str, str]) -> Element: ... - def remove(self, __subelement: Element) -> None: ... - def set(self, __key: str, __value: str) -> None: ... + def makeelement(self, tag: str, attrib: dict[str, str], /) -> Element: ... + def remove(self, subelement: Element, /) -> None: ... + def set(self, key: str, value: str, /) -> None: ... def __copy__(self) -> Element: ... # returns the type of self in Python impl, but not in C impl - def __deepcopy__(self, __memo: Any) -> Element: ... # Only exists in C impl - def __delitem__(self, __key: SupportsIndex | slice) -> None: ... + def __deepcopy__(self, memo: Any, /) -> Element: ... # Only exists in C impl + def __delitem__(self, key: SupportsIndex | slice, /) -> None: ... @overload - def __getitem__(self, __key: SupportsIndex) -> Element: ... + def __getitem__(self, key: SupportsIndex, /) -> Element: ... @overload - def __getitem__(self, __key: slice) -> list[Element]: ... + def __getitem__(self, key: slice, /) -> list[Element]: ... def __len__(self) -> int: ... # Doesn't actually exist at runtime, but instance of the class are indeed iterable due to __getitem__. def __iter__(self) -> Iterator[Element]: ... @overload - def __setitem__(self, __key: SupportsIndex, __value: Element) -> None: ... + def __setitem__(self, key: SupportsIndex, value: Element, /) -> None: ... @overload - def __setitem__(self, __key: slice, __value: Iterable[Element]) -> None: ... + def __setitem__(self, key: slice, value: Iterable[Element], /) -> None: ... # Doesn't really exist in earlier versions, where __len__ is called implicitly instead @deprecated("Testing an element's truth value is deprecated.") @@ -285,14 +285,14 @@ class TreeBuilder: insert_pis: bool def close(self) -> Element: ... - def data(self, __data: str) -> None: ... + def data(self, data: str, /) -> None: ... # tag and attrs are passed to the element_factory, so they could be anything # depending on what the particular factory supports. - def start(self, __tag: Any, __attrs: dict[Any, Any]) -> Element: ... - def end(self, __tag: str) -> Element: ... + def start(self, tag: Any, attrs: dict[Any, Any], /) -> Element: ... + def end(self, tag: str, /) -> Element: ... # These two methods have pos-only parameters in the C implementation - def comment(self, __text: str | None) -> Element: ... - def pi(self, __target: str, __text: str | None = None) -> Element: ... + def comment(self, text: str | None, /) -> Element: ... + def pi(self, target: str, text: str | None = None, /) -> Element: ... class C14NWriterTarget: def __init__( @@ -322,4 +322,4 @@ class XMLParser: version: str def __init__(self, *, target: Any = ..., encoding: str | None = ...) -> None: ... def close(self) -> Any: ... - def feed(self, __data: str | ReadableBuffer) -> None: ... + def feed(self, data: str | ReadableBuffer, /) -> None: ... diff --git a/mypy/typeshed/stdlib/xmlrpc/server.pyi b/mypy/typeshed/stdlib/xmlrpc/server.pyi index 832fe265e0a5..8ca3a4d1a33c 100644 --- a/mypy/typeshed/stdlib/xmlrpc/server.pyi +++ b/mypy/typeshed/stdlib/xmlrpc/server.pyi @@ -12,17 +12,17 @@ class _DispatchArity0(Protocol): def __call__(self) -> _Marshallable: ... class _DispatchArity1(Protocol): - def __call__(self, __arg1: _Marshallable) -> _Marshallable: ... + def __call__(self, arg1: _Marshallable, /) -> _Marshallable: ... class _DispatchArity2(Protocol): - def __call__(self, __arg1: _Marshallable, __arg2: _Marshallable) -> _Marshallable: ... + def __call__(self, arg1: _Marshallable, arg2: _Marshallable, /) -> _Marshallable: ... class _DispatchArity3(Protocol): - def __call__(self, __arg1: _Marshallable, __arg2: _Marshallable, __arg3: _Marshallable) -> _Marshallable: ... + def __call__(self, arg1: _Marshallable, arg2: _Marshallable, arg3: _Marshallable, /) -> _Marshallable: ... class _DispatchArity4(Protocol): def __call__( - self, __arg1: _Marshallable, __arg2: _Marshallable, __arg3: _Marshallable, __arg4: _Marshallable + self, arg1: _Marshallable, arg2: _Marshallable, arg3: _Marshallable, arg4: _Marshallable, / ) -> _Marshallable: ... class _DispatchArityN(Protocol): diff --git a/mypy/typeshed/stdlib/xxlimited.pyi b/mypy/typeshed/stdlib/xxlimited.pyi index 3e6e78de3f70..6bae87a8db2a 100644 --- a/mypy/typeshed/stdlib/xxlimited.pyi +++ b/mypy/typeshed/stdlib/xxlimited.pyi @@ -9,7 +9,7 @@ class Xxo: if sys.version_info >= (3, 11) and sys.platform != "win32": x_exports: int -def foo(__i: int, __j: int) -> Any: ... +def foo(i: int, j: int, /) -> Any: ... def new() -> Xxo: ... if sys.version_info >= (3, 10): @@ -19,4 +19,4 @@ else: class error(Exception): ... class Null: ... - def roj(__b: Any) -> None: ... + def roj(b: Any, /) -> None: ... diff --git a/mypy/typeshed/stdlib/zipfile/__init__.pyi b/mypy/typeshed/stdlib/zipfile/__init__.pyi index be0cdf12a4a9..b61e07f8b90d 100644 --- a/mypy/typeshed/stdlib/zipfile/__init__.pyi +++ b/mypy/typeshed/stdlib/zipfile/__init__.pyi @@ -40,16 +40,16 @@ error = BadZipfile class LargeZipFile(Exception): ... class _ZipStream(Protocol): - def read(self, __n: int) -> bytes: ... + def read(self, n: int, /) -> bytes: ... # The following methods are optional: # def seekable(self) -> bool: ... # def tell(self) -> int: ... - # def seek(self, __n: int) -> object: ... + # def seek(self, n: int, /) -> object: ... # Stream shape as required by _EndRecData() and _EndRecData64(). class _SupportsReadSeekTell(Protocol): - def read(self, __n: int = ...) -> bytes: ... - def seek(self, __cookie: int, __whence: int) -> object: ... + def read(self, n: int = ..., /) -> bytes: ... + def seek(self, cookie: int, whence: int, /) -> object: ... def tell(self) -> int: ... class _ClosableZipStream(_ZipStream, Protocol): @@ -92,7 +92,7 @@ class ZipExtFile(io.BufferedIOBase): def seek(self, offset: int, whence: int = 0) -> int: ... class _Writer(Protocol): - def write(self, __s: str) -> object: ... + def write(self, s: str, /) -> object: ... class ZipFile: filename: str | None diff --git a/mypy/typeshed/stdlib/zlib.pyi b/mypy/typeshed/stdlib/zlib.pyi index efeb5a88a76f..234770172d40 100644 --- a/mypy/typeshed/stdlib/zlib.pyi +++ b/mypy/typeshed/stdlib/zlib.pyi @@ -40,17 +40,17 @@ class _Decompress: def flush(self, length: int = ...) -> bytes: ... def copy(self) -> _Decompress: ... -def adler32(__data: ReadableBuffer, __value: int = 1) -> int: ... +def adler32(data: ReadableBuffer, value: int = 1, /) -> int: ... if sys.version_info >= (3, 11): - def compress(__data: ReadableBuffer, level: int = -1, wbits: int = 15) -> bytes: ... + def compress(data: ReadableBuffer, /, level: int = -1, wbits: int = 15) -> bytes: ... else: - def compress(__data: ReadableBuffer, level: int = -1) -> bytes: ... + def compress(data: ReadableBuffer, /, level: int = -1) -> bytes: ... def compressobj( level: int = -1, method: int = 8, wbits: int = 15, memLevel: int = 8, strategy: int = 0, zdict: ReadableBuffer | None = None ) -> _Compress: ... -def crc32(__data: ReadableBuffer, __value: int = 0) -> int: ... -def decompress(__data: ReadableBuffer, wbits: int = 15, bufsize: int = 16384) -> bytes: ... +def crc32(data: ReadableBuffer, value: int = 0, /) -> int: ... +def decompress(data: ReadableBuffer, /, wbits: int = 15, bufsize: int = 16384) -> bytes: ... def decompressobj(wbits: int = 15, zdict: ReadableBuffer = b"") -> _Decompress: ... diff --git a/mypy/typeshed/stdlib/zoneinfo/__init__.pyi b/mypy/typeshed/stdlib/zoneinfo/__init__.pyi index a95530ed461a..77930ac79dd5 100644 --- a/mypy/typeshed/stdlib/zoneinfo/__init__.pyi +++ b/mypy/typeshed/stdlib/zoneinfo/__init__.pyi @@ -7,8 +7,8 @@ from typing_extensions import Self __all__ = ["ZoneInfo", "reset_tzpath", "available_timezones", "TZPATH", "ZoneInfoNotFoundError", "InvalidTZPathWarning"] class _IOBytes(Protocol): - def read(self, __size: int) -> bytes: ... - def seek(self, __size: int, __whence: int = ...) -> Any: ... + def read(self, size: int, /) -> bytes: ... + def seek(self, size: int, whence: int = ..., /) -> Any: ... class ZoneInfo(tzinfo): @property @@ -17,12 +17,12 @@ class ZoneInfo(tzinfo): @classmethod def no_cache(cls, key: str) -> Self: ... @classmethod - def from_file(cls, __fobj: _IOBytes, key: str | None = None) -> Self: ... + def from_file(cls, fobj: _IOBytes, /, key: str | None = None) -> Self: ... @classmethod def clear_cache(cls, *, only_keys: Iterable[str] | None = None) -> None: ... - def tzname(self, __dt: datetime | None) -> str | None: ... - def utcoffset(self, __dt: datetime | None) -> timedelta | None: ... - def dst(self, __dt: datetime | None) -> timedelta | None: ... + def tzname(self, dt: datetime | None, /) -> str | None: ... + def utcoffset(self, dt: datetime | None, /) -> timedelta | None: ... + def dst(self, dt: datetime | None, /) -> timedelta | None: ... # Note: Both here and in clear_cache, the types allow the use of `str` where # a sequence of strings is required. This should be remedied if a solution From 5c00e362d40aa26e0a22a740f05a52d05edf0f91 Mon Sep 17 00:00:00 2001 From: Shantanu <12621235+hauntsaninja@users.noreply.github.com> Date: Mon, 26 Sep 2022 12:55:07 -0700 Subject: [PATCH 50/54] Remove use of LiteralString in builtins (#13743) --- mypy/typeshed/stdlib/builtins.pyi | 88 ------------------------------- 1 file changed, 88 deletions(-) diff --git a/mypy/typeshed/stdlib/builtins.pyi b/mypy/typeshed/stdlib/builtins.pyi index b4765b26c8e5..99919c64c50d 100644 --- a/mypy/typeshed/stdlib/builtins.pyi +++ b/mypy/typeshed/stdlib/builtins.pyi @@ -61,7 +61,6 @@ from typing import ( # noqa: Y022 from typing_extensions import ( # noqa: Y023 Concatenate, Literal, - LiteralString, ParamSpec, Self, TypeAlias, @@ -434,31 +433,16 @@ class str(Sequence[str]): def __new__(cls, object: object = ...) -> Self: ... @overload def __new__(cls, object: ReadableBuffer, encoding: str = ..., errors: str = ...) -> Self: ... - @overload - def capitalize(self: LiteralString) -> LiteralString: ... - @overload def capitalize(self) -> str: ... # type: ignore[misc] - @overload - def casefold(self: LiteralString) -> LiteralString: ... - @overload def casefold(self) -> str: ... # type: ignore[misc] - @overload - def center(self: LiteralString, width: SupportsIndex, fillchar: LiteralString = " ", /) -> LiteralString: ... - @overload def center(self, width: SupportsIndex, fillchar: str = " ", /) -> str: ... # type: ignore[misc] def count(self, sub: str, start: SupportsIndex | None = ..., end: SupportsIndex | None = ..., /) -> int: ... def encode(self, encoding: str = "utf-8", errors: str = "strict") -> bytes: ... def endswith( self, suffix: str | tuple[str, ...], start: SupportsIndex | None = ..., end: SupportsIndex | None = ..., / ) -> bool: ... - @overload - def expandtabs(self: LiteralString, tabsize: SupportsIndex = 8) -> LiteralString: ... - @overload def expandtabs(self, tabsize: SupportsIndex = 8) -> str: ... # type: ignore[misc] def find(self, sub: str, start: SupportsIndex | None = ..., end: SupportsIndex | None = ..., /) -> int: ... - @overload - def format(self: LiteralString, *args: LiteralString, **kwargs: LiteralString) -> LiteralString: ... - @overload def format(self, *args: object, **kwargs: object) -> str: ... def format_map(self, map: _FormatMapMapping) -> str: ... def index(self, sub: str, start: SupportsIndex | None = ..., end: SupportsIndex | None = ..., /) -> int: ... @@ -474,89 +458,32 @@ class str(Sequence[str]): def isspace(self) -> bool: ... def istitle(self) -> bool: ... def isupper(self) -> bool: ... - @overload - def join(self: LiteralString, iterable: Iterable[LiteralString], /) -> LiteralString: ... - @overload def join(self, iterable: Iterable[str], /) -> str: ... # type: ignore[misc] - @overload - def ljust(self: LiteralString, width: SupportsIndex, fillchar: LiteralString = " ", /) -> LiteralString: ... - @overload def ljust(self, width: SupportsIndex, fillchar: str = " ", /) -> str: ... # type: ignore[misc] - @overload - def lower(self: LiteralString) -> LiteralString: ... - @overload def lower(self) -> str: ... # type: ignore[misc] - @overload - def lstrip(self: LiteralString, chars: LiteralString | None = None, /) -> LiteralString: ... - @overload def lstrip(self, chars: str | None = None, /) -> str: ... # type: ignore[misc] - @overload - def partition(self: LiteralString, sep: LiteralString, /) -> tuple[LiteralString, LiteralString, LiteralString]: ... - @overload def partition(self, sep: str, /) -> tuple[str, str, str]: ... # type: ignore[misc] - @overload - def replace(self: LiteralString, old: LiteralString, new: LiteralString, count: SupportsIndex = -1, /) -> LiteralString: ... - @overload def replace(self, old: str, new: str, count: SupportsIndex = -1, /) -> str: ... # type: ignore[misc] if sys.version_info >= (3, 9): - @overload - def removeprefix(self: LiteralString, prefix: LiteralString, /) -> LiteralString: ... - @overload def removeprefix(self, prefix: str, /) -> str: ... # type: ignore[misc] - @overload - def removesuffix(self: LiteralString, suffix: LiteralString, /) -> LiteralString: ... - @overload def removesuffix(self, suffix: str, /) -> str: ... # type: ignore[misc] def rfind(self, sub: str, start: SupportsIndex | None = ..., end: SupportsIndex | None = ..., /) -> int: ... def rindex(self, sub: str, start: SupportsIndex | None = ..., end: SupportsIndex | None = ..., /) -> int: ... - @overload - def rjust(self: LiteralString, width: SupportsIndex, fillchar: LiteralString = " ", /) -> LiteralString: ... - @overload def rjust(self, width: SupportsIndex, fillchar: str = " ", /) -> str: ... # type: ignore[misc] - @overload - def rpartition(self: LiteralString, sep: LiteralString, /) -> tuple[LiteralString, LiteralString, LiteralString]: ... - @overload def rpartition(self, sep: str, /) -> tuple[str, str, str]: ... # type: ignore[misc] - @overload - def rsplit(self: LiteralString, sep: LiteralString | None = None, maxsplit: SupportsIndex = -1) -> list[LiteralString]: ... - @overload def rsplit(self, sep: str | None = None, maxsplit: SupportsIndex = -1) -> list[str]: ... # type: ignore[misc] - @overload - def rstrip(self: LiteralString, chars: LiteralString | None = None, /) -> LiteralString: ... - @overload def rstrip(self, chars: str | None = None, /) -> str: ... # type: ignore[misc] - @overload - def split(self: LiteralString, sep: LiteralString | None = None, maxsplit: SupportsIndex = -1) -> list[LiteralString]: ... - @overload def split(self, sep: str | None = None, maxsplit: SupportsIndex = -1) -> list[str]: ... # type: ignore[misc] - @overload - def splitlines(self: LiteralString, keepends: bool = False) -> list[LiteralString]: ... - @overload def splitlines(self, keepends: bool = False) -> list[str]: ... # type: ignore[misc] def startswith( self, prefix: str | tuple[str, ...], start: SupportsIndex | None = ..., end: SupportsIndex | None = ..., / ) -> bool: ... - @overload - def strip(self: LiteralString, chars: LiteralString | None = None, /) -> LiteralString: ... - @overload def strip(self, chars: str | None = None, /) -> str: ... # type: ignore[misc] - @overload - def swapcase(self: LiteralString) -> LiteralString: ... - @overload def swapcase(self) -> str: ... # type: ignore[misc] - @overload - def title(self: LiteralString) -> LiteralString: ... - @overload def title(self) -> str: ... # type: ignore[misc] def translate(self, table: _TranslateTable, /) -> str: ... - @overload - def upper(self: LiteralString) -> LiteralString: ... - @overload def upper(self) -> str: ... # type: ignore[misc] - @overload - def zfill(self: LiteralString, width: SupportsIndex, /) -> LiteralString: ... - @overload def zfill(self, width: SupportsIndex, /) -> str: ... # type: ignore[misc] @staticmethod @overload @@ -567,9 +494,6 @@ class str(Sequence[str]): @staticmethod @overload def maketrans(x: str, y: str, z: str, /) -> dict[int, int | None]: ... - @overload - def __add__(self: LiteralString, value: LiteralString, /) -> LiteralString: ... - @overload def __add__(self, value: str, /) -> str: ... # type: ignore[misc] # Incompatible with Sequence.__contains__ def __contains__(self, key: str, /) -> bool: ... # type: ignore[override] @@ -578,25 +502,13 @@ class str(Sequence[str]): def __getitem__(self, key: SupportsIndex | slice, /) -> str: ... def __gt__(self, value: str, /) -> bool: ... def __hash__(self) -> int: ... - @overload - def __iter__(self: LiteralString) -> Iterator[LiteralString]: ... - @overload def __iter__(self) -> Iterator[str]: ... # type: ignore[misc] def __le__(self, value: str, /) -> bool: ... def __len__(self) -> int: ... def __lt__(self, value: str, /) -> bool: ... - @overload - def __mod__(self: LiteralString, value: LiteralString | tuple[LiteralString, ...], /) -> LiteralString: ... - @overload def __mod__(self, value: Any, /) -> str: ... - @overload - def __mul__(self: LiteralString, value: SupportsIndex, /) -> LiteralString: ... - @overload def __mul__(self, value: SupportsIndex, /) -> str: ... # type: ignore[misc] def __ne__(self, value: object, /) -> bool: ... - @overload - def __rmul__(self: LiteralString, value: SupportsIndex, /) -> LiteralString: ... - @overload def __rmul__(self, value: SupportsIndex, /) -> str: ... # type: ignore[misc] def __getnewargs__(self) -> tuple[str]: ... From 44bc98bd50e7170887f0740b53ed95a8eb04f00e Mon Sep 17 00:00:00 2001 From: Shantanu <12621235+hauntsaninja@users.noreply.github.com> Date: Sat, 29 Oct 2022 12:47:21 -0700 Subject: [PATCH 51/54] Revert sum literal integer change (#13961) This is allegedly causing large performance problems, see 13821 typeshed/8231 had zero hits on mypy_primer, so it's not the worst thing to undo. Patching this in typeshed also feels weird, since there's a more general soundness issue. If a typevar has a bound or constraint, we might not want to solve it to a Literal. If we can confirm the performance regression or fix the unsoundness within mypy, I might pursue upstreaming this in typeshed. (Reminder: add this to the sync_typeshed script once merged) --- mypy/typeshed/stdlib/builtins.pyi | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mypy/typeshed/stdlib/builtins.pyi b/mypy/typeshed/stdlib/builtins.pyi index 99919c64c50d..680cd556172f 100644 --- a/mypy/typeshed/stdlib/builtins.pyi +++ b/mypy/typeshed/stdlib/builtins.pyi @@ -1596,7 +1596,7 @@ _SupportsSumNoDefaultT = TypeVar("_SupportsSumNoDefaultT", bound=_SupportsSumWit # without creating many false-positive errors (see #7578). # Instead, we special-case the most common examples of this: bool and literal integers. @overload -def sum(iterable: Iterable[bool | _LiteralInteger], /, start: int = 0) -> int: ... # type: ignore[overload-overlap] +def sum(iterable: Iterable[bool], /, start: int = 0) -> int: ... # type: ignore[overload-overlap] @overload def sum(iterable: Iterable[_SupportsSumNoDefaultT], /) -> _SupportsSumNoDefaultT | Literal[0]: ... @overload From 61a490091d7c941780919660dc4fdfa88ae6474a Mon Sep 17 00:00:00 2001 From: AlexWaygood Date: Mon, 1 May 2023 20:34:55 +0100 Subject: [PATCH 52/54] Revert typeshed ctypes change Since the plugin provides superior type checking: https://github.com/python/mypy/pull/13987#issuecomment-1310863427 A manual cherry-pick of e437cdf. --- mypy/typeshed/stdlib/_ctypes.pyi | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/mypy/typeshed/stdlib/_ctypes.pyi b/mypy/typeshed/stdlib/_ctypes.pyi index 60bbc51d9411..cf9cb81a44a3 100644 --- a/mypy/typeshed/stdlib/_ctypes.pyi +++ b/mypy/typeshed/stdlib/_ctypes.pyi @@ -169,11 +169,7 @@ class Array(_CData, Generic[_CT]): def _type_(self) -> type[_CT]: ... @_type_.setter def _type_(self, value: type[_CT]) -> None: ... - # Note: only available if _CT == c_char - @property - def raw(self) -> bytes: ... - @raw.setter - def raw(self, value: ReadableBuffer) -> None: ... + raw: bytes # Note: only available if _CT == c_char value: Any # Note: bytes if _CT == c_char, str if _CT == c_wchar, unavailable otherwise # TODO These methods cannot be annotated correctly at the moment. # All of these "Any"s stand for the array's element type, but it's not possible to use _CT From b013cc016a3e3c8c7caa6a27bdf7b5e22998dd41 Mon Sep 17 00:00:00 2001 From: Ali Hamdan Date: Sat, 16 Mar 2024 14:38:05 +0100 Subject: [PATCH 53/54] Support `TypeAliasType` in a class scope (#17038) Fixes https://github.com/python/mypy/issues/16614#issuecomment-2000428700 --- mypy/semanal.py | 2 +- test-data/unit/check-type-aliases.test | 5 +++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/mypy/semanal.py b/mypy/semanal.py index 93e84ced4639..5aaf2bc6f433 100644 --- a/mypy/semanal.py +++ b/mypy/semanal.py @@ -3657,7 +3657,7 @@ def check_and_set_up_type_alias(self, s: AssignmentStmt) -> bool: return False non_global_scope = self.type or self.is_func_scope() - if not pep_613 and isinstance(rvalue, RefExpr) and non_global_scope: + if not pep_613 and not pep_695 and isinstance(rvalue, RefExpr) and non_global_scope: # Fourth rule (special case): Non-subscripted right hand side creates a variable # at class and function scopes. For example: # diff --git a/test-data/unit/check-type-aliases.test b/test-data/unit/check-type-aliases.test index 79a443dbeedc..7330a04c3647 100644 --- a/test-data/unit/check-type-aliases.test +++ b/test-data/unit/check-type-aliases.test @@ -1074,6 +1074,11 @@ TestType = TypeAliasType("TestType", Union[int, str]) x: TestType = 42 y: TestType = 'a' z: TestType = object() # E: Incompatible types in assignment (expression has type "object", variable has type "Union[int, str]") + +class A: + ClassAlias = TypeAliasType("ClassAlias", int) +xc: A.ClassAlias = 1 +yc: A.ClassAlias = "" # E: Incompatible types in assignment (expression has type "str", variable has type "int") [builtins fixtures/tuple.pyi] [case testTypeAliasTypeInvalid] From 00220bd095f42b080e0844bb2b0c11f37afc35a5 Mon Sep 17 00:00:00 2001 From: Alex Waygood Date: Sat, 16 Mar 2024 15:39:13 +0000 Subject: [PATCH 54/54] Update commit hashes in sync-typeshed.py (#17042) Followup to #17039 --- misc/sync-typeshed.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/misc/sync-typeshed.py b/misc/sync-typeshed.py index 56bc1624d5d0..2dc6e230df00 100644 --- a/misc/sync-typeshed.py +++ b/misc/sync-typeshed.py @@ -179,9 +179,9 @@ def main() -> None: print("Created typeshed sync commit.") commits_to_cherry_pick = [ - "d25e4a9eb", # LiteralString reverts - "d132999ba", # sum reverts - "dd12a2d81", # ctypes reverts + "5c00e362d", # LiteralString reverts + "44bc98bd5", # sum reverts + "61a490091", # ctypes reverts ] for commit in commits_to_cherry_pick: try: