From 474d286169ccf9579a92e0703f5cba985d3e4284 Mon Sep 17 00:00:00 2001 From: EmmanuelNiyonshuti Date: Sun, 15 Nov 2026 17:08:23 +0200 Subject: [PATCH 1/6] drop support for py3.10 --- .github/workflows/autodeps.yml | 4 +- .github/workflows/ci.yml | 18 +++---- .pre-commit-config.yaml | 2 +- README.rst | 2 +- docs/source/conf.py | 24 +++------ docs/source/index.rst | 2 +- docs/source/reference-core.rst | 39 -------------- pyproject.toml | 8 ++- src/trio/_abc.py | 4 +- src/trio/_channel.py | 19 ++----- src/trio/_core/_asyncgens.py | 14 ++--- src/trio/_core/_entry_queue.py | 13 +++-- src/trio/_core/_exceptions.py | 3 +- src/trio/_core/_generated_run.py | 5 +- src/trio/_core/_ki.py | 3 +- src/trio/_core/_run.py | 44 ++++++++------- src/trio/_core/_tests/test_asyncgen.py | 6 +-- .../_core/_tests/test_exceptiongroup_gc.py | 21 ++++---- src/trio/_core/_tests/test_guest_mode.py | 8 +-- src/trio/_core/_tests/test_instrumentation.py | 8 +-- src/trio/_core/_tests/test_run.py | 54 ++++++++----------- src/trio/_core/_tests/test_thread_cache.py | 6 +-- src/trio/_core/_traps.py | 4 +- src/trio/_core/_unbounded_queue.py | 5 +- src/trio/_core/_windows_cffi.py | 4 +- src/trio/_dtls.py | 7 ++- src/trio/_highlevel_open_tcp_listeners.py | 3 -- src/trio/_highlevel_open_tcp_stream.py | 4 -- src/trio/_highlevel_serve_listeners.py | 6 +-- src/trio/_highlevel_ssl_helpers.py | 4 +- src/trio/_path.py | 3 +- src/trio/_signals.py | 3 +- src/trio/_socket.py | 4 +- src/trio/_ssl.py | 16 ++++-- src/trio/_subprocess.py | 15 ++---- src/trio/_tests/pytest_plugin.py | 4 +- src/trio/_tests/test_channel.py | 5 -- src/trio/_tests/test_dtls.py | 4 +- src/trio/_tests/test_exports.py | 4 +- src/trio/_tests/test_highlevel_generic.py | 6 +-- .../test_highlevel_open_tcp_listeners.py | 4 -- .../_tests/test_highlevel_open_tcp_stream.py | 4 -- .../_tests/test_highlevel_serve_listeners.py | 8 +-- src/trio/_tests/test_highlevel_ssl_helpers.py | 4 +- src/trio/_tests/test_repl.py | 4 -- src/trio/_tests/test_signals.py | 4 +- src/trio/_tests/test_ssl.py | 10 ++-- src/trio/_tests/test_subprocess.py | 4 +- src/trio/_tests/test_testing_raisesgroup.py | 3 -- src/trio/_tests/test_threads.py | 12 ++--- src/trio/_tests/test_util.py | 20 +------ src/trio/_threads.py | 16 +++--- src/trio/_timeouts.py | 4 +- src/trio/_util.py | 23 ++++---- src/trio/testing/_check_streams.py | 3 -- src/trio/testing/_fake_net.py | 8 +-- src/trio/testing/_raises_group.py | 4 -- tox.ini | 4 +- 58 files changed, 201 insertions(+), 346 deletions(-) diff --git a/.github/workflows/autodeps.yml b/.github/workflows/autodeps.yml index adc407dda5..fb73ad31a7 100644 --- a/.github/workflows/autodeps.yml +++ b/.github/workflows/autodeps.yml @@ -26,13 +26,13 @@ jobs: - name: Setup python uses: actions/setup-python@v6 with: - python-version: "3.10" + python-version: "3.11" - name: Bump dependencies run: | python -m pip install -U pip pre-commit python -m pip install -r test-requirements.txt - uv pip compile --universal --python-version=3.10 --upgrade test-requirements.in -o test-requirements.txt + uv pip compile --universal --python-version=3.11 --upgrade test-requirements.in -o test-requirements.txt uv pip compile --universal --python-version=3.11 --upgrade docs-requirements.in -o docs-requirements.txt pre-commit autoupdate --jobs 0 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ad39592c88..679fde7ae0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -168,18 +168,18 @@ jobs: strategy: fail-fast: false matrix: - python: ['3.10', '3.11', '3.12', '3.13', '3.14', '3.14t', '3.15', '3.15t'] + python: ['3.11', '3.12', '3.13', '3.14', '3.14t', '3.15', '3.15t'] arch: ['x86', 'x64'] lsp: [''] lsp_extract_file: [''] extra_name: [''] include: - - python: '3.10' + - python: '3.11' arch: 'x64' lsp: 'https://raw.githubusercontent.com/python-trio/trio-ci-assets/master/komodia-based-vpn-setup.zip' lsp_extract_file: 'komodia-based-vpn-setup.exe' extra_name: ', with Komodia LSP' - - python: '3.10' + - python: '3.11' arch: 'x64' lsp: 'https://www.proxifier.com/download/legacy/ProxifierSetup342.exe' lsp_extract_file: '' @@ -243,7 +243,7 @@ jobs: strategy: fail-fast: false matrix: - python: ['pypy-3.11', '3.10', '3.11', '3.12', '3.13', '3.14', '3.14t', '3.15', '3.15t'] + python: ['pypy-3.11', '3.11', '3.12', '3.13', '3.14', '3.14t', '3.15', '3.15t'] check_formatting: ['0'] no_test_requirements: ['0'] extra_name: [''] @@ -252,7 +252,7 @@ jobs: check_formatting: '1' extra_name: ', check formatting' # separate test run that doesn't install test-requirements.txt - - python: '3.10' + - python: '3.11' no_test_requirements: '1' extra_name: ', no test-requirements' continue-on-error: >- @@ -288,7 +288,7 @@ jobs: if: matrix.check_formatting == '1' uses: actions/setup-python@v6 with: - python-version: '3.10' + python-version: '3.11' cache: pip cache-dependency-path: test-requirements.txt allow-prereleases: true @@ -321,7 +321,7 @@ jobs: strategy: fail-fast: false matrix: - python: ['pypy-3.11', '3.10', '3.11', '3.12', '3.13', '3.14', '3.14t', '3.15', '3.15t'] + python: ['pypy-3.11', '3.11', '3.12', '3.13', '3.14', '3.14t', '3.15', '3.15t'] continue-on-error: >- ${{ ( @@ -412,12 +412,10 @@ jobs: include: # Cython 2 supports 3.10 and 3.11 and Cython 3 supports all versions we do, # so test both the lowest and higher version for both - - python: '3.10' - cython: '<3' - python: '3.11' cython: '<3' # TODO: technically we should pin cython versions - - python: '3.10' + - python: '3.11' cython: '>=3' - python: '3.15' cython: '>=3' diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 63b2f1c292..8d097dea9a 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -76,7 +76,7 @@ repos: name: uv pip-compile test-requirements.in args: [ "--universal", - "--python-version=3.10", + "--python-version=3.11", "test-requirements.in", "-o", "test-requirements.txt"] diff --git a/README.rst b/README.rst index e29f9035f7..041b7e91a7 100644 --- a/README.rst +++ b/README.rst @@ -92,7 +92,7 @@ demonstration of implementing the "Happy Eyeballs" algorithm in an older library versus Trio. **Cool, but will it work on my system?** Probably! As long as you have -some kind of Python 3.10-or-better (CPython or `currently maintained versions of +some kind of Python 3.11-or-better (CPython or `currently maintained versions of PyPy3 `__ are both fine), and are using Linux, macOS, Windows, or FreeBSD, then Trio will work. Other environments might work too, but those diff --git a/docs/source/conf.py b/docs/source/conf.py index eb278bf65f..10a651a494 100755 --- a/docs/source/conf.py +++ b/docs/source/conf.py @@ -25,9 +25,7 @@ from pathlib import Path from typing import TYPE_CHECKING, cast -if sys.version_info >= (3, 11): - from sphinx.util.inventory import _InventoryItem - +from sphinx.util.inventory import _InventoryItem from sphinx.util.logging import getLogger if TYPE_CHECKING: @@ -274,20 +272,12 @@ def add_mapping( assert isinstance(inventory, dict) inventory = cast("Inventory", inventory) - if sys.version_info >= (3, 11): - inventory[f"py:{reftype}"][f"{target}"] = _InventoryItem( - project_name="Python", - project_version=version, - uri=f"https://docs.python.org/{url_version}/library/{library}.html/{obj}", - display_name="-", - ) - else: - inventory[f"py:{reftype}"][f"{target}"] = ( - "Python", - version, - f"https://docs.python.org/{url_version}/library/{library}.html/{obj}", - "-", - ) + inventory[f"py:{reftype}"][f"{target}"] = _InventoryItem( + project_name="Python", + project_version=version, + uri=f"https://docs.python.org/{url_version}/library/{library}.html/{obj}", + display_name="-", + ) # This has been removed in Py3.12, so add a link to the 3.11 version with deprecation warnings. add_mapping("method", "pathlib", "Path.link_to", "3.11") diff --git a/docs/source/index.rst b/docs/source/index.rst index 1744f91bdd..5f901ad268 100644 --- a/docs/source/index.rst +++ b/docs/source/index.rst @@ -45,7 +45,7 @@ Vital statistics: * Supported environments: We test on - - Python: 3.10+ (CPython and PyPy) + - Python: 3.11+ (CPython and PyPy) - Windows, macOS, Linux (glibc and musl), FreeBSD Other environments might also work; give it a try and see. diff --git a/docs/source/reference-core.rst b/docs/source/reference-core.rst index ee4468ce6d..8c4b07b5c6 100644 --- a/docs/source/reference-core.rst +++ b/docs/source/reference-core.rst @@ -773,45 +773,6 @@ If you want to reraise exceptions, or raise new ones, you can do so, but be awar exceptions raised in ``except*`` sections will be raised together in a new exception group. -But what if you can't use Python 3.11, and therefore ``except*``, just yet? -The same exceptiongroup_ library which backports `ExceptionGroup` also lets -you approximate this behavior with exception handler callbacks: - -.. code-block:: python - - from exceptiongroup import catch - - def handle_keyerrors(excgroup): - for exc in excgroup.exceptions: - ... # handle each KeyError - - def handle_indexerrors(excgroup): - for exc in excgroup.exceptions: - ... # handle each IndexError - - with catch({ - KeyError: handle_keyerrors, - IndexError: handle_indexerrors - }): - async with trio.open_nursery() as nursery: - nursery.start_soon(broken1) - nursery.start_soon(broken2) - -The semantics for the handler functions are equal to ``except*`` blocks, except for -setting local variables. If you need to set local variables, you need to declare them -inside the handler function(s) with the ``nonlocal`` keyword: - -.. code-block:: python - - def handle_keyerrors(excgroup): - nonlocal myflag - myflag = True - - myflag = False - with catch({KeyError: handle_keyerrors}): - async with trio.open_nursery() as nursery: - nursery.start_soon(broken1) - .. _handling_exception_groups: Designing for multiple errors diff --git a/pyproject.toml b/pyproject.toml index 8ebfa12ee6..e8ac1e919a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -26,7 +26,6 @@ classifiers = [ "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: Python :: Implementation :: PyPy", "Programming Language :: Python :: 3 :: Only", - "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", @@ -35,7 +34,7 @@ classifiers = [ "Topic :: System :: Networking", "Typing :: Typed", ] -requires-python = ">=3.10" +requires-python = ">=3.11" dependencies = [ # attrs 19.2.0 adds `eq` option to decorators # attrs 20.1.0 adds @frozen @@ -50,7 +49,6 @@ dependencies = [ # cffi 1.14 fixes memory leak inside ffi.getwinerror() # cffi is required on Windows, except on PyPy where it is built-in "cffi>=1.14; os_name == 'nt' and implementation_name != 'pypy'", - "exceptiongroup; python_version < '3.11'", ] dynamic = ["version"] @@ -195,7 +193,7 @@ combine-as-imports = true fixture-parentheses = false [tool.mypy] -python_version = "3.10" +python_version = "3.11" files = ["src/trio/", "docs/source/*.py"] # Be flexible about dependencies that don't have stubs yet (like pytest) @@ -222,7 +220,7 @@ disallow_untyped_defs = true check_untyped_defs = true [tool.pyright] -pythonVersion = "3.10" +pythonVersion = "3.11" reportUnnecessaryTypeIgnoreComment = true typeCheckingMode = "strict" diff --git a/src/trio/_abc.py b/src/trio/_abc.py index 2036f297f9..f737b1148c 100644 --- a/src/trio/_abc.py +++ b/src/trio/_abc.py @@ -2,15 +2,13 @@ import socket from abc import ABC, abstractmethod -from typing import TYPE_CHECKING, Generic, Literal, TypeVar +from typing import TYPE_CHECKING, Generic, Literal, Self, TypeVar import trio if TYPE_CHECKING: from types import TracebackType - from typing_extensions import Self - # both of these introduce circular imports if outside a TYPE_CHECKING guard from ._socket import SocketType from .lowlevel import Task diff --git a/src/trio/_channel.py b/src/trio/_channel.py index c785434e7a..3e609249da 100644 --- a/src/trio/_channel.py +++ b/src/trio/_channel.py @@ -6,10 +6,7 @@ from contextlib import AbstractAsyncContextManager, asynccontextmanager from functools import wraps from math import inf -from typing import ( - TYPE_CHECKING, - Generic, -) +from typing import TYPE_CHECKING, Generic, ParamSpec, Self import attrs from outcome import Error, Value @@ -25,14 +22,9 @@ raise_single_exception_from_group, ) -if sys.version_info < (3, 11): - from exceptiongroup import BaseExceptionGroup - if TYPE_CHECKING: from types import TracebackType - from typing_extensions import ParamSpec, Self - P = ParamSpec("P") elif "sphinx.ext.autodoc" in sys.modules: # P needs to exist for Sphinx to parse the type hints successfully. @@ -583,11 +575,10 @@ async def context_manager( except MultipleExceptionError: # In case user has except* we make it possible for them to handle the # exceptions. - if sys.version_info >= (3, 11): - eg.add_note( - "Encountered exception during cleanup of generator object, as " - "well as exception in the contextmanager body - unable to unwrap." - ) + eg.add_note( + "Encountered exception during cleanup of generator object, as " + "well as exception in the contextmanager body - unable to unwrap." + ) raise eg from None diff --git a/src/trio/_core/_asyncgens.py b/src/trio/_core/_asyncgens.py index fea41e0e4d..5cdca35f64 100644 --- a/src/trio/_core/_asyncgens.py +++ b/src/trio/_core/_asyncgens.py @@ -4,7 +4,7 @@ import sys import warnings import weakref -from typing import TYPE_CHECKING, NoReturn, TypeVar +from typing import TYPE_CHECKING, Never, TypeVar import attrs @@ -23,8 +23,8 @@ _P = ParamSpec("_P") - _WEAK_ASYNC_GEN_SET = weakref.WeakSet[AsyncGeneratorType[object, NoReturn]] - _ASYNC_GEN_SET = set[AsyncGeneratorType[object, NoReturn]] + _WEAK_ASYNC_GEN_SET = weakref.WeakSet[AsyncGeneratorType[object, Never]] + _ASYNC_GEN_SET = set[AsyncGeneratorType[object, Never]] else: _WEAK_ASYNC_GEN_SET = weakref.WeakSet _ASYNC_GEN_SET = set @@ -66,7 +66,7 @@ class AsyncGenerators: prev_hooks: sys._asyncgen_hooks = attrs.field(init=False) def install_hooks(self, runner: _run.Runner) -> None: - def firstiter(agen: AsyncGeneratorType[object, NoReturn]) -> None: + def firstiter(agen: AsyncGeneratorType[object, Never]) -> None: if hasattr(_run.GLOBAL_RUN_CONTEXT, "task"): self.alive.add(agen) else: @@ -81,7 +81,7 @@ def firstiter(agen: AsyncGeneratorType[object, NoReturn]) -> None: self.prev_hooks.firstiter(agen) def finalize_in_trio_context( - agen: AsyncGeneratorType[object, NoReturn], + agen: AsyncGeneratorType[object, Never], agen_name: str, ) -> None: try: @@ -99,7 +99,7 @@ def finalize_in_trio_context( self.trailing_needs_finalize.add(agen) @_core.enable_ki_protection - def finalizer(agen: AsyncGeneratorType[object, NoReturn]) -> None: + def finalizer(agen: AsyncGeneratorType[object, Never]) -> None: try: self.foreign.remove(id(agen)) except KeyError: @@ -222,7 +222,7 @@ def close(self) -> None: async def _finalize_one( self, - agen: AsyncGeneratorType[object, NoReturn], + agen: AsyncGeneratorType[object, Never], name: object, ) -> None: try: diff --git a/src/trio/_core/_entry_queue.py b/src/trio/_core/_entry_queue.py index 988b45ca00..ea601a9693 100644 --- a/src/trio/_core/_entry_queue.py +++ b/src/trio/_core/_entry_queue.py @@ -3,7 +3,7 @@ import threading from collections import deque from collections.abc import Callable -from typing import TYPE_CHECKING, NoReturn +from typing import TYPE_CHECKING, Never, TypeVarTuple import attrs @@ -12,7 +12,6 @@ from ._wakeup_socketpair import WakeupSocketpair if TYPE_CHECKING: - from typing_extensions import TypeVarTuple, Unpack PosArgsT = TypeVarTuple("PosArgsT") @@ -67,7 +66,7 @@ def run_cb(job: Job) -> None: async def kill_everything( # noqa: RUF029 # await not used exc: BaseException, - ) -> NoReturn: + ) -> Never: raise exc try: @@ -129,8 +128,8 @@ def size(self) -> int: def run_sync_soon( self, - sync_fn: Callable[[Unpack[PosArgsT]], object], - *args: Unpack[PosArgsT], + sync_fn: Callable[[*PosArgsT], object], + *args: *PosArgsT, idempotent: bool = False, ) -> None: with self.lock: @@ -173,8 +172,8 @@ class TrioToken(metaclass=NoPublicConstructor): def run_sync_soon( self, - sync_fn: Callable[[Unpack[PosArgsT]], object], - *args: Unpack[PosArgsT], + sync_fn: Callable[[*PosArgsT], object], + *args: *PosArgsT, idempotent: bool = False, ) -> None: """Schedule a call to ``sync_fn(*args)`` to occur in the context of a diff --git a/src/trio/_core/_exceptions.py b/src/trio/_core/_exceptions.py index f24e56b5e6..e0961b6893 100644 --- a/src/trio/_core/_exceptions.py +++ b/src/trio/_core/_exceptions.py @@ -1,7 +1,7 @@ from __future__ import annotations from functools import partial -from typing import TYPE_CHECKING, Literal, TypeAlias +from typing import TYPE_CHECKING, Literal, Self, TypeAlias import attrs @@ -10,7 +10,6 @@ if TYPE_CHECKING: from collections.abc import Callable - from typing_extensions import Self CancelReasonLiteral: TypeAlias = Literal[ "KeyboardInterrupt", diff --git a/src/trio/_core/_generated_run.py b/src/trio/_core/_generated_run.py index 4da520109b..107442c673 100644 --- a/src/trio/_core/_generated_run.py +++ b/src/trio/_core/_generated_run.py @@ -13,7 +13,6 @@ from collections.abc import Awaitable, Callable import outcome - from typing_extensions import Unpack from .._abc import Clock from ._entry_queue import TrioToken @@ -128,8 +127,8 @@ def reschedule(task: Task, next_send: outcome.Outcome[object] = _NO_SEND) -> Non @enable_ki_protection def spawn_system_task( - async_fn: Callable[[Unpack[PosArgT]], Awaitable[object]], - *args: Unpack[PosArgT], + async_fn: Callable[[*PosArgT], Awaitable[object]], + *args: *PosArgT, name: object = None, context: contextvars.Context | None = None, ) -> Task: diff --git a/src/trio/_core/_ki.py b/src/trio/_core/_ki.py index fa3369d56d..00895ed1ca 100644 --- a/src/trio/_core/_ki.py +++ b/src/trio/_core/_ki.py @@ -3,7 +3,7 @@ import signal import sys import weakref -from typing import TYPE_CHECKING, Generic, Protocol, TypeGuard, TypeVar +from typing import TYPE_CHECKING, Generic, Protocol, Self, TypeGuard, TypeVar import attrs @@ -14,7 +14,6 @@ import types from collections.abc import Callable - from typing_extensions import Self # In ordinary single-threaded Python code, when you hit control-C, it raises # an exception and automatically does all the regular unwinding stuff. # diff --git a/src/trio/_core/_run.py b/src/trio/_core/_run.py index ddd4ea7ee2..339300ac9f 100644 --- a/src/trio/_core/_run.py +++ b/src/trio/_core/_run.py @@ -18,8 +18,10 @@ TYPE_CHECKING, Any, Final, - NoReturn, + Never, Protocol, + Self, + TypeVarTuple, cast, overload, ) @@ -57,10 +59,6 @@ wait_task_rescheduled, ) -if sys.version_info < (3, 11): - from exceptiongroup import BaseExceptionGroup - - if TYPE_CHECKING: import contextvars import types @@ -75,7 +73,7 @@ # for some strange reason Sphinx works with outcome.Outcome, but not Outcome, in # start_guest_run. Same with types.FrameType in iter_await_frames - from typing_extensions import Self, TypeVar, TypeVarTuple, Unpack + from typing_extensions import TypeVar PosArgT = TypeVarTuple("PosArgT") StatusT = TypeVar("StatusT", default=None) @@ -156,7 +154,7 @@ def _count_context_run_tb_frames() -> int: """ - def function_with_unique_name_xyzzy() -> NoReturn: + def function_with_unique_name_xyzzy() -> Never: try: 1 / 0 # noqa: B018 # We need a ZeroDivisionError to fire except ZeroDivisionError: @@ -1126,7 +1124,7 @@ async def __aexit__( # make sure these raise errors in static analysis if called if not TYPE_CHECKING: - def __enter__(self) -> NoReturn: + def __enter__(self) -> Never: raise RuntimeError( "use 'async with open_nursery(...)', not 'with open_nursery(...)'", ) @@ -1136,7 +1134,7 @@ def __exit__( exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None, - ) -> NoReturn: # pragma: no cover + ) -> Never: # pragma: no cover raise AssertionError("Never called, but should be defined") @@ -1339,8 +1337,8 @@ def aborted(raise_cancel: _core.RaiseCancelT) -> Abort: def start_soon( self, - async_fn: Callable[[Unpack[PosArgT]], Awaitable[object]], - *args: Unpack[PosArgT], + async_fn: Callable[[*PosArgT], Awaitable[object]], + *args: *PosArgT, name: object = None, ) -> None: """Creates a child task, scheduling ``await async_fn(*args)``. @@ -1650,7 +1648,7 @@ def _attempt_delivery_of_any_pending_cancel(self) -> None: reason = self._cancel_status._scope._cancel_reason - def raise_cancel() -> NoReturn: + def raise_cancel() -> Never: if reason is None: raise Cancelled._create(source="unknown", reason="misnesting") else: @@ -1667,7 +1665,7 @@ def _attempt_delivery_of_pending_ki(self) -> None: if self._abort_func is None: return - def raise_cancel() -> NoReturn: + def raise_cancel() -> Never: self._runner.ki_pending = False raise KeyboardInterrupt @@ -1932,8 +1930,8 @@ def reschedule( def spawn_impl( self, - async_fn: Callable[[Unpack[PosArgT]], Awaitable[object]], - args: tuple[Unpack[PosArgT]], + async_fn: Callable[[*PosArgT], Awaitable[object]], + args: tuple[*PosArgT], nursery: Nursery | None, name: object, *, @@ -2076,8 +2074,8 @@ def task_exited(self, task: Task, outcome: Outcome[object]) -> None: @_public def spawn_system_task( self, - async_fn: Callable[[Unpack[PosArgT]], Awaitable[object]], - *args: Unpack[PosArgT], + async_fn: Callable[[*PosArgT], Awaitable[object]], + *args: *PosArgT, name: object = None, context: contextvars.Context | None = None, ) -> Task: @@ -2143,8 +2141,8 @@ def spawn_system_task( async def init( self, - async_fn: Callable[[Unpack[PosArgT]], Awaitable[object]], - args: tuple[Unpack[PosArgT]], + async_fn: Callable[[*PosArgT], Awaitable[object]], + args: tuple[*PosArgT], ) -> None: # run_sync_soon task runs here: async with open_nursery() as run_sync_soon_nursery: @@ -2422,8 +2420,8 @@ def setup_runner( def run( - async_fn: Callable[[Unpack[PosArgT]], Awaitable[RetT]], - *args: Unpack[PosArgT], + async_fn: Callable[[*PosArgT], Awaitable[RetT]], + *args: *PosArgT, clock: Clock | None = None, instruments: Sequence[Instrument] = (), restrict_keyboard_interrupt_to_checkpoints: bool = False, @@ -2712,8 +2710,8 @@ def my_done_callback(run_outcome): @enable_ki_protection def unrolled_run( runner: Runner, - async_fn: Callable[[Unpack[PosArgT]], Awaitable[object]], - args: tuple[Unpack[PosArgT]], + async_fn: Callable[[*PosArgT], Awaitable[object]], + args: tuple[*PosArgT], host_uses_signal_set_wakeup_fd: bool = False, ) -> Generator[float, EventResult, None]: __tracebackhide__ = True diff --git a/src/trio/_core/_tests/test_asyncgen.py b/src/trio/_core/_tests/test_asyncgen.py index a5c27ed5fb..8705707c44 100644 --- a/src/trio/_core/_tests/test_asyncgen.py +++ b/src/trio/_core/_tests/test_asyncgen.py @@ -5,7 +5,7 @@ import weakref from math import inf from types import AsyncGeneratorType -from typing import TYPE_CHECKING, NoReturn +from typing import TYPE_CHECKING, Never import pytest @@ -306,12 +306,12 @@ async def awaits_after_yield() -> AsyncGenerator[int, None]: def test_delegation_to_existing_hooks() -> None: record = [] - def my_firstiter(agen: AsyncGenerator[object, NoReturn]) -> None: + def my_firstiter(agen: AsyncGenerator[object, Never]) -> None: assert isinstance(agen, AsyncGeneratorType) assert agen.ag_frame is not None record.append("firstiter " + agen.ag_frame.f_locals["arg"]) - def my_finalizer(agen: AsyncGenerator[object, NoReturn]) -> None: + def my_finalizer(agen: AsyncGenerator[object, Never]) -> None: assert isinstance(agen, AsyncGeneratorType) assert agen.ag_frame is not None record.append("finalizer " + agen.ag_frame.f_locals["arg"]) diff --git a/src/trio/_core/_tests/test_exceptiongroup_gc.py b/src/trio/_core/_tests/test_exceptiongroup_gc.py index e8ffa62945..f83bb4e1c2 100644 --- a/src/trio/_core/_tests/test_exceptiongroup_gc.py +++ b/src/trio/_core/_tests/test_exceptiongroup_gc.py @@ -3,7 +3,7 @@ import gc import sys from traceback import extract_tb -from typing import TYPE_CHECKING, NoReturn +from typing import TYPE_CHECKING, Never import pytest @@ -13,31 +13,28 @@ from collections.abc import Callable from types import TracebackType -if sys.version_info < (3, 11): - from exceptiongroup import ExceptionGroup - -def raiser1() -> NoReturn: +def raiser1() -> Never: raiser1_2() -def raiser1_2() -> NoReturn: +def raiser1_2() -> Never: raiser1_3() -def raiser1_3() -> NoReturn: +def raiser1_3() -> Never: raise ValueError("raiser1_string") -def raiser2() -> NoReturn: +def raiser2() -> Never: raiser2_2() -def raiser2_2() -> NoReturn: +def raiser2_2() -> Never: raise KeyError("raiser2_string") -def get_exc(raiser: Callable[[], NoReturn]) -> Exception: +def get_exc(raiser: Callable[[], Never]) -> Exception: try: raiser() except Exception as exc: @@ -45,7 +42,7 @@ def get_exc(raiser: Callable[[], NoReturn]) -> Exception: raise AssertionError("raiser should always raise") # pragma: no cover -def get_tb(raiser: Callable[[], NoReturn]) -> TracebackType | None: +def get_tb(raiser: Callable[[], Never]) -> TracebackType | None: return get_exc(raiser).__traceback__ @@ -85,7 +82,7 @@ def test_ExceptionGroup_catch_doesnt_create_cyclic_garbage() -> None: gc.collect() old_flags = gc.get_debug() - def make_multi() -> NoReturn: + def make_multi() -> Never: raise ExceptionGroup("", [get_exc(raiser1), get_exc(raiser2)]) try: diff --git a/src/trio/_core/_tests/test_guest_mode.py b/src/trio/_core/_tests/test_guest_mode.py index 7acbc0f082..8d0a903dba 100644 --- a/src/trio/_core/_tests/test_guest_mode.py +++ b/src/trio/_core/_tests/test_guest_mode.py @@ -16,7 +16,7 @@ from math import inf from typing import ( TYPE_CHECKING, - NoReturn, + Never, TypeAlias, TypeVar, cast, @@ -123,7 +123,7 @@ async def trio_return(in_host: InHost) -> str: assert trivial_guest_run(trio_return) == "ok" - async def trio_fail(in_host: InHost) -> NoReturn: + async def trio_fail(in_host: InHost) -> Never: raise KeyError("whoopsiedaisy") with pytest.raises(KeyError, match="whoopsiedaisy"): @@ -178,7 +178,7 @@ async def early_task() -> None: assert set(record) == {"system task ran", "main task ran", "run_sync_soon cb ran"} class BadClock(Clock): - def start_clock(self) -> NoReturn: + def start_clock(self) -> Never: raise ValueError("whoops") def current_time(self) -> float: @@ -645,7 +645,7 @@ async def trio_main(in_host: InHost) -> None: # Also check chaining in the case where KI is injected after main exits final_exc = KeyError("whoa") - async def trio_main_raising(in_host: InHost) -> NoReturn: + async def trio_main_raising(in_host: InHost) -> Never: in_host(partial(signal.raise_signal, signal.SIGINT)) raise final_exc diff --git a/src/trio/_core/_tests/test_instrumentation.py b/src/trio/_core/_tests/test_instrumentation.py index 60c54307ee..f6f3c00e6b 100644 --- a/src/trio/_core/_tests/test_instrumentation.py +++ b/src/trio/_core/_tests/test_instrumentation.py @@ -1,6 +1,6 @@ from __future__ import annotations -from typing import TYPE_CHECKING, NoReturn +from typing import TYPE_CHECKING, Never import attrs import pytest @@ -184,7 +184,7 @@ def test_instruments_crash(caplog: pytest.LogCaptureFixture) -> None: record = [] class BrokenInstrument(_abc.Instrument): - def task_scheduled(self, task: Task) -> NoReturn: + def task_scheduled(self, task: Task) -> Never: record.append("scheduled") raise ValueError("oops") @@ -249,11 +249,11 @@ async def main() -> None: def test_instrument_that_raises_on_getattr() -> None: class EvilInstrument(_abc.Instrument): - def task_exited(self, task: Task) -> NoReturn: + def task_exited(self, task: Task) -> Never: raise AssertionError("this should never happen") # pragma: no cover @property - def after_run(self) -> NoReturn: + def after_run(self) -> Never: raise ValueError("oops") async def main() -> None: diff --git a/src/trio/_core/_tests/test_run.py b/src/trio/_core/_tests/test_run.py index e49e2e6ed2..5d16f248b0 100644 --- a/src/trio/_core/_tests/test_run.py +++ b/src/trio/_core/_tests/test_run.py @@ -16,7 +16,7 @@ suppress, ) from math import inf, nan -from typing import TYPE_CHECKING, NoReturn, TypeVar +from typing import TYPE_CHECKING, Never, TypeVar from unittest import mock import outcome @@ -50,9 +50,6 @@ Generator, ) -if sys.version_info < (3, 11): - from exceptiongroup import BaseExceptionGroup, ExceptionGroup - T = TypeVar("T") @@ -95,7 +92,7 @@ async def trivial2(x: T) -> T: def test_initial_task_error() -> None: - async def main(x: object) -> NoReturn: + async def main(x: object) -> Never: raise ValueError(x) with pytest.raises(ValueError, match=r"^17$") as excinfo: @@ -140,7 +137,7 @@ async def test_nursery_main_block_error_basic() -> None: async def test_child_crash_basic() -> None: my_exc = ValueError("uh oh") - async def erroring() -> NoReturn: + async def erroring() -> Never: raise my_exc with pytest.RaisesGroup(pytest.RaisesExc(check=lambda e: e is my_exc)): @@ -177,7 +174,7 @@ async def looper() -> None: print("looper cancelled") looper_record.append("cancelled") - async def crasher() -> NoReturn: + async def crasher() -> Never: raise ValueError("argh") async def main() -> None: @@ -194,10 +191,10 @@ async def main() -> None: def test_main_and_task_both_crash() -> None: # If main crashes and there's also a task crash, then we get both in an # ExceptionGroup - async def crasher() -> NoReturn: + async def crasher() -> Never: raise ValueError - async def main() -> NoReturn: + async def main() -> Never: async with _core.open_nursery() as nursery: nursery.start_soon(crasher) raise KeyError @@ -207,7 +204,7 @@ async def main() -> NoReturn: def test_two_child_crashes() -> None: - async def crasher(etype: type[Exception]) -> NoReturn: + async def crasher(etype: type[Exception]) -> Never: raise etype async def main() -> None: @@ -220,7 +217,7 @@ async def main() -> None: async def test_child_crash_wakes_parent() -> None: - async def crasher() -> NoReturn: + async def crasher() -> Never: raise ValueError("this is a crash") with pytest.RaisesGroup(pytest.RaisesExc(ValueError, match="^this is a crash$")): @@ -457,7 +454,7 @@ async def test_cancel_edge_cases() -> None: async def test_cancel_scope_exceptiongroup_filtering() -> None: - async def crasher() -> NoReturn: + async def crasher() -> Never: raise KeyError # This is outside the outer scope, so all the Cancelled @@ -1084,7 +1081,7 @@ async def system_task(x: int) -> None: # intentionally make a system task crash def test_system_task_crash() -> None: - async def crasher() -> NoReturn: + async def crasher() -> Never: raise KeyError async def main() -> None: @@ -1096,10 +1093,10 @@ async def main() -> None: def test_system_task_crash_ExceptionGroup() -> None: - async def crasher1() -> NoReturn: + async def crasher1() -> Never: raise KeyError - async def crasher2() -> NoReturn: + async def crasher2() -> Never: raise ValueError async def system_task() -> None: @@ -1158,7 +1155,7 @@ async def main() -> None: def test_system_task_crash_KeyboardInterrupt() -> None: - async def ki() -> NoReturn: + async def ki() -> Never: raise KeyboardInterrupt async def main() -> None: @@ -1395,7 +1392,7 @@ async def inner() -> None: async def test_nursery_exception_chaining_doesnt_make_context_loops() -> None: - async def crasher() -> NoReturn: + async def crasher() -> Never: raise KeyError # the ExceptionGroup should not have the KeyError or ValueError as context @@ -2195,7 +2192,7 @@ async def test_nursery_explicit_exception() -> None: async def test_nursery_stop_iteration() -> None: - async def fail() -> NoReturn: + async def fail() -> Never: raise ValueError with pytest.RaisesGroup(StopIteration, ValueError): @@ -2262,7 +2259,7 @@ async def __anext__(self) -> list[int]: async def test_traceback_frame_removal() -> None: - async def my_child_task() -> NoReturn: + async def my_child_task() -> Never: raise KeyError() def check_traceback(exc: KeyError) -> bool: @@ -2614,7 +2611,7 @@ async def do_a_cancel() -> None: cscope.cancel() await sleep_forever() - async def crasher() -> NoReturn: + async def crasher() -> Never: raise ValueError("this is a crash") old_flags = gc.get_debug() @@ -2651,7 +2648,7 @@ async def test_cancel_scope_exit_doesnt_create_cyclic_garbage() -> None: # https://github.com/python-trio/trio/pull/2063 gc.collect() - async def crasher() -> NoReturn: + async def crasher() -> Never: raise ValueError("this is a crash") old_flags = gc.get_debug() @@ -2767,7 +2764,7 @@ def test_setting_strict_exception_groups( setting of strict_exception_groups. """ - async def raise_error() -> NoReturn: + async def raise_error() -> Never: raise RuntimeError("test error") async def main() -> None: @@ -2806,7 +2803,7 @@ async def test_nursery_collapse(strict: bool | None) -> None: depending on strict_exception_groups value when CancelledErrors are stripped from it. """ - async def raise_error() -> NoReturn: + async def raise_error() -> Never: raise RuntimeError("test error") # mypy requires explicit type for conditional expression @@ -2951,15 +2948,8 @@ async def spawn_tasks_in_old_nursery(task_status: _core.TaskStatus[None]) -> Non assert pytest.RaisesGroup(ValueError, ValueError).matches(excinfo.value.__cause__) -if sys.version_info >= (3, 11): - - def no_other_refs() -> list[object]: - return [] - -else: - - def no_other_refs() -> list[object]: - return [sys._getframe(1)] +def no_other_refs() -> list[object]: + return [] @pytest.mark.skipif( diff --git a/src/trio/_core/_tests/test_thread_cache.py b/src/trio/_core/_tests/test_thread_cache.py index 77d0cc6d5e..2f6bb5c890 100644 --- a/src/trio/_core/_tests/test_thread_cache.py +++ b/src/trio/_core/_tests/test_thread_cache.py @@ -7,7 +7,7 @@ import warnings from contextlib import contextmanager from queue import Queue -from typing import TYPE_CHECKING, NoReturn +from typing import TYPE_CHECKING, Never import pytest @@ -25,7 +25,7 @@ def test_thread_cache_basics() -> None: q: Queue[Outcome[object]] = Queue() - def fn() -> NoReturn: + def fn() -> Never: raise RuntimeError("hi") def deliver(outcome: Outcome[object]) -> None: @@ -185,7 +185,7 @@ def test_raise_in_deliver(capfd: pytest.CaptureFixture[str]) -> None: def track_threads() -> None: seen_threads.add(threading.current_thread()) - def deliver(_: object) -> NoReturn: + def deliver(_: object) -> Never: done.set() raise RuntimeError("don't do this") diff --git a/src/trio/_core/_traps.py b/src/trio/_core/_traps.py index 14f66af927..dba074d81e 100644 --- a/src/trio/_core/_traps.py +++ b/src/trio/_core/_traps.py @@ -11,7 +11,7 @@ TYPE_CHECKING, Any, Callable, - NoReturn, + Never, TypeAlias, cast, ) @@ -26,7 +26,7 @@ from ._run import Task -RaiseCancelT: TypeAlias = Callable[[], NoReturn] +RaiseCancelT: TypeAlias = Callable[[], Never] # This class object is used as a singleton. diff --git a/src/trio/_core/_unbounded_queue.py b/src/trio/_core/_unbounded_queue.py index b9e7974841..75e8491208 100644 --- a/src/trio/_core/_unbounded_queue.py +++ b/src/trio/_core/_unbounded_queue.py @@ -1,6 +1,6 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Generic, TypeVar +from typing import Generic, Self, TypeVar import attrs @@ -10,9 +10,6 @@ T = TypeVar("T") -if TYPE_CHECKING: - from typing_extensions import Self - @attrs.frozen class UnboundedQueueStatistics: diff --git a/src/trio/_core/_windows_cffi.py b/src/trio/_core/_windows_cffi.py index cafae17fa2..c8fcf5adfe 100644 --- a/src/trio/_core/_windows_cffi.py +++ b/src/trio/_core/_windows_cffi.py @@ -1,7 +1,7 @@ from __future__ import annotations import enum -from typing import TYPE_CHECKING, NewType, NoReturn, Protocol, TypeAlias, cast +from typing import TYPE_CHECKING, Never, NewType, Protocol, TypeAlias, cast if TYPE_CHECKING: import cffi @@ -294,7 +294,7 @@ def raise_winerror( *, filename: str | None = None, filename2: str | None = None, -) -> NoReturn: +) -> Never: # assert sys.platform == "win32" # TODO: make this work in MyPy # ... in the meanwhile, ffi.getwinerror() is undefined on non-Windows, necessitating the type # ignores. diff --git a/src/trio/_dtls.py b/src/trio/_dtls.py index a789038257..3043753151 100644 --- a/src/trio/_dtls.py +++ b/src/trio/_dtls.py @@ -17,7 +17,7 @@ import warnings import weakref from itertools import count -from typing import TYPE_CHECKING, Generic, TypeAlias, TypeVar +from typing import TYPE_CHECKING, Generic, Self, TypeAlias, TypeVar, TypeVarTuple from weakref import ReferenceType, WeakValueDictionary import attrs @@ -32,7 +32,6 @@ # See DTLSEndpoint.__init__ for why this is imported here from OpenSSL import SSL # noqa: TC004 - from typing_extensions import Self, TypeVarTuple, Unpack from trio._socket import AddressFormat from trio.socket import SocketType @@ -1272,8 +1271,8 @@ def _check_closed(self) -> None: async def serve( self, ssl_context: SSL.Context, - async_fn: Callable[[DTLSChannel, Unpack[PosArgsT]], Awaitable[object]], - *args: Unpack[PosArgsT], + async_fn: Callable[[DTLSChannel, *PosArgsT], Awaitable[object]], + *args: *PosArgsT, task_status: trio.TaskStatus[None] = trio.TASK_STATUS_IGNORED, ) -> None: """Listen for incoming connections, and spawn a handler for each using an diff --git a/src/trio/_highlevel_open_tcp_listeners.py b/src/trio/_highlevel_open_tcp_listeners.py index 023b2b240f..2c7b6179d2 100644 --- a/src/trio/_highlevel_open_tcp_listeners.py +++ b/src/trio/_highlevel_open_tcp_listeners.py @@ -12,9 +12,6 @@ if TYPE_CHECKING: from collections.abc import Awaitable, Callable -if sys.version_info < (3, 11): - from exceptiongroup import ExceptionGroup - # Default backlog size: # diff --git a/src/trio/_highlevel_open_tcp_stream.py b/src/trio/_highlevel_open_tcp_stream.py index 400bc52834..f4f9f120fb 100644 --- a/src/trio/_highlevel_open_tcp_stream.py +++ b/src/trio/_highlevel_open_tcp_stream.py @@ -1,6 +1,5 @@ from __future__ import annotations -import sys from contextlib import contextmanager, suppress from typing import TYPE_CHECKING @@ -13,9 +12,6 @@ from trio._socket import AddressFormat, _GetAddrInfoEntry -if sys.version_info < (3, 11): - from exceptiongroup import BaseExceptionGroup, ExceptionGroup - # Implementation of RFC 6555 "Happy eyeballs" # https://tools.ietf.org/html/rfc6555 diff --git a/src/trio/_highlevel_serve_listeners.py b/src/trio/_highlevel_serve_listeners.py index 008caaabea..9316a303fe 100644 --- a/src/trio/_highlevel_serve_listeners.py +++ b/src/trio/_highlevel_serve_listeners.py @@ -4,7 +4,7 @@ import logging import os from collections.abc import Awaitable, Callable -from typing import Any, NoReturn, TypeVar +from typing import Any, Never, TypeVar import trio @@ -40,7 +40,7 @@ async def _serve_one_listener( listener: trio.abc.Listener[StreamT], handler_nursery: trio.Nursery, handler: Handler[StreamT], -) -> NoReturn: +) -> Never: async with listener: while True: try: @@ -73,7 +73,7 @@ async def serve_listeners( # type: ignore[explicit-any] *, handler_nursery: trio.Nursery | None = None, task_status: trio.TaskStatus[list[ListenerT]] = trio.TASK_STATUS_IGNORED, -) -> NoReturn: +) -> Never: r"""Listen for incoming connections on ``listeners``, and for each one start a task running ``handler(stream)``. diff --git a/src/trio/_highlevel_ssl_helpers.py b/src/trio/_highlevel_ssl_helpers.py index 1239491a43..2379e1a4b9 100644 --- a/src/trio/_highlevel_ssl_helpers.py +++ b/src/trio/_highlevel_ssl_helpers.py @@ -1,7 +1,7 @@ from __future__ import annotations import ssl -from typing import TYPE_CHECKING, NoReturn, TypeVar +from typing import TYPE_CHECKING, Never, TypeVar import trio @@ -117,7 +117,7 @@ async def serve_ssl_over_tcp( task_status: trio.TaskStatus[ list[trio.SSLListener[SocketStream]] ] = trio.TASK_STATUS_IGNORED, -) -> NoReturn: +) -> Never: """Listen for incoming TCP connections, and for each one start a task running ``handler(stream)``. diff --git a/src/trio/_path.py b/src/trio/_path.py index ea571c9c01..60b9148806 100644 --- a/src/trio/_path.py +++ b/src/trio/_path.py @@ -13,6 +13,8 @@ ClassVar, Concatenate, Literal, + ParamSpec, + Self, TypeVar, overload, ) @@ -32,7 +34,6 @@ OpenBinaryModeWriting, OpenTextMode, ) - from typing_extensions import ParamSpec, Self P = ParamSpec("P") diff --git a/src/trio/_signals.py b/src/trio/_signals.py index 729c48ad4e..686a75ce46 100644 --- a/src/trio/_signals.py +++ b/src/trio/_signals.py @@ -3,7 +3,7 @@ import signal from collections import OrderedDict from contextlib import contextmanager -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, Self import trio @@ -13,7 +13,6 @@ from collections.abc import AsyncIterator, Callable, Generator, Iterable from types import FrameType - from typing_extensions import Self # Discussion of signal handling strategies: # diff --git a/src/trio/_socket.py b/src/trio/_socket.py index 5202e295ad..11f615b9b2 100644 --- a/src/trio/_socket.py +++ b/src/trio/_socket.py @@ -11,6 +11,8 @@ Any, Concatenate, Literal, + ParamSpec, + Self, SupportsIndex, TypeAlias, TypeVar, @@ -28,7 +30,7 @@ from collections.abc import Awaitable, Callable, Iterable from types import TracebackType - from typing_extensions import Buffer, ParamSpec, Self + from typing_extensions import Buffer from ._abc import HostnameResolver, SocketFactory diff --git a/src/trio/_ssl.py b/src/trio/_ssl.py index 7579f3445e..56e1dd41cb 100644 --- a/src/trio/_ssl.py +++ b/src/trio/_ssl.py @@ -4,7 +4,15 @@ import operator as _operator import ssl as _stdlib_ssl from enum import Enum as _Enum -from typing import TYPE_CHECKING, Any, ClassVar, Final as TFinal, Generic, TypeVar +from typing import ( + TYPE_CHECKING, + Any, + ClassVar, + Final as TFinal, + Generic, + TypeVar, + TypeVarTuple, +) import trio @@ -17,8 +25,6 @@ if TYPE_CHECKING: from collections.abc import Awaitable, Callable - from typing_extensions import TypeVarTuple, Unpack - Ts = TypeVarTuple("Ts") # General theory of operation: @@ -229,7 +235,7 @@ class _Once: def __init__( self, afn: Callable[[*Ts], Awaitable[object]], - *args: Unpack[Ts], + *args: *Ts, ) -> None: self._afn = afn self._args = args @@ -468,7 +474,7 @@ def _check_status(self) -> None: async def _retry( self, fn: Callable[[*Ts], T], - *args: Unpack[Ts], + *args: *Ts, ignore_want_read: bool = False, is_handshake: bool = False, ) -> T | None: diff --git a/src/trio/_subprocess.py b/src/trio/_subprocess.py index b384d18ffa..a3295d0a2b 100644 --- a/src/trio/_subprocess.py +++ b/src/trio/_subprocess.py @@ -15,6 +15,7 @@ Protocol, TypeAlias, TypedDict, + Unpack, overload, ) @@ -34,8 +35,6 @@ import signal from collections.abc import Awaitable, Callable, Iterable, Mapping, Sequence - from typing_extensions import Unpack - from ._abc import ReceiveStream, SendStream @@ -1120,17 +1119,11 @@ class UnixRunProcessMixin(TypedDict, total=False): # TODO: once https://github.com/python/mypy/issues/18692 is # fixed, move the `UnixRunProcessArgs` definition down. - if sys.version_info >= (3, 11): - UnixProcessArgs = UnixProcessArgs3_11 - - class UnixRunProcessArgs(UnixProcessArgs3_11, UnixRunProcessMixin): - """Arguments for run_process on Unix with 3.11+""" - else: - UnixProcessArgs = UnixProcessArgs3_10 + UnixProcessArgs = UnixProcessArgs3_11 - class UnixRunProcessArgs(UnixProcessArgs3_10, UnixRunProcessMixin): - """Arguments for run_process on Unix with 3.10+""" + class UnixRunProcessArgs(UnixProcessArgs3_11, UnixRunProcessMixin): + """Arguments for run_process on Unix with 3.11+""" @overload # type: ignore[no-overload-impl] async def open_process( diff --git a/src/trio/_tests/pytest_plugin.py b/src/trio/_tests/pytest_plugin.py index b929ae3a73..fa63a9b1b1 100644 --- a/src/trio/_tests/pytest_plugin.py +++ b/src/trio/_tests/pytest_plugin.py @@ -1,7 +1,7 @@ from __future__ import annotations import inspect -from typing import NoReturn +from typing import Never import pytest @@ -53,7 +53,7 @@ def pytest_pyfunc_call(pyfuncitem: pytest.Function) -> None: pyfuncitem.obj = trio_test(pyfuncitem.obj) -def maybe_ignore_import_error(error: ImportError) -> NoReturn: +def maybe_ignore_import_error(error: ImportError) -> Never: if SKIP_OPTIONAL_IMPORTS or (SKIP_SSL_IMPORTS and error.name == "cryptography"): pytest.skip(error.msg, allow_module_level=True) else: # pragma: no cover diff --git a/src/trio/_tests/test_channel.py b/src/trio/_tests/test_channel.py index 831f8eb483..4ed1471371 100644 --- a/src/trio/_tests/test_channel.py +++ b/src/trio/_tests/test_channel.py @@ -1,6 +1,5 @@ from __future__ import annotations -import sys from typing import TYPE_CHECKING import pytest @@ -10,9 +9,6 @@ from ..testing import assert_checkpoints, wait_all_tasks_blocked -if sys.version_info < (3, 11): - from exceptiongroup import ExceptionGroup - if TYPE_CHECKING: from collections.abc import AsyncGenerator @@ -534,7 +530,6 @@ async def agen(events: list[str]) -> AsyncGenerator[int]: assert i == 1 raise TypeError("iterator") - if sys.version_info >= (3, 11): assert g.value.__notes__ == [ "Encountered exception during cleanup of generator object, as " "well as exception in the contextmanager body - unable to unwrap." diff --git a/src/trio/_tests/test_dtls.py b/src/trio/_tests/test_dtls.py index 5a34d8c811..5eed68fe84 100644 --- a/src/trio/_tests/test_dtls.py +++ b/src/trio/_tests/test_dtls.py @@ -3,7 +3,7 @@ import random from contextlib import asynccontextmanager from itertools import count -from typing import TYPE_CHECKING, NoReturn +from typing import TYPE_CHECKING, Never import attrs import pytest @@ -922,7 +922,7 @@ async def test_association_replaced_before_handshake_starts( fn.enable() # This test shouldn't send any packets - def route_packet(packet: UDPPacket) -> NoReturn: # pragma: no cover + def route_packet(packet: UDPPacket) -> Never: # pragma: no cover raise AssertionError() fn.route_packet = route_packet # type: ignore[assignment] # TODO add type annotations for FakeNet diff --git a/src/trio/_tests/test_exports.py b/src/trio/_tests/test_exports.py index d1c254a285..62b675e6fe 100644 --- a/src/trio/_tests/test_exports.py +++ b/src/trio/_tests/test_exports.py @@ -416,7 +416,7 @@ def lookup_symbol(symbol: str) -> dict[str, Any]: # type: ignore[misc, explicit # using .remove() instead of .delete() to get an error in case they start not # being missing - if BaseException in class_.__mro__ and sys.version_info >= (3, 11): + if BaseException in class_.__mro__: extra.remove("__notes__") if tool == "mypy" and attrs.has(class_): @@ -480,7 +480,7 @@ def lookup_symbol(symbol: str) -> dict[str, Any]: # type: ignore[misc, explicit # I have not researched why these are missing, should maybe create an issue # upstream with jedi - if tool == "jedi" and sys.version_info >= (3, 11): + if tool == "jedi": if class_ in ( trio.DTLSChannel, trio.MemoryReceiveChannel, diff --git a/src/trio/_tests/test_highlevel_generic.py b/src/trio/_tests/test_highlevel_generic.py index a1a394aba5..d03438e29b 100644 --- a/src/trio/_tests/test_highlevel_generic.py +++ b/src/trio/_tests/test_highlevel_generic.py @@ -1,6 +1,6 @@ from __future__ import annotations -from typing import NoReturn +from typing import Never import attrs import pytest @@ -79,12 +79,12 @@ async def test_StapledStream_with_erroring_close() -> None: # Make sure that if one of the aclose methods errors out, then the other # one still gets called. class BrokenSendStream(RecordSendStream): - async def aclose(self) -> NoReturn: + async def aclose(self) -> Never: await super().aclose() raise ValueError("send error") class BrokenReceiveStream(RecordReceiveStream): - async def aclose(self) -> NoReturn: + async def aclose(self) -> Never: await super().aclose() raise ValueError("recv error") diff --git a/src/trio/_tests/test_highlevel_open_tcp_listeners.py b/src/trio/_tests/test_highlevel_open_tcp_listeners.py index 5c5a50c6cd..5967d86c39 100644 --- a/src/trio/_tests/test_highlevel_open_tcp_listeners.py +++ b/src/trio/_tests/test_highlevel_open_tcp_listeners.py @@ -2,7 +2,6 @@ import errno import socket as stdlib_socket -import sys from socket import AddressFamily, SocketKind from typing import TYPE_CHECKING, Literal, cast, overload @@ -22,9 +21,6 @@ from .. import socket as tsocket from .._core._tests.tutil import binds_ipv6, slow -if sys.version_info < (3, 11): - from exceptiongroup import BaseExceptionGroup - if TYPE_CHECKING: from collections.abc import Sequence diff --git a/src/trio/_tests/test_highlevel_open_tcp_stream.py b/src/trio/_tests/test_highlevel_open_tcp_stream.py index 3c9ae9e593..f42164bf4d 100644 --- a/src/trio/_tests/test_highlevel_open_tcp_stream.py +++ b/src/trio/_tests/test_highlevel_open_tcp_stream.py @@ -1,7 +1,6 @@ from __future__ import annotations import socket -import sys from socket import AddressFamily, SocketKind from typing import TYPE_CHECKING, Literal @@ -23,9 +22,6 @@ from trio._socket import _GetAddrInfoEntry from trio.testing import MockClock -if sys.version_info < (3, 11): - from exceptiongroup import BaseExceptionGroup - def test_close_all() -> None: class CloseMe(SocketType): diff --git a/src/trio/_tests/test_highlevel_serve_listeners.py b/src/trio/_tests/test_highlevel_serve_listeners.py index 1a6ac94690..6f84b1221a 100644 --- a/src/trio/_tests/test_highlevel_serve_listeners.py +++ b/src/trio/_tests/test_highlevel_serve_listeners.py @@ -2,7 +2,7 @@ import errno from functools import partial -from typing import TYPE_CHECKING, NoReturn, cast +from typing import TYPE_CHECKING, Never, cast import attrs import pytest @@ -113,7 +113,7 @@ async def test_serve_listeners_accept_unrecognized_error() -> None: for error in [KeyError(), OSError(errno.ECONNABORTED, "ECONNABORTED")]: listener = MemoryListener() - async def raise_error() -> NoReturn: + async def raise_error() -> Never: raise error # noqa: B023 # Set from loop def check_error(e: BaseException) -> bool: @@ -131,7 +131,7 @@ async def test_serve_listeners_accept_capacity_error( ) -> None: listener = MemoryListener() - async def raise_EMFILE() -> NoReturn: + async def raise_EMFILE() -> Never: raise OSError(errno.EMFILE, "out of file descriptors") listener.accept_hook = raise_EMFILE @@ -161,7 +161,7 @@ class Done(Exception): async def connection_watcher( *, task_status: TaskStatus[Nursery] = trio.TASK_STATUS_IGNORED, - ) -> NoReturn: + ) -> Never: async with trio.open_nursery() as nursery: task_status.started(nursery) await wait_all_tasks_blocked() diff --git a/src/trio/_tests/test_highlevel_ssl_helpers.py b/src/trio/_tests/test_highlevel_ssl_helpers.py index 80b5e30fab..3ba5caad00 100644 --- a/src/trio/_tests/test_highlevel_ssl_helpers.py +++ b/src/trio/_tests/test_highlevel_ssl_helpers.py @@ -1,7 +1,7 @@ from __future__ import annotations from functools import partial -from typing import TYPE_CHECKING, NoReturn, cast +from typing import TYPE_CHECKING, Never, cast import attrs import pytest @@ -61,7 +61,7 @@ async def getnameinfo( self, sockaddr: tuple[str, int] | tuple[str, int, int, int], flags: int, - ) -> NoReturn: # pragma: no cover + ) -> Never: # pragma: no cover raise NotImplementedError diff --git a/src/trio/_tests/test_repl.py b/src/trio/_tests/test_repl.py index 28075d551c..f6cbfbfa1e 100644 --- a/src/trio/_tests/test_repl.py +++ b/src/trio/_tests/test_repl.py @@ -129,8 +129,6 @@ async def test_system_exits_in_exc_group( raw_input = build_raw_input( [ "import sys", - "if sys.version_info < (3, 11):", - " from exceptiongroup import BaseExceptionGroup", "", "raise BaseExceptionGroup('', [RuntimeError(), SystemExit()])", "print('AFTER BaseExceptionGroup')", @@ -152,8 +150,6 @@ async def test_system_exits_in_nested_exc_group( raw_input = build_raw_input( [ "import sys", - "if sys.version_info < (3, 11):", - " from exceptiongroup import BaseExceptionGroup", "", "raise BaseExceptionGroup(", " '', [BaseExceptionGroup('', [RuntimeError(), SystemExit()])])", diff --git a/src/trio/_tests/test_signals.py b/src/trio/_tests/test_signals.py index 501ae1e80a..57d6c68924 100644 --- a/src/trio/_tests/test_signals.py +++ b/src/trio/_tests/test_signals.py @@ -1,7 +1,7 @@ from __future__ import annotations import signal -from typing import TYPE_CHECKING, NoReturn +from typing import TYPE_CHECKING, Never import pytest @@ -169,7 +169,7 @@ def direct_handler(signo: int, frame: FrameType | None) -> None: # Check exception chaining if there are multiple exception-raising # handlers - def raise_handler(signum: int, frame: FrameType | None) -> NoReturn: + def raise_handler(signum: int, frame: FrameType | None) -> Never: raise RuntimeError(signum) with _signal_handler({signal.SIGILL, signal.SIGFPE}, raise_handler): diff --git a/src/trio/_tests/test_ssl.py b/src/trio/_tests/test_ssl.py index a9a4298efc..9f72f19ed6 100644 --- a/src/trio/_tests/test_ssl.py +++ b/src/trio/_tests/test_ssl.py @@ -8,7 +8,7 @@ from contextlib import asynccontextmanager, contextmanager, suppress from functools import partial from ssl import SSLContext -from typing import TYPE_CHECKING, Any, NoReturn, TypeAlias +from typing import TYPE_CHECKING, Any, Never, TypeAlias import pytest @@ -1022,7 +1022,7 @@ async def test_send_all_fails_in_the_middle(client_ctx: SSLContext) -> None: nursery.start_soon(client.do_handshake) nursery.start_soon(server.do_handshake) - async def bad_hook() -> NoReturn: + async def bad_hook() -> Never: raise KeyError client.transport_stream.send_stream.send_all_hook = bad_hook @@ -1144,7 +1144,7 @@ async def test_ssl_only_closes_stream_once(client_ctx: SSLContext) -> None: client_orig_close_hook = client.transport_stream.send_stream.close_hook transport_close_count = 0 - def close_hook() -> NoReturn: + def close_hook() -> Never: nonlocal transport_close_count assert client_orig_close_hook is not None client_orig_close_hook() @@ -1200,7 +1200,7 @@ async def server_expect_clean_eof() -> None: async def test_send_error_during_handshake(client_ctx: SSLContext) -> None: client, _server = ssl_memory_stream_pair(client_ctx) - async def bad_hook() -> NoReturn: + async def bad_hook() -> Never: raise KeyError client.transport_stream.send_stream.send_all_hook = bad_hook @@ -1217,7 +1217,7 @@ async def bad_hook() -> NoReturn: async def test_receive_error_during_handshake(client_ctx: SSLContext) -> None: client, server = ssl_memory_stream_pair(client_ctx) - async def bad_hook() -> NoReturn: + async def bad_hook() -> Never: raise KeyError client.transport_stream.receive_stream.receive_some_hook = bad_hook diff --git a/src/trio/_tests/test_subprocess.py b/src/trio/_tests/test_subprocess.py index be762c0756..82c3438d0c 100644 --- a/src/trio/_tests/test_subprocess.py +++ b/src/trio/_tests/test_subprocess.py @@ -14,7 +14,7 @@ from typing import ( TYPE_CHECKING, Any, - NoReturn, + Never, TypeAlias, ) from unittest import mock @@ -690,7 +690,7 @@ async def do_stuff() -> None: async def test_warn_on_failed_cancel_terminate(monkeypatch: pytest.MonkeyPatch) -> None: original_terminate = Process.terminate - def broken_terminate(self: Process) -> NoReturn: + def broken_terminate(self: Process) -> Never: original_terminate(self) raise OSError("whoops") diff --git a/src/trio/_tests/test_testing_raisesgroup.py b/src/trio/_tests/test_testing_raisesgroup.py index ba453edbe8..a95c0ff22c 100644 --- a/src/trio/_tests/test_testing_raisesgroup.py +++ b/src/trio/_tests/test_testing_raisesgroup.py @@ -10,9 +10,6 @@ from trio.testing import _Matcher as Matcher, _RaisesGroup as RaisesGroup from trio.testing._raises_group import repr_callable -if sys.version_info < (3, 11): - from exceptiongroup import BaseExceptionGroup, ExceptionGroup - def wrap_escape(s: str) -> str: return "^" + re.escape(s) + "$" diff --git a/src/trio/_tests/test_threads.py b/src/trio/_tests/test_threads.py index f349850ffe..371d315cad 100644 --- a/src/trio/_tests/test_threads.py +++ b/src/trio/_tests/test_threads.py @@ -10,7 +10,7 @@ from functools import partial from typing import ( TYPE_CHECKING, - NoReturn, + Never, TypeVar, ) @@ -87,7 +87,7 @@ def f1(record: RecordType) -> int: await check_case(from_thread_run_sync, f1, ("got", 2), trio_token=token) - def f2(record: RecordType) -> NoReturn: + def f2(record: RecordType) -> Never: assert not _core.currently_ki_protected() record.append(("f", threading.current_thread())) raise ValueError @@ -102,7 +102,7 @@ async def f3(record: RecordType) -> int: await check_case(from_thread_run, f3, ("got", 3), trio_token=token) - async def f4(record: RecordType) -> NoReturn: + async def f4(record: RecordType) -> Never: assert not _core.currently_ki_protected() await _core.checkpoint() record.append(("f", threading.current_thread())) @@ -327,7 +327,7 @@ def f(x: T) -> tuple[T, threading.Thread]: assert x == 1 assert child_thread != trio_thread - def g() -> NoReturn: + def g() -> Never: raise ValueError(threading.current_thread()) with pytest.raises( @@ -583,7 +583,7 @@ class BadCapacityLimiter: async def acquire_on_behalf_of(self, borrower: Task) -> None: record.append("acquire") - def release_on_behalf_of(self, borrower: Task) -> NoReturn: + def release_on_behalf_of(self, borrower: Task) -> Never: record.append("release") raise ValueError("release on behalf") @@ -608,7 +608,7 @@ async def test_run_in_worker_thread_fail_to_spawn( monkeypatch: pytest.MonkeyPatch, ) -> None: # Test the unlikely but possible case where trying to spawn a thread fails - def bad_start(self: object, *args: object) -> NoReturn: + def bad_start(self: object, *args: object) -> Never: raise RuntimeError("the engines canna take it captain") monkeypatch.setattr(_core._thread_cache.ThreadCache, "start_thread_soon", bad_start) diff --git a/src/trio/_tests/test_util.py b/src/trio/_tests/test_util.py index c8beefa1ca..69eca4785e 100644 --- a/src/trio/_tests/test_util.py +++ b/src/trio/_tests/test_util.py @@ -1,11 +1,10 @@ from __future__ import annotations -import sys import types from typing import TYPE_CHECKING, TypeVar if TYPE_CHECKING: - from collections.abc import AsyncGenerator, Coroutine, Generator + from collections.abc import AsyncGenerator import pytest import trio @@ -28,9 +27,6 @@ ) from ..testing import wait_all_tasks_blocked -if sys.version_info < (3, 11): - from exceptiongroup import BaseExceptionGroup, ExceptionGroup - if TYPE_CHECKING: from collections.abc import AsyncGenerator @@ -108,20 +104,6 @@ async def f() -> None: # pragma: no cover coroutine_or_error(f()) # type: ignore[arg-type, unused-coroutine] assert "expecting an async function" in str(excinfo.value) - import asyncio - - if sys.version_info < (3, 11): - - @asyncio.coroutine - def generator_based_coro() -> ( - Generator[Coroutine[None, None, None], None, None] - ): # pragma: no cover - yield from asyncio.sleep(1) - - with pytest.raises(TypeError) as excinfo: - coroutine_or_error(generator_based_coro()) # type: ignore[arg-type, unused-coroutine] - assert "asyncio" in str(excinfo.value) - with pytest.raises(TypeError) as excinfo: coroutine_or_error(create_asyncio_future_in_new_loop()) # type: ignore[arg-type, unused-coroutine] assert "asyncio" in str(excinfo.value) diff --git a/src/trio/_threads.py b/src/trio/_threads.py index 46de93563d..84bf184283 100644 --- a/src/trio/_threads.py +++ b/src/trio/_threads.py @@ -6,7 +6,7 @@ import queue as stdlib_queue import threading from itertools import count -from typing import TYPE_CHECKING, Generic, TypeVar +from typing import TYPE_CHECKING, Generic, TypeVar, TypeVarTuple import attrs import outcome @@ -29,8 +29,6 @@ if TYPE_CHECKING: from collections.abc import Awaitable, Callable, Generator - from typing_extensions import TypeVarTuple, Unpack - from trio._core._traps import RaiseCancelT Ts = TypeVarTuple("Ts") @@ -255,8 +253,8 @@ def run_in_system_nursery(self, token: TrioToken) -> None: @enable_ki_protection async def to_thread_run_sync( - sync_fn: Callable[[Unpack[Ts]], RetT], - *args: Unpack[Ts], + sync_fn: Callable[[*Ts], RetT], + *args: *Ts, thread_name: str | None = None, abandon_on_cancel: bool = False, limiter: CapacityLimiter | None = None, @@ -529,8 +527,8 @@ def _send_message_to_trio( def from_thread_run( - afn: Callable[[Unpack[Ts]], Awaitable[RetT]], - *args: Unpack[Ts], + afn: Callable[[*Ts], Awaitable[RetT]], + *args: *Ts, trio_token: TrioToken | None = None, ) -> RetT: """Run the given async function in the parent Trio thread, blocking until it @@ -573,8 +571,8 @@ def from_thread_run( def from_thread_run_sync( - fn: Callable[[Unpack[Ts]], RetT], - *args: Unpack[Ts], + fn: Callable[[*Ts], RetT], + *args: *Ts, trio_token: TrioToken | None = None, ) -> RetT: """Run the given sync function in the parent Trio thread, blocking until it diff --git a/src/trio/_timeouts.py b/src/trio/_timeouts.py index d95cbe4cfc..b1bb23a06f 100644 --- a/src/trio/_timeouts.py +++ b/src/trio/_timeouts.py @@ -3,7 +3,7 @@ import math import sys from contextlib import contextmanager -from typing import TYPE_CHECKING, NoReturn +from typing import TYPE_CHECKING, Never import trio @@ -58,7 +58,7 @@ def move_on_after( ) -async def sleep_forever() -> NoReturn: +async def sleep_forever() -> Never: """Pause execution of the current task forever (or until cancelled). Equivalent to calling ``await sleep(math.inf)``, except that if manually diff --git a/src/trio/_util.py b/src/trio/_util.py index bae6608d88..2142875738 100644 --- a/src/trio/_util.py +++ b/src/trio/_util.py @@ -9,8 +9,9 @@ from typing import ( TYPE_CHECKING, Any, - NoReturn, + Never, TypeVar, + TypeVarTuple, final as std_final, ) @@ -24,14 +25,8 @@ RetT = TypeVar("RetT") if TYPE_CHECKING: - import sys from types import AsyncGeneratorType, TracebackType - from typing_extensions import TypeVarTuple, Unpack - - if sys.version_info < (3, 11): - from exceptiongroup import BaseExceptionGroup - PosArgsT = TypeVarTuple("PosArgsT") @@ -57,9 +52,9 @@ def is_main_thread() -> bool: # errors for common mistakes. Returns coroutine object. ###### def coroutine_or_error( - async_fn: Callable[[Unpack[PosArgsT]], Awaitable[RetT]], - *args: Unpack[PosArgsT], -) -> collections.abc.Coroutine[object, NoReturn, RetT]: + async_fn: Callable[[*PosArgsT], Awaitable[RetT]], + *args: *PosArgsT, +) -> collections.abc.Coroutine[object, Never, RetT]: def _return_value_looks_like_wrong_library(value: object) -> bool: # Returned by legacy @asyncio.coroutine functions, which includes # a surprising proportion of asyncio builtins. @@ -228,7 +223,7 @@ def fix_one(qualname: str, name: str, obj: object) -> None: fix_one(objname, objname, obj) -def _init_final_cls(cls: type[object]) -> NoReturn: +def _init_final_cls(cls: type[object]) -> Never: """Raises an exception when a final class is subclassed.""" raise TypeError(f"{cls.__module__}.{cls.__qualname__} does not support subclassing") @@ -291,7 +286,7 @@ def _create(cls: type[T], *args: object, **kwargs: object) -> T: return super().__call__(*args, **kwargs) # type: ignore -def name_asyncgen(agen: AsyncGeneratorType[object, NoReturn]) -> str: +def name_asyncgen(agen: AsyncGeneratorType[object, Never]) -> str: """Return the fully-qualified name of the async generator function that produced the async generator iterator *agen*. """ @@ -323,7 +318,7 @@ def wraps( # type: ignore[explicit-any] from functools import wraps # noqa: F401 # this is re-exported -def raise_saving_context(exc: BaseException) -> NoReturn: +def raise_saving_context(exc: BaseException) -> Never: """This helper allows re-raising an exception without __context__ being set.""" # cause does not need special handling, we simply avoid using `raise .. from ..` # __suppress_context__ also does not need handling, it's only set if modifying cause @@ -343,7 +338,7 @@ class MultipleExceptionError(Exception): def raise_single_exception_from_group( eg: BaseExceptionGroup[BaseException], -) -> NoReturn: +) -> Never: """This function takes an exception group that is assumed to have at most one non-cancelled exception, which it reraises as a standalone exception. diff --git a/src/trio/testing/_check_streams.py b/src/trio/testing/_check_streams.py index a53a45416a..7d39bf33dc 100644 --- a/src/trio/testing/_check_streams.py +++ b/src/trio/testing/_check_streams.py @@ -2,7 +2,6 @@ from __future__ import annotations import random -import sys from collections.abc import Awaitable, Callable, Generator from contextlib import contextmanager, suppress from typing import ( @@ -24,8 +23,6 @@ ArgsT = ParamSpec("ArgsT") -if sys.version_info < (3, 11): - from exceptiongroup import BaseExceptionGroup Res1 = TypeVar("Res1", bound=AsyncResource) Res2 = TypeVar("Res2", bound=AsyncResource) diff --git a/src/trio/testing/_fake_net.py b/src/trio/testing/_fake_net.py index 82d14f590d..24ff1c69b5 100644 --- a/src/trio/testing/_fake_net.py +++ b/src/trio/testing/_fake_net.py @@ -14,7 +14,7 @@ import os import socket import sys -from typing import TYPE_CHECKING, Any, NoReturn, TypeAlias, overload +from typing import TYPE_CHECKING, Any, Never, Self, TypeAlias, overload import attrs @@ -27,7 +27,7 @@ from socket import AddressFamily, SocketKind from types import TracebackType - from typing_extensions import Buffer, Self + from typing_extensions import Buffer from trio._socket import AddressFormat, _GetAddrInfoEntry @@ -59,7 +59,7 @@ def _localhost_ip_for(family: int) -> IPAddress: # pragma: no cover raise NotImplementedError("Unhandled ip address family") -def _fake_err(code: int) -> NoReturn: +def _fake_err(code: int) -> Never: raise OSError(code, os.strerror(code)) @@ -289,7 +289,7 @@ async def bind(self, addr: object) -> None: self._fake_net._bind(binding, self) self._binding = binding - async def connect(self, peer: object) -> NoReturn: + async def connect(self, peer: object) -> Never: raise NotImplementedError("FakeNet does not (yet) support connected sockets") async def _sendmsg( diff --git a/src/trio/testing/_raises_group.py b/src/trio/testing/_raises_group.py index 2c483a0f29..9874cfc5fb 100644 --- a/src/trio/testing/_raises_group.py +++ b/src/trio/testing/_raises_group.py @@ -1,7 +1,6 @@ from __future__ import annotations import re -import sys from abc import ABC, abstractmethod from re import Pattern from textwrap import indent @@ -39,9 +38,6 @@ ExcT_1 = TypeVar("ExcT_1", bound=Exception) ExcT_2 = TypeVar("ExcT_2", bound=Exception) -if sys.version_info < (3, 11): - from exceptiongroup import BaseExceptionGroup, ExceptionGroup - @final class _ExceptionInfo(Generic[MatchE]): diff --git a/tox.ini b/tox.ini index e09c1d97ca..8b0319f504 100644 --- a/tox.ini +++ b/tox.ini @@ -1,5 +1,5 @@ [tox] -envlist = py{39,310,311,312,313,314,315,py310,py311} +envlist = py{39,311,312,313,314,315,py310,py311} labels = check = typing, gen_exports, type_completeness, pip_compile cython = py39-cython2,py39-cython,py311-cython2,py313-cython @@ -101,7 +101,7 @@ description = "Run type checks: mypy on all platforms, and pyright on `src/trio[ deps = -r test-requirements.txt exceptiongroup -base_python = 3.10 +base_python = 3.11 set_env = PYRIGHT_PYTHON_IGNORE_WARNINGS=1 commands = From bef0b6574e5c574d46e977f8aa9aa593e945126b Mon Sep 17 00:00:00 2001 From: EmmanuelNiyonshuti Date: Sun, 15 Nov 2026 17:41:42 +0200 Subject: [PATCH 2/6] add changelog --- newsfragments/3594.removal.rst | 1 + 1 file changed, 1 insertion(+) create mode 100644 newsfragments/3594.removal.rst diff --git a/newsfragments/3594.removal.rst b/newsfragments/3594.removal.rst new file mode 100644 index 0000000000..c943b718d8 --- /dev/null +++ b/newsfragments/3594.removal.rst @@ -0,0 +1 @@ +Drop support for Python 3.10. From 7a50801c8279e70ca805865ab1e7e4d9268ab5c4 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Sun, 15 Nov 2026 15:47:14 +0000 Subject: [PATCH 3/6] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- src/trio/_core/_tests/test_ki.py | 3 +-- src/trio/_core/_tests/type_tests/run.py | 3 +-- src/trio/_tests/type_tests/check_wraps.py | 3 ++- src/trio/_tests/type_tests/path.py | 3 +-- src/trio/_tests/type_tests/subprocesses.py | 3 +-- src/trio/_tests/type_tests/task_status.py | 3 ++- 6 files changed, 8 insertions(+), 10 deletions(-) diff --git a/src/trio/_core/_tests/test_ki.py b/src/trio/_core/_tests/test_ki.py index 1ce4af9aaf..47e092bc3a 100644 --- a/src/trio/_core/_tests/test_ki.py +++ b/src/trio/_core/_tests/test_ki.py @@ -33,8 +33,7 @@ Iterator, ) from types import AsyncGeneratorType - - from typing_extensions import Never + from typing import Never from ..._core import Abort, RaiseCancelT diff --git a/src/trio/_core/_tests/type_tests/run.py b/src/trio/_core/_tests/type_tests/run.py index 5c51b91496..46f62b70e8 100644 --- a/src/trio/_core/_tests/type_tests/run.py +++ b/src/trio/_core/_tests/type_tests/run.py @@ -1,9 +1,8 @@ from __future__ import annotations -from typing import TYPE_CHECKING, overload +from typing import TYPE_CHECKING, assert_type, overload import trio -from typing_extensions import assert_type if TYPE_CHECKING: from collections.abc import Sequence diff --git a/src/trio/_tests/type_tests/check_wraps.py b/src/trio/_tests/type_tests/check_wraps.py index 058e9d0609..36af56cc17 100644 --- a/src/trio/_tests/type_tests/check_wraps.py +++ b/src/trio/_tests/type_tests/check_wraps.py @@ -1,7 +1,8 @@ # https://github.com/python-trio/trio/issues/2775#issuecomment-1702267589 # (except platform independent...) +from typing import assert_type + import trio -from typing_extensions import assert_type async def fn(s: trio.SocketStream) -> None: diff --git a/src/trio/_tests/type_tests/path.py b/src/trio/_tests/type_tests/path.py index 2b956c9315..8cbe026f69 100644 --- a/src/trio/_tests/type_tests/path.py +++ b/src/trio/_tests/type_tests/path.py @@ -4,11 +4,10 @@ import os import pathlib import sys -from typing import IO, Any, BinaryIO +from typing import IO, Any, BinaryIO, assert_type import trio from trio._file_io import AsyncIOWrapper -from typing_extensions import assert_type def operator_checks(text: str, tpath: trio.Path, ppath: pathlib.Path) -> None: diff --git a/src/trio/_tests/type_tests/subprocesses.py b/src/trio/_tests/type_tests/subprocesses.py index 689ffd7d95..12ce31d36a 100644 --- a/src/trio/_tests/type_tests/subprocesses.py +++ b/src/trio/_tests/type_tests/subprocesses.py @@ -1,10 +1,9 @@ import os import sys from collections.abc import Sequence -from typing import TypeAlias +from typing import TypeAlias, assert_type import trio -from typing_extensions import assert_type StrOrBytesPath: TypeAlias = str | bytes | os.PathLike[str] | os.PathLike[bytes] diff --git a/src/trio/_tests/type_tests/task_status.py b/src/trio/_tests/type_tests/task_status.py index 6d2e3922bb..1f37bc9d85 100644 --- a/src/trio/_tests/type_tests/task_status.py +++ b/src/trio/_tests/type_tests/task_status.py @@ -1,7 +1,8 @@ """Check that started() can only be called for TaskStatus[None].""" +from typing import assert_type + from trio import TaskStatus -from typing_extensions import assert_type def check_status( From 7531f9434b1c858fd1b5e485f4daeda0ff44bb16 Mon Sep 17 00:00:00 2001 From: EmmanuelNiyonshuti Date: Sun, 15 Nov 2026 19:01:41 +0200 Subject: [PATCH 4/6] update TrioToken --- src/trio/_core/_entry_queue.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/trio/_core/_entry_queue.py b/src/trio/_core/_entry_queue.py index ea601a9693..654bc78d45 100644 --- a/src/trio/_core/_entry_queue.py +++ b/src/trio/_core/_entry_queue.py @@ -3,7 +3,7 @@ import threading from collections import deque from collections.abc import Callable -from typing import TYPE_CHECKING, Never, TypeVarTuple +from typing import TYPE_CHECKING, Never, TypeVarTuple, Unpack import attrs @@ -172,8 +172,8 @@ class TrioToken(metaclass=NoPublicConstructor): def run_sync_soon( self, - sync_fn: Callable[[*PosArgsT], object], - *args: *PosArgsT, + sync_fn: Callable[[Unpack[PosArgsT]], object], + *args: Unpack[PosArgsT], idempotent: bool = False, ) -> None: """Schedule a call to ``sync_fn(*args)`` to occur in the context of a From 9c991e9176c5bab54fd831cca0dceebfd9864190 Mon Sep 17 00:00:00 2001 From: EmmanuelNiyonshuti Date: Mon, 16 Nov 2026 08:27:41 +0200 Subject: [PATCH 5/6] change back unpack operator to Unpack --- pyproject.toml | 1 + src/trio/_core/_entry_queue.py | 4 ++-- src/trio/_core/_generated_run.py | 5 +++-- src/trio/_core/_run.py | 25 +++++++++++++------------ src/trio/_dtls.py | 14 +++++++++++--- src/trio/_ssl.py | 9 +++++---- src/trio/_threads.py | 14 +++++++------- src/trio/_util.py | 5 +++-- 8 files changed, 45 insertions(+), 32 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index e8ac1e919a..a7ca069fcd 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -159,6 +159,7 @@ extend-ignore = [ # conflicts with formatter (ruff recommends these be disabled) "missing-trailing-comma", # COM812 + "non-pep646-unpack" # (UP044) ignoring it for now(See: https://github.com/python-trio/trio/pull/3594#issuecomment-6898086470) ] [tool.ruff.lint.per-file-ignores] diff --git a/src/trio/_core/_entry_queue.py b/src/trio/_core/_entry_queue.py index 654bc78d45..3d080af005 100644 --- a/src/trio/_core/_entry_queue.py +++ b/src/trio/_core/_entry_queue.py @@ -128,8 +128,8 @@ def size(self) -> int: def run_sync_soon( self, - sync_fn: Callable[[*PosArgsT], object], - *args: *PosArgsT, + sync_fn: Callable[[Unpack[PosArgsT]], object], + *args: Unpack[PosArgsT], idempotent: bool = False, ) -> None: with self.lock: diff --git a/src/trio/_core/_generated_run.py b/src/trio/_core/_generated_run.py index 107442c673..4da520109b 100644 --- a/src/trio/_core/_generated_run.py +++ b/src/trio/_core/_generated_run.py @@ -13,6 +13,7 @@ from collections.abc import Awaitable, Callable import outcome + from typing_extensions import Unpack from .._abc import Clock from ._entry_queue import TrioToken @@ -127,8 +128,8 @@ def reschedule(task: Task, next_send: outcome.Outcome[object] = _NO_SEND) -> Non @enable_ki_protection def spawn_system_task( - async_fn: Callable[[*PosArgT], Awaitable[object]], - *args: *PosArgT, + async_fn: Callable[[Unpack[PosArgT]], Awaitable[object]], + *args: Unpack[PosArgT], name: object = None, context: contextvars.Context | None = None, ) -> Task: diff --git a/src/trio/_core/_run.py b/src/trio/_core/_run.py index d94a5ef47e..81fe6dd5fd 100644 --- a/src/trio/_core/_run.py +++ b/src/trio/_core/_run.py @@ -22,6 +22,7 @@ Protocol, Self, TypeVarTuple, + Unpack, cast, overload, ) @@ -1337,8 +1338,8 @@ def aborted(raise_cancel: _core.RaiseCancelT) -> Abort: def start_soon( self, - async_fn: Callable[[*PosArgT], Awaitable[object]], - *args: *PosArgT, + async_fn: Callable[[Unpack[PosArgT]], Awaitable[object]], + *args: Unpack[PosArgT], name: object = None, ) -> None: """Creates a child task, scheduling ``await async_fn(*args)``. @@ -1930,8 +1931,8 @@ def reschedule( def spawn_impl( self, - async_fn: Callable[[*PosArgT], Awaitable[object]], - args: tuple[*PosArgT], + async_fn: Callable[[Unpack[PosArgT]], Awaitable[object]], + args: tuple[Unpack[PosArgT]], nursery: Nursery | None, name: object, *, @@ -2074,8 +2075,8 @@ def task_exited(self, task: Task, outcome: Outcome[object]) -> None: @_public def spawn_system_task( self, - async_fn: Callable[[*PosArgT], Awaitable[object]], - *args: *PosArgT, + async_fn: Callable[[Unpack[PosArgT]], Awaitable[object]], + *args: Unpack[PosArgT], name: object = None, context: contextvars.Context | None = None, ) -> Task: @@ -2141,8 +2142,8 @@ def spawn_system_task( async def init( self, - async_fn: Callable[[*PosArgT], Awaitable[object]], - args: tuple[*PosArgT], + async_fn: Callable[[Unpack[PosArgT]], Awaitable[object]], + args: tuple[Unpack[PosArgT]], ) -> None: # run_sync_soon task runs here: async with open_nursery() as run_sync_soon_nursery: @@ -2422,8 +2423,8 @@ def setup_runner( def run( - async_fn: Callable[[*PosArgT], Awaitable[RetT]], - *args: *PosArgT, + async_fn: Callable[[Unpack[PosArgT]], Awaitable[RetT]], + *args: Unpack[PosArgT], clock: Clock | None = None, instruments: Sequence[Instrument] = (), restrict_keyboard_interrupt_to_checkpoints: bool = False, @@ -2712,8 +2713,8 @@ def my_done_callback(run_outcome): @enable_ki_protection def unrolled_run( runner: Runner, - async_fn: Callable[[*PosArgT], Awaitable[object]], - args: tuple[*PosArgT], + async_fn: Callable[[Unpack[PosArgT]], Awaitable[object]], + args: tuple[Unpack[PosArgT]], host_uses_signal_set_wakeup_fd: bool = False, ) -> Generator[float, EventResult, None]: __tracebackhide__ = True diff --git a/src/trio/_dtls.py b/src/trio/_dtls.py index 24a39ffda7..e63f735078 100644 --- a/src/trio/_dtls.py +++ b/src/trio/_dtls.py @@ -18,7 +18,15 @@ import weakref from itertools import count from math import isnan -from typing import TYPE_CHECKING, Generic, Self, TypeAlias, TypeVar, TypeVarTuple +from typing import ( + TYPE_CHECKING, + Generic, + Self, + TypeAlias, + TypeVar, + TypeVarTuple, + Unpack, +) from weakref import ReferenceType, WeakValueDictionary import attrs @@ -1274,8 +1282,8 @@ def _check_closed(self) -> None: async def serve( self, ssl_context: SSL.Context, - async_fn: Callable[[DTLSChannel, *PosArgsT], Awaitable[object]], - *args: *PosArgsT, + async_fn: Callable[[DTLSChannel, Unpack[PosArgsT]], Awaitable[object]], + *args: Unpack[PosArgsT], task_status: trio.TaskStatus[None] = trio.TASK_STATUS_IGNORED, ) -> None: """Listen for incoming connections, and spawn a handler for each using an diff --git a/src/trio/_ssl.py b/src/trio/_ssl.py index 56e1dd41cb..c86ee816ed 100644 --- a/src/trio/_ssl.py +++ b/src/trio/_ssl.py @@ -12,6 +12,7 @@ Generic, TypeVar, TypeVarTuple, + Unpack, ) import trio @@ -234,8 +235,8 @@ class _Once: def __init__( self, - afn: Callable[[*Ts], Awaitable[object]], - *args: *Ts, + afn: Callable[[Unpack[Ts]], Awaitable[object]], + *args: Unpack[Ts], ) -> None: self._afn = afn self._args = args @@ -473,8 +474,8 @@ def _check_status(self) -> None: # too. async def _retry( self, - fn: Callable[[*Ts], T], - *args: *Ts, + fn: Callable[[Unpack[Ts]], T], + *args: Unpack[Ts], ignore_want_read: bool = False, is_handshake: bool = False, ) -> T | None: diff --git a/src/trio/_threads.py b/src/trio/_threads.py index 84bf184283..9d33b5ff89 100644 --- a/src/trio/_threads.py +++ b/src/trio/_threads.py @@ -6,7 +6,7 @@ import queue as stdlib_queue import threading from itertools import count -from typing import TYPE_CHECKING, Generic, TypeVar, TypeVarTuple +from typing import TYPE_CHECKING, Generic, TypeVar, TypeVarTuple, Unpack import attrs import outcome @@ -253,8 +253,8 @@ def run_in_system_nursery(self, token: TrioToken) -> None: @enable_ki_protection async def to_thread_run_sync( - sync_fn: Callable[[*Ts], RetT], - *args: *Ts, + sync_fn: Callable[[Unpack[Ts]], RetT], + *args: Unpack[Ts], thread_name: str | None = None, abandon_on_cancel: bool = False, limiter: CapacityLimiter | None = None, @@ -527,8 +527,8 @@ def _send_message_to_trio( def from_thread_run( - afn: Callable[[*Ts], Awaitable[RetT]], - *args: *Ts, + afn: Callable[[Unpack[Ts]], Awaitable[RetT]], + *args: Unpack[Ts], trio_token: TrioToken | None = None, ) -> RetT: """Run the given async function in the parent Trio thread, blocking until it @@ -571,8 +571,8 @@ def from_thread_run( def from_thread_run_sync( - fn: Callable[[*Ts], RetT], - *args: *Ts, + fn: Callable[[Unpack[Ts]], RetT], + *args: Unpack[Ts], trio_token: TrioToken | None = None, ) -> RetT: """Run the given sync function in the parent Trio thread, blocking until it diff --git a/src/trio/_util.py b/src/trio/_util.py index 2142875738..dc5eee9202 100644 --- a/src/trio/_util.py +++ b/src/trio/_util.py @@ -12,6 +12,7 @@ Never, TypeVar, TypeVarTuple, + Unpack, final as std_final, ) @@ -52,8 +53,8 @@ def is_main_thread() -> bool: # errors for common mistakes. Returns coroutine object. ###### def coroutine_or_error( - async_fn: Callable[[*PosArgsT], Awaitable[RetT]], - *args: *PosArgsT, + async_fn: Callable[[Unpack[PosArgsT]], Awaitable[RetT]], + *args: Unpack[PosArgsT], ) -> collections.abc.Coroutine[object, Never, RetT]: def _return_value_looks_like_wrong_library(value: object) -> bool: # Returned by legacy @asyncio.coroutine functions, which includes From d097f1884550bad39ffa47ca17de8fbd31d7984f Mon Sep 17 00:00:00 2001 From: EmmanuelNiyonshuti Date: Mon, 16 Nov 2026 09:03:09 +0200 Subject: [PATCH 6/6] use NoReturn for return values --- src/trio/_core/_entry_queue.py | 4 +- src/trio/_core/_run.py | 12 +++--- .../_core/_tests/test_exceptiongroup_gc.py | 18 ++++----- src/trio/_core/_tests/test_guest_mode.py | 8 ++-- src/trio/_core/_tests/test_instrumentation.py | 8 ++-- src/trio/_core/_tests/test_ki.py | 3 +- src/trio/_core/_tests/test_run.py | 40 +++++++++---------- src/trio/_core/_tests/test_thread_cache.py | 6 +-- src/trio/_core/_windows_cffi.py | 4 +- src/trio/_highlevel_serve_listeners.py | 6 +-- src/trio/_highlevel_ssl_helpers.py | 4 +- src/trio/_tests/pytest_plugin.py | 4 +- src/trio/_tests/test_dtls.py | 4 +- src/trio/_tests/test_highlevel_generic.py | 6 +-- .../_tests/test_highlevel_serve_listeners.py | 8 ++-- src/trio/_tests/test_highlevel_ssl_helpers.py | 4 +- src/trio/_tests/test_signals.py | 4 +- src/trio/_tests/test_ssl.py | 10 ++--- src/trio/_tests/test_subprocess.py | 4 +- src/trio/_tests/test_threads.py | 12 +++--- src/trio/_timeouts.py | 4 +- src/trio/_util.py | 9 +++-- src/trio/testing/_fake_net.py | 6 +-- 23 files changed, 94 insertions(+), 94 deletions(-) diff --git a/src/trio/_core/_entry_queue.py b/src/trio/_core/_entry_queue.py index 3d080af005..9f5435c048 100644 --- a/src/trio/_core/_entry_queue.py +++ b/src/trio/_core/_entry_queue.py @@ -3,7 +3,7 @@ import threading from collections import deque from collections.abc import Callable -from typing import TYPE_CHECKING, Never, TypeVarTuple, Unpack +from typing import TYPE_CHECKING, NoReturn, TypeVarTuple, Unpack import attrs @@ -66,7 +66,7 @@ def run_cb(job: Job) -> None: async def kill_everything( # noqa: RUF029 # await not used exc: BaseException, - ) -> Never: + ) -> NoReturn: raise exc try: diff --git a/src/trio/_core/_run.py b/src/trio/_core/_run.py index 81fe6dd5fd..18cfb193a6 100644 --- a/src/trio/_core/_run.py +++ b/src/trio/_core/_run.py @@ -18,7 +18,7 @@ TYPE_CHECKING, Any, Final, - Never, + NoReturn, Protocol, Self, TypeVarTuple, @@ -155,7 +155,7 @@ def _count_context_run_tb_frames() -> int: """ - def function_with_unique_name_xyzzy() -> Never: + def function_with_unique_name_xyzzy() -> NoReturn: try: 1 / 0 # noqa: B018 # We need a ZeroDivisionError to fire except ZeroDivisionError: @@ -1125,7 +1125,7 @@ async def __aexit__( # make sure these raise errors in static analysis if called if not TYPE_CHECKING: - def __enter__(self) -> Never: + def __enter__(self) -> NoReturn: raise RuntimeError( "use 'async with open_nursery(...)', not 'with open_nursery(...)'", ) @@ -1135,7 +1135,7 @@ def __exit__( exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None, - ) -> Never: # pragma: no cover + ) -> NoReturn: # pragma: no cover raise AssertionError("Never called, but should be defined") @@ -1649,7 +1649,7 @@ def _attempt_delivery_of_any_pending_cancel(self) -> None: reason = self._cancel_status._scope._cancel_reason - def raise_cancel() -> Never: + def raise_cancel() -> NoReturn: if reason is None: raise Cancelled._create(source="unknown", reason="misnesting") else: @@ -1666,7 +1666,7 @@ def _attempt_delivery_of_pending_ki(self) -> None: if self._abort_func is None: return - def raise_cancel() -> Never: + def raise_cancel() -> NoReturn: self._runner.ki_pending = False raise KeyboardInterrupt diff --git a/src/trio/_core/_tests/test_exceptiongroup_gc.py b/src/trio/_core/_tests/test_exceptiongroup_gc.py index f83bb4e1c2..799040a614 100644 --- a/src/trio/_core/_tests/test_exceptiongroup_gc.py +++ b/src/trio/_core/_tests/test_exceptiongroup_gc.py @@ -3,7 +3,7 @@ import gc import sys from traceback import extract_tb -from typing import TYPE_CHECKING, Never +from typing import TYPE_CHECKING, NoReturn import pytest @@ -14,27 +14,27 @@ from types import TracebackType -def raiser1() -> Never: +def raiser1() -> NoReturn: raiser1_2() -def raiser1_2() -> Never: +def raiser1_2() -> NoReturn: raiser1_3() -def raiser1_3() -> Never: +def raiser1_3() -> NoReturn: raise ValueError("raiser1_string") -def raiser2() -> Never: +def raiser2() -> NoReturn: raiser2_2() -def raiser2_2() -> Never: +def raiser2_2() -> NoReturn: raise KeyError("raiser2_string") -def get_exc(raiser: Callable[[], Never]) -> Exception: +def get_exc(raiser: Callable[[], NoReturn]) -> Exception: try: raiser() except Exception as exc: @@ -42,7 +42,7 @@ def get_exc(raiser: Callable[[], Never]) -> Exception: raise AssertionError("raiser should always raise") # pragma: no cover -def get_tb(raiser: Callable[[], Never]) -> TracebackType | None: +def get_tb(raiser: Callable[[], NoReturn]) -> TracebackType | None: return get_exc(raiser).__traceback__ @@ -82,7 +82,7 @@ def test_ExceptionGroup_catch_doesnt_create_cyclic_garbage() -> None: gc.collect() old_flags = gc.get_debug() - def make_multi() -> Never: + def make_multi() -> NoReturn: raise ExceptionGroup("", [get_exc(raiser1), get_exc(raiser2)]) try: diff --git a/src/trio/_core/_tests/test_guest_mode.py b/src/trio/_core/_tests/test_guest_mode.py index 8d0a903dba..7acbc0f082 100644 --- a/src/trio/_core/_tests/test_guest_mode.py +++ b/src/trio/_core/_tests/test_guest_mode.py @@ -16,7 +16,7 @@ from math import inf from typing import ( TYPE_CHECKING, - Never, + NoReturn, TypeAlias, TypeVar, cast, @@ -123,7 +123,7 @@ async def trio_return(in_host: InHost) -> str: assert trivial_guest_run(trio_return) == "ok" - async def trio_fail(in_host: InHost) -> Never: + async def trio_fail(in_host: InHost) -> NoReturn: raise KeyError("whoopsiedaisy") with pytest.raises(KeyError, match="whoopsiedaisy"): @@ -178,7 +178,7 @@ async def early_task() -> None: assert set(record) == {"system task ran", "main task ran", "run_sync_soon cb ran"} class BadClock(Clock): - def start_clock(self) -> Never: + def start_clock(self) -> NoReturn: raise ValueError("whoops") def current_time(self) -> float: @@ -645,7 +645,7 @@ async def trio_main(in_host: InHost) -> None: # Also check chaining in the case where KI is injected after main exits final_exc = KeyError("whoa") - async def trio_main_raising(in_host: InHost) -> Never: + async def trio_main_raising(in_host: InHost) -> NoReturn: in_host(partial(signal.raise_signal, signal.SIGINT)) raise final_exc diff --git a/src/trio/_core/_tests/test_instrumentation.py b/src/trio/_core/_tests/test_instrumentation.py index f6f3c00e6b..60c54307ee 100644 --- a/src/trio/_core/_tests/test_instrumentation.py +++ b/src/trio/_core/_tests/test_instrumentation.py @@ -1,6 +1,6 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Never +from typing import TYPE_CHECKING, NoReturn import attrs import pytest @@ -184,7 +184,7 @@ def test_instruments_crash(caplog: pytest.LogCaptureFixture) -> None: record = [] class BrokenInstrument(_abc.Instrument): - def task_scheduled(self, task: Task) -> Never: + def task_scheduled(self, task: Task) -> NoReturn: record.append("scheduled") raise ValueError("oops") @@ -249,11 +249,11 @@ async def main() -> None: def test_instrument_that_raises_on_getattr() -> None: class EvilInstrument(_abc.Instrument): - def task_exited(self, task: Task) -> Never: + def task_exited(self, task: Task) -> NoReturn: raise AssertionError("this should never happen") # pragma: no cover @property - def after_run(self) -> Never: + def after_run(self) -> NoReturn: raise ValueError("oops") async def main() -> None: diff --git a/src/trio/_core/_tests/test_ki.py b/src/trio/_core/_tests/test_ki.py index 47e092bc3a..9b72cfb273 100644 --- a/src/trio/_core/_tests/test_ki.py +++ b/src/trio/_core/_tests/test_ki.py @@ -6,7 +6,7 @@ import sys import threading import weakref -from typing import TYPE_CHECKING, TypeVar +from typing import TYPE_CHECKING, Never, TypeVar import outcome import pytest @@ -33,7 +33,6 @@ Iterator, ) from types import AsyncGeneratorType - from typing import Never from ..._core import Abort, RaiseCancelT diff --git a/src/trio/_core/_tests/test_run.py b/src/trio/_core/_tests/test_run.py index 5d16f248b0..d518ce913b 100644 --- a/src/trio/_core/_tests/test_run.py +++ b/src/trio/_core/_tests/test_run.py @@ -16,7 +16,7 @@ suppress, ) from math import inf, nan -from typing import TYPE_CHECKING, Never, TypeVar +from typing import TYPE_CHECKING, NoReturn, TypeVar from unittest import mock import outcome @@ -92,7 +92,7 @@ async def trivial2(x: T) -> T: def test_initial_task_error() -> None: - async def main(x: object) -> Never: + async def main(x: object) -> NoReturn: raise ValueError(x) with pytest.raises(ValueError, match=r"^17$") as excinfo: @@ -137,7 +137,7 @@ async def test_nursery_main_block_error_basic() -> None: async def test_child_crash_basic() -> None: my_exc = ValueError("uh oh") - async def erroring() -> Never: + async def erroring() -> NoReturn: raise my_exc with pytest.RaisesGroup(pytest.RaisesExc(check=lambda e: e is my_exc)): @@ -174,7 +174,7 @@ async def looper() -> None: print("looper cancelled") looper_record.append("cancelled") - async def crasher() -> Never: + async def crasher() -> NoReturn: raise ValueError("argh") async def main() -> None: @@ -191,10 +191,10 @@ async def main() -> None: def test_main_and_task_both_crash() -> None: # If main crashes and there's also a task crash, then we get both in an # ExceptionGroup - async def crasher() -> Never: + async def crasher() -> NoReturn: raise ValueError - async def main() -> Never: + async def main() -> NoReturn: async with _core.open_nursery() as nursery: nursery.start_soon(crasher) raise KeyError @@ -204,7 +204,7 @@ async def main() -> Never: def test_two_child_crashes() -> None: - async def crasher(etype: type[Exception]) -> Never: + async def crasher(etype: type[Exception]) -> NoReturn: raise etype async def main() -> None: @@ -217,7 +217,7 @@ async def main() -> None: async def test_child_crash_wakes_parent() -> None: - async def crasher() -> Never: + async def crasher() -> NoReturn: raise ValueError("this is a crash") with pytest.RaisesGroup(pytest.RaisesExc(ValueError, match="^this is a crash$")): @@ -454,7 +454,7 @@ async def test_cancel_edge_cases() -> None: async def test_cancel_scope_exceptiongroup_filtering() -> None: - async def crasher() -> Never: + async def crasher() -> NoReturn: raise KeyError # This is outside the outer scope, so all the Cancelled @@ -1081,7 +1081,7 @@ async def system_task(x: int) -> None: # intentionally make a system task crash def test_system_task_crash() -> None: - async def crasher() -> Never: + async def crasher() -> NoReturn: raise KeyError async def main() -> None: @@ -1093,10 +1093,10 @@ async def main() -> None: def test_system_task_crash_ExceptionGroup() -> None: - async def crasher1() -> Never: + async def crasher1() -> NoReturn: raise KeyError - async def crasher2() -> Never: + async def crasher2() -> NoReturn: raise ValueError async def system_task() -> None: @@ -1155,7 +1155,7 @@ async def main() -> None: def test_system_task_crash_KeyboardInterrupt() -> None: - async def ki() -> Never: + async def ki() -> NoReturn: raise KeyboardInterrupt async def main() -> None: @@ -1392,7 +1392,7 @@ async def inner() -> None: async def test_nursery_exception_chaining_doesnt_make_context_loops() -> None: - async def crasher() -> Never: + async def crasher() -> NoReturn: raise KeyError # the ExceptionGroup should not have the KeyError or ValueError as context @@ -2192,7 +2192,7 @@ async def test_nursery_explicit_exception() -> None: async def test_nursery_stop_iteration() -> None: - async def fail() -> Never: + async def fail() -> NoReturn: raise ValueError with pytest.RaisesGroup(StopIteration, ValueError): @@ -2259,7 +2259,7 @@ async def __anext__(self) -> list[int]: async def test_traceback_frame_removal() -> None: - async def my_child_task() -> Never: + async def my_child_task() -> NoReturn: raise KeyError() def check_traceback(exc: KeyError) -> bool: @@ -2611,7 +2611,7 @@ async def do_a_cancel() -> None: cscope.cancel() await sleep_forever() - async def crasher() -> Never: + async def crasher() -> NoReturn: raise ValueError("this is a crash") old_flags = gc.get_debug() @@ -2648,7 +2648,7 @@ async def test_cancel_scope_exit_doesnt_create_cyclic_garbage() -> None: # https://github.com/python-trio/trio/pull/2063 gc.collect() - async def crasher() -> Never: + async def crasher() -> NoReturn: raise ValueError("this is a crash") old_flags = gc.get_debug() @@ -2764,7 +2764,7 @@ def test_setting_strict_exception_groups( setting of strict_exception_groups. """ - async def raise_error() -> Never: + async def raise_error() -> NoReturn: raise RuntimeError("test error") async def main() -> None: @@ -2803,7 +2803,7 @@ async def test_nursery_collapse(strict: bool | None) -> None: depending on strict_exception_groups value when CancelledErrors are stripped from it. """ - async def raise_error() -> Never: + async def raise_error() -> NoReturn: raise RuntimeError("test error") # mypy requires explicit type for conditional expression diff --git a/src/trio/_core/_tests/test_thread_cache.py b/src/trio/_core/_tests/test_thread_cache.py index 2f6bb5c890..77d0cc6d5e 100644 --- a/src/trio/_core/_tests/test_thread_cache.py +++ b/src/trio/_core/_tests/test_thread_cache.py @@ -7,7 +7,7 @@ import warnings from contextlib import contextmanager from queue import Queue -from typing import TYPE_CHECKING, Never +from typing import TYPE_CHECKING, NoReturn import pytest @@ -25,7 +25,7 @@ def test_thread_cache_basics() -> None: q: Queue[Outcome[object]] = Queue() - def fn() -> Never: + def fn() -> NoReturn: raise RuntimeError("hi") def deliver(outcome: Outcome[object]) -> None: @@ -185,7 +185,7 @@ def test_raise_in_deliver(capfd: pytest.CaptureFixture[str]) -> None: def track_threads() -> None: seen_threads.add(threading.current_thread()) - def deliver(_: object) -> Never: + def deliver(_: object) -> NoReturn: done.set() raise RuntimeError("don't do this") diff --git a/src/trio/_core/_windows_cffi.py b/src/trio/_core/_windows_cffi.py index c8fcf5adfe..cafae17fa2 100644 --- a/src/trio/_core/_windows_cffi.py +++ b/src/trio/_core/_windows_cffi.py @@ -1,7 +1,7 @@ from __future__ import annotations import enum -from typing import TYPE_CHECKING, Never, NewType, Protocol, TypeAlias, cast +from typing import TYPE_CHECKING, NewType, NoReturn, Protocol, TypeAlias, cast if TYPE_CHECKING: import cffi @@ -294,7 +294,7 @@ def raise_winerror( *, filename: str | None = None, filename2: str | None = None, -) -> Never: +) -> NoReturn: # assert sys.platform == "win32" # TODO: make this work in MyPy # ... in the meanwhile, ffi.getwinerror() is undefined on non-Windows, necessitating the type # ignores. diff --git a/src/trio/_highlevel_serve_listeners.py b/src/trio/_highlevel_serve_listeners.py index 9316a303fe..008caaabea 100644 --- a/src/trio/_highlevel_serve_listeners.py +++ b/src/trio/_highlevel_serve_listeners.py @@ -4,7 +4,7 @@ import logging import os from collections.abc import Awaitable, Callable -from typing import Any, Never, TypeVar +from typing import Any, NoReturn, TypeVar import trio @@ -40,7 +40,7 @@ async def _serve_one_listener( listener: trio.abc.Listener[StreamT], handler_nursery: trio.Nursery, handler: Handler[StreamT], -) -> Never: +) -> NoReturn: async with listener: while True: try: @@ -73,7 +73,7 @@ async def serve_listeners( # type: ignore[explicit-any] *, handler_nursery: trio.Nursery | None = None, task_status: trio.TaskStatus[list[ListenerT]] = trio.TASK_STATUS_IGNORED, -) -> Never: +) -> NoReturn: r"""Listen for incoming connections on ``listeners``, and for each one start a task running ``handler(stream)``. diff --git a/src/trio/_highlevel_ssl_helpers.py b/src/trio/_highlevel_ssl_helpers.py index 150de2d15d..3166172568 100644 --- a/src/trio/_highlevel_ssl_helpers.py +++ b/src/trio/_highlevel_ssl_helpers.py @@ -1,7 +1,7 @@ from __future__ import annotations import ssl -from typing import TYPE_CHECKING, Never, TypeVar +from typing import TYPE_CHECKING, NoReturn, TypeVar import trio @@ -117,7 +117,7 @@ async def serve_ssl_over_tcp( task_status: trio.TaskStatus[ list[trio.SSLListener[SocketStream]] ] = trio.TASK_STATUS_IGNORED, -) -> Never: +) -> NoReturn: """Listen for incoming TCP connections, and for each one start a task running ``handler(stream)``. diff --git a/src/trio/_tests/pytest_plugin.py b/src/trio/_tests/pytest_plugin.py index fa63a9b1b1..b929ae3a73 100644 --- a/src/trio/_tests/pytest_plugin.py +++ b/src/trio/_tests/pytest_plugin.py @@ -1,7 +1,7 @@ from __future__ import annotations import inspect -from typing import Never +from typing import NoReturn import pytest @@ -53,7 +53,7 @@ def pytest_pyfunc_call(pyfuncitem: pytest.Function) -> None: pyfuncitem.obj = trio_test(pyfuncitem.obj) -def maybe_ignore_import_error(error: ImportError) -> Never: +def maybe_ignore_import_error(error: ImportError) -> NoReturn: if SKIP_OPTIONAL_IMPORTS or (SKIP_SSL_IMPORTS and error.name == "cryptography"): pytest.skip(error.msg, allow_module_level=True) else: # pragma: no cover diff --git a/src/trio/_tests/test_dtls.py b/src/trio/_tests/test_dtls.py index d7509ba6c6..ea77822197 100644 --- a/src/trio/_tests/test_dtls.py +++ b/src/trio/_tests/test_dtls.py @@ -3,7 +3,7 @@ import random from contextlib import asynccontextmanager from itertools import count -from typing import TYPE_CHECKING, Never +from typing import TYPE_CHECKING, NoReturn import attrs import pytest @@ -931,7 +931,7 @@ async def test_association_replaced_before_handshake_starts( fn.enable() # This test shouldn't send any packets - def route_packet(packet: UDPPacket) -> Never: # pragma: no cover + def route_packet(packet: UDPPacket) -> NoReturn: # pragma: no cover raise AssertionError() fn.route_packet = route_packet # type: ignore[assignment] # TODO add type annotations for FakeNet diff --git a/src/trio/_tests/test_highlevel_generic.py b/src/trio/_tests/test_highlevel_generic.py index d03438e29b..a1a394aba5 100644 --- a/src/trio/_tests/test_highlevel_generic.py +++ b/src/trio/_tests/test_highlevel_generic.py @@ -1,6 +1,6 @@ from __future__ import annotations -from typing import Never +from typing import NoReturn import attrs import pytest @@ -79,12 +79,12 @@ async def test_StapledStream_with_erroring_close() -> None: # Make sure that if one of the aclose methods errors out, then the other # one still gets called. class BrokenSendStream(RecordSendStream): - async def aclose(self) -> Never: + async def aclose(self) -> NoReturn: await super().aclose() raise ValueError("send error") class BrokenReceiveStream(RecordReceiveStream): - async def aclose(self) -> Never: + async def aclose(self) -> NoReturn: await super().aclose() raise ValueError("recv error") diff --git a/src/trio/_tests/test_highlevel_serve_listeners.py b/src/trio/_tests/test_highlevel_serve_listeners.py index 6f84b1221a..1a6ac94690 100644 --- a/src/trio/_tests/test_highlevel_serve_listeners.py +++ b/src/trio/_tests/test_highlevel_serve_listeners.py @@ -2,7 +2,7 @@ import errno from functools import partial -from typing import TYPE_CHECKING, Never, cast +from typing import TYPE_CHECKING, NoReturn, cast import attrs import pytest @@ -113,7 +113,7 @@ async def test_serve_listeners_accept_unrecognized_error() -> None: for error in [KeyError(), OSError(errno.ECONNABORTED, "ECONNABORTED")]: listener = MemoryListener() - async def raise_error() -> Never: + async def raise_error() -> NoReturn: raise error # noqa: B023 # Set from loop def check_error(e: BaseException) -> bool: @@ -131,7 +131,7 @@ async def test_serve_listeners_accept_capacity_error( ) -> None: listener = MemoryListener() - async def raise_EMFILE() -> Never: + async def raise_EMFILE() -> NoReturn: raise OSError(errno.EMFILE, "out of file descriptors") listener.accept_hook = raise_EMFILE @@ -161,7 +161,7 @@ class Done(Exception): async def connection_watcher( *, task_status: TaskStatus[Nursery] = trio.TASK_STATUS_IGNORED, - ) -> Never: + ) -> NoReturn: async with trio.open_nursery() as nursery: task_status.started(nursery) await wait_all_tasks_blocked() diff --git a/src/trio/_tests/test_highlevel_ssl_helpers.py b/src/trio/_tests/test_highlevel_ssl_helpers.py index 3ba5caad00..80b5e30fab 100644 --- a/src/trio/_tests/test_highlevel_ssl_helpers.py +++ b/src/trio/_tests/test_highlevel_ssl_helpers.py @@ -1,7 +1,7 @@ from __future__ import annotations from functools import partial -from typing import TYPE_CHECKING, Never, cast +from typing import TYPE_CHECKING, NoReturn, cast import attrs import pytest @@ -61,7 +61,7 @@ async def getnameinfo( self, sockaddr: tuple[str, int] | tuple[str, int, int, int], flags: int, - ) -> Never: # pragma: no cover + ) -> NoReturn: # pragma: no cover raise NotImplementedError diff --git a/src/trio/_tests/test_signals.py b/src/trio/_tests/test_signals.py index 57d6c68924..501ae1e80a 100644 --- a/src/trio/_tests/test_signals.py +++ b/src/trio/_tests/test_signals.py @@ -1,7 +1,7 @@ from __future__ import annotations import signal -from typing import TYPE_CHECKING, Never +from typing import TYPE_CHECKING, NoReturn import pytest @@ -169,7 +169,7 @@ def direct_handler(signo: int, frame: FrameType | None) -> None: # Check exception chaining if there are multiple exception-raising # handlers - def raise_handler(signum: int, frame: FrameType | None) -> Never: + def raise_handler(signum: int, frame: FrameType | None) -> NoReturn: raise RuntimeError(signum) with _signal_handler({signal.SIGILL, signal.SIGFPE}, raise_handler): diff --git a/src/trio/_tests/test_ssl.py b/src/trio/_tests/test_ssl.py index 9f72f19ed6..a9a4298efc 100644 --- a/src/trio/_tests/test_ssl.py +++ b/src/trio/_tests/test_ssl.py @@ -8,7 +8,7 @@ from contextlib import asynccontextmanager, contextmanager, suppress from functools import partial from ssl import SSLContext -from typing import TYPE_CHECKING, Any, Never, TypeAlias +from typing import TYPE_CHECKING, Any, NoReturn, TypeAlias import pytest @@ -1022,7 +1022,7 @@ async def test_send_all_fails_in_the_middle(client_ctx: SSLContext) -> None: nursery.start_soon(client.do_handshake) nursery.start_soon(server.do_handshake) - async def bad_hook() -> Never: + async def bad_hook() -> NoReturn: raise KeyError client.transport_stream.send_stream.send_all_hook = bad_hook @@ -1144,7 +1144,7 @@ async def test_ssl_only_closes_stream_once(client_ctx: SSLContext) -> None: client_orig_close_hook = client.transport_stream.send_stream.close_hook transport_close_count = 0 - def close_hook() -> Never: + def close_hook() -> NoReturn: nonlocal transport_close_count assert client_orig_close_hook is not None client_orig_close_hook() @@ -1200,7 +1200,7 @@ async def server_expect_clean_eof() -> None: async def test_send_error_during_handshake(client_ctx: SSLContext) -> None: client, _server = ssl_memory_stream_pair(client_ctx) - async def bad_hook() -> Never: + async def bad_hook() -> NoReturn: raise KeyError client.transport_stream.send_stream.send_all_hook = bad_hook @@ -1217,7 +1217,7 @@ async def bad_hook() -> Never: async def test_receive_error_during_handshake(client_ctx: SSLContext) -> None: client, server = ssl_memory_stream_pair(client_ctx) - async def bad_hook() -> Never: + async def bad_hook() -> NoReturn: raise KeyError client.transport_stream.receive_stream.receive_some_hook = bad_hook diff --git a/src/trio/_tests/test_subprocess.py b/src/trio/_tests/test_subprocess.py index 82c3438d0c..be762c0756 100644 --- a/src/trio/_tests/test_subprocess.py +++ b/src/trio/_tests/test_subprocess.py @@ -14,7 +14,7 @@ from typing import ( TYPE_CHECKING, Any, - Never, + NoReturn, TypeAlias, ) from unittest import mock @@ -690,7 +690,7 @@ async def do_stuff() -> None: async def test_warn_on_failed_cancel_terminate(monkeypatch: pytest.MonkeyPatch) -> None: original_terminate = Process.terminate - def broken_terminate(self: Process) -> Never: + def broken_terminate(self: Process) -> NoReturn: original_terminate(self) raise OSError("whoops") diff --git a/src/trio/_tests/test_threads.py b/src/trio/_tests/test_threads.py index 371d315cad..f349850ffe 100644 --- a/src/trio/_tests/test_threads.py +++ b/src/trio/_tests/test_threads.py @@ -10,7 +10,7 @@ from functools import partial from typing import ( TYPE_CHECKING, - Never, + NoReturn, TypeVar, ) @@ -87,7 +87,7 @@ def f1(record: RecordType) -> int: await check_case(from_thread_run_sync, f1, ("got", 2), trio_token=token) - def f2(record: RecordType) -> Never: + def f2(record: RecordType) -> NoReturn: assert not _core.currently_ki_protected() record.append(("f", threading.current_thread())) raise ValueError @@ -102,7 +102,7 @@ async def f3(record: RecordType) -> int: await check_case(from_thread_run, f3, ("got", 3), trio_token=token) - async def f4(record: RecordType) -> Never: + async def f4(record: RecordType) -> NoReturn: assert not _core.currently_ki_protected() await _core.checkpoint() record.append(("f", threading.current_thread())) @@ -327,7 +327,7 @@ def f(x: T) -> tuple[T, threading.Thread]: assert x == 1 assert child_thread != trio_thread - def g() -> Never: + def g() -> NoReturn: raise ValueError(threading.current_thread()) with pytest.raises( @@ -583,7 +583,7 @@ class BadCapacityLimiter: async def acquire_on_behalf_of(self, borrower: Task) -> None: record.append("acquire") - def release_on_behalf_of(self, borrower: Task) -> Never: + def release_on_behalf_of(self, borrower: Task) -> NoReturn: record.append("release") raise ValueError("release on behalf") @@ -608,7 +608,7 @@ async def test_run_in_worker_thread_fail_to_spawn( monkeypatch: pytest.MonkeyPatch, ) -> None: # Test the unlikely but possible case where trying to spawn a thread fails - def bad_start(self: object, *args: object) -> Never: + def bad_start(self: object, *args: object) -> NoReturn: raise RuntimeError("the engines canna take it captain") monkeypatch.setattr(_core._thread_cache.ThreadCache, "start_thread_soon", bad_start) diff --git a/src/trio/_timeouts.py b/src/trio/_timeouts.py index b1bb23a06f..d95cbe4cfc 100644 --- a/src/trio/_timeouts.py +++ b/src/trio/_timeouts.py @@ -3,7 +3,7 @@ import math import sys from contextlib import contextmanager -from typing import TYPE_CHECKING, Never +from typing import TYPE_CHECKING, NoReturn import trio @@ -58,7 +58,7 @@ def move_on_after( ) -async def sleep_forever() -> Never: +async def sleep_forever() -> NoReturn: """Pause execution of the current task forever (or until cancelled). Equivalent to calling ``await sleep(math.inf)``, except that if manually diff --git a/src/trio/_util.py b/src/trio/_util.py index dc5eee9202..b95b13b928 100644 --- a/src/trio/_util.py +++ b/src/trio/_util.py @@ -10,6 +10,7 @@ TYPE_CHECKING, Any, Never, + NoReturn, TypeVar, TypeVarTuple, Unpack, @@ -55,7 +56,7 @@ def is_main_thread() -> bool: def coroutine_or_error( async_fn: Callable[[Unpack[PosArgsT]], Awaitable[RetT]], *args: Unpack[PosArgsT], -) -> collections.abc.Coroutine[object, Never, RetT]: +) -> collections.abc.Coroutine[object, NoReturn, RetT]: def _return_value_looks_like_wrong_library(value: object) -> bool: # Returned by legacy @asyncio.coroutine functions, which includes # a surprising proportion of asyncio builtins. @@ -224,7 +225,7 @@ def fix_one(qualname: str, name: str, obj: object) -> None: fix_one(objname, objname, obj) -def _init_final_cls(cls: type[object]) -> Never: +def _init_final_cls(cls: type[object]) -> NoReturn: """Raises an exception when a final class is subclassed.""" raise TypeError(f"{cls.__module__}.{cls.__qualname__} does not support subclassing") @@ -319,7 +320,7 @@ def wraps( # type: ignore[explicit-any] from functools import wraps # noqa: F401 # this is re-exported -def raise_saving_context(exc: BaseException) -> Never: +def raise_saving_context(exc: BaseException) -> NoReturn: """This helper allows re-raising an exception without __context__ being set.""" # cause does not need special handling, we simply avoid using `raise .. from ..` # __suppress_context__ also does not need handling, it's only set if modifying cause @@ -339,7 +340,7 @@ class MultipleExceptionError(Exception): def raise_single_exception_from_group( eg: BaseExceptionGroup[BaseException], -) -> Never: +) -> NoReturn: """This function takes an exception group that is assumed to have at most one non-cancelled exception, which it reraises as a standalone exception. diff --git a/src/trio/testing/_fake_net.py b/src/trio/testing/_fake_net.py index 24ff1c69b5..b0bef1cd05 100644 --- a/src/trio/testing/_fake_net.py +++ b/src/trio/testing/_fake_net.py @@ -14,7 +14,7 @@ import os import socket import sys -from typing import TYPE_CHECKING, Any, Never, Self, TypeAlias, overload +from typing import TYPE_CHECKING, Any, NoReturn, Self, TypeAlias, overload import attrs @@ -59,7 +59,7 @@ def _localhost_ip_for(family: int) -> IPAddress: # pragma: no cover raise NotImplementedError("Unhandled ip address family") -def _fake_err(code: int) -> Never: +def _fake_err(code: int) -> NoReturn: raise OSError(code, os.strerror(code)) @@ -289,7 +289,7 @@ async def bind(self, addr: object) -> None: self._fake_net._bind(binding, self) self._binding = binding - async def connect(self, peer: object) -> Never: + async def connect(self, peer: object) -> NoReturn: raise NotImplementedError("FakeNet does not (yet) support connected sockets") async def _sendmsg(