diff --git a/src/trio/_abc.py b/src/trio/_abc.py index 306ee227f..cba058c4d 100644 --- a/src/trio/_abc.py +++ b/src/trio/_abc.py @@ -198,9 +198,7 @@ async def getaddrinfo( @abstractmethod async def getnameinfo( - self, - sockaddr: tuple[str, int] | tuple[str, int, int, int], - flags: int, + self, sockaddr: tuple[str, int] | tuple[str, int, int, int], flags: int ) -> tuple[str, str]: """A custom implementation of :func:`~trio.socket.getnameinfo`. diff --git a/src/trio/_channel.py b/src/trio/_channel.py index 6410d9120..43598050e 100644 --- a/src/trio/_channel.py +++ b/src/trio/_channel.py @@ -2,10 +2,7 @@ from collections import OrderedDict, deque from math import inf -from typing import ( - TYPE_CHECKING, - Generic, -) +from typing import TYPE_CHECKING, Generic import attrs from outcome import Error, Value @@ -81,10 +78,7 @@ def _open_memory_channel( if max_buffer_size < 0: raise ValueError("max_buffer_size must be >= 0") state: MemoryChannelState[T] = MemoryChannelState(max_buffer_size) - return ( - MemorySendChannel[T]._create(state), - MemoryReceiveChannel[T]._create(state), - ) + return (MemorySendChannel[T]._create(state), MemoryReceiveChannel[T]._create(state)) # This workaround requires python3.9+, once older python versions are not supported @@ -94,8 +88,7 @@ def _open_memory_channel( # written as a class so you can say open_memory_channel[int](5) class open_memory_channel(tuple["MemorySendChannel[T]", "MemoryReceiveChannel[T]"]): def __new__( # type: ignore[misc] # "must return a subtype" - cls, - max_buffer_size: int | float, # noqa: PYI041 + cls, max_buffer_size: int | float # noqa: PYI041 ) -> tuple[MemorySendChannel[T], MemoryReceiveChannel[T]]: return _open_memory_channel(max_buffer_size) diff --git a/src/trio/_core/_asyncgens.py b/src/trio/_core/_asyncgens.py index b3b689575..1d729d225 100644 --- a/src/trio/_core/_asyncgens.py +++ b/src/trio/_core/_asyncgens.py @@ -34,10 +34,7 @@ @_core.disable_ki_protection def _call_without_ki_protection( - f: Callable[_P, _R], - /, - *args: _P.args, - **kwargs: _P.kwargs, + f: Callable[_P, _R], /, *args: _P.args, **kwargs: _P.kwargs ) -> _R: return f(*args, **kwargs) @@ -81,8 +78,7 @@ def firstiter(agen: AsyncGeneratorType[object, NoReturn]) -> None: self.prev_hooks.firstiter(agen) def finalize_in_trio_context( - agen: AsyncGeneratorType[object, NoReturn], - agen_name: str, + agen: AsyncGeneratorType[object, NoReturn], agen_name: str ) -> None: try: runner.spawn_system_task( @@ -110,9 +106,7 @@ def finalizer(agen: AsyncGeneratorType[object, NoReturn]) -> None: agen_name = name_asyncgen(agen) if is_ours: runner.entry_queue.run_sync_soon( - finalize_in_trio_context, - agen, - agen_name, + finalize_in_trio_context, agen, agen_name ) # Do this last, because it might raise an exception @@ -151,7 +145,7 @@ def finalizer(agen: AsyncGeneratorType[object, NoReturn]) -> None: raise RuntimeError( f"Non-Trio async generator {agen_name!r} awaited something " "during finalization; install a finalization hook to " - "support this, or wrap it in 'async with aclosing(...):'", + "support this, or wrap it in 'async with aclosing(...):'" ) self.prev_hooks = sys.get_asyncgen_hooks() @@ -174,7 +168,7 @@ async def finalize_remaining(self, runner: _run.Runner) -> None: # them was an asyncgen finalizer that snuck in under the wire. runner.entry_queue.run_sync_soon(runner.reschedule, runner.init_task) await _core.wait_task_rescheduled( - lambda _: _core.Abort.FAILED, # pragma: no cover + lambda _: _core.Abort.FAILED # pragma: no cover ) self.alive.update(self.trailing_needs_finalize) self.trailing_needs_finalize.clear() @@ -221,9 +215,7 @@ def close(self) -> None: sys.set_asyncgen_hooks(*self.prev_hooks) async def _finalize_one( - self, - agen: AsyncGeneratorType[object, NoReturn], - name: object, + self, agen: AsyncGeneratorType[object, NoReturn], name: object ) -> None: try: # This shield ensures that finalize_asyncgen never exits diff --git a/src/trio/_core/_concat_tb.py b/src/trio/_core/_concat_tb.py index 82e525137..01f93199c 100644 --- a/src/trio/_core/_concat_tb.py +++ b/src/trio/_core/_concat_tb.py @@ -95,11 +95,7 @@ def controller( # type: ignore[no-any-unimported] # no missing test we could add, and no value in coverage nagging # us about adding one. if ( - operation.opname - in { - "__getattribute__", - "__getattr__", - } + operation.opname in {"__getattribute__", "__getattr__"} and operation.args[0] == "tb_next" ) or TYPE_CHECKING: # pragma: no cover return tb_next @@ -107,8 +103,7 @@ def controller( # type: ignore[no-any-unimported] return operation.delegate() # type: ignore[no-any-return] return cast( - TracebackType, - tputil.make_proxy(controller, type(base_tb), base_tb), + TracebackType, tputil.make_proxy(controller, type(base_tb), base_tb) ) # Returns proxy to traceback @@ -116,8 +111,7 @@ def controller( # type: ignore[no-any-unimported] # `strict_exception_groups=False`. Once that is retired this function and its helper can # be removed as well. def concat_tb( - head: TracebackType | None, - tail: TracebackType | None, + head: TracebackType | None, tail: TracebackType | None ) -> TracebackType | None: # We have to use an iterative algorithm here, because in the worst case # this might be a RecursionError stack that is by definition too deep to diff --git a/src/trio/_core/_entry_queue.py b/src/trio/_core/_entry_queue.py index 0691de351..01ea92260 100644 --- a/src/trio/_core/_entry_queue.py +++ b/src/trio/_core/_entry_queue.py @@ -81,7 +81,7 @@ async def kill_everything( # noqa: RUF029 # await not used parent_nursery = _core.current_task().parent_nursery if parent_nursery is None: raise AssertionError( - "Internal error: `parent_nursery` should never be `None`", + "Internal error: `parent_nursery` should never be `None`" ) from exc # pragma: no cover parent_nursery.start_soon(kill_everything, exc) diff --git a/src/trio/_core/_generated_io_kqueue.py b/src/trio/_core/_generated_io_kqueue.py index 016704eac..556d29e1f 100644 --- a/src/trio/_core/_generated_io_kqueue.py +++ b/src/trio/_core/_generated_io_kqueue.py @@ -45,8 +45,7 @@ def current_kqueue() -> select.kqueue: @enable_ki_protection def monitor_kevent( - ident: int, - filter: int, + ident: int, filter: int ) -> AbstractContextManager[_core.UnboundedQueue[select.kevent]]: """TODO: these are implemented, but are currently more of a sketch than anything real. See `#26 @@ -60,9 +59,7 @@ def monitor_kevent( @enable_ki_protection async def wait_kevent( - ident: int, - filter: int, - abort_func: Callable[[RaiseCancelT], Abort], + ident: int, filter: int, abort_func: Callable[[RaiseCancelT], Abort] ) -> Abort: """TODO: these are implemented, but are currently more of a sketch than anything real. See `#26 @@ -70,9 +67,7 @@ async def wait_kevent( """ try: return await GLOBAL_RUN_CONTEXT.runner.io_manager.wait_kevent( - ident, - filter, - abort_func, + ident, filter, abort_func ) except AttributeError: raise RuntimeError("must be called from async context") from None diff --git a/src/trio/_core/_generated_io_windows.py b/src/trio/_core/_generated_io_windows.py index 745fa4fc4..211f81215 100644 --- a/src/trio/_core/_generated_io_windows.py +++ b/src/trio/_core/_generated_io_windows.py @@ -136,8 +136,7 @@ async def wait_overlapped(handle_: int | CData, lpOverlapped: CData | int) -> ob """ try: return await GLOBAL_RUN_CONTEXT.runner.io_manager.wait_overlapped( - handle_, - lpOverlapped, + handle_, lpOverlapped ) except AttributeError: raise RuntimeError("must be called from async context") from None @@ -145,9 +144,7 @@ async def wait_overlapped(handle_: int | CData, lpOverlapped: CData | int) -> ob @enable_ki_protection async def write_overlapped( - handle: int | CData, - data: Buffer, - file_offset: int = 0, + handle: int | CData, data: Buffer, file_offset: int = 0 ) -> int: """TODO: these are implemented, but are currently more of a sketch than anything real. See `#26 @@ -156,9 +153,7 @@ async def write_overlapped( """ try: return await GLOBAL_RUN_CONTEXT.runner.io_manager.write_overlapped( - handle, - data, - file_offset, + handle, data, file_offset ) except AttributeError: raise RuntimeError("must be called from async context") from None @@ -166,9 +161,7 @@ async def write_overlapped( @enable_ki_protection async def readinto_overlapped( - handle: int | CData, - buffer: Buffer, - file_offset: int = 0, + handle: int | CData, buffer: Buffer, file_offset: int = 0 ) -> int: """TODO: these are implemented, but are currently more of a sketch than anything real. See `#26 @@ -177,9 +170,7 @@ async def readinto_overlapped( """ try: return await GLOBAL_RUN_CONTEXT.runner.io_manager.readinto_overlapped( - handle, - buffer, - file_offset, + handle, buffer, file_offset ) except AttributeError: raise RuntimeError("must be called from async context") from None diff --git a/src/trio/_core/_generated_run.py b/src/trio/_core/_generated_run.py index 67d70d907..db1454e6c 100644 --- a/src/trio/_core/_generated_run.py +++ b/src/trio/_core/_generated_run.py @@ -186,10 +186,7 @@ def spawn_system_task( """ try: return GLOBAL_RUN_CONTEXT.runner.spawn_system_task( - async_fn, - *args, - name=name, - context=context, + async_fn, *args, name=name, context=context ) except AttributeError: raise RuntimeError("must be called from async context") from None diff --git a/src/trio/_core/_instrumentation.py b/src/trio/_core/_instrumentation.py index 40bddd1a2..f807a9c3d 100644 --- a/src/trio/_core/_instrumentation.py +++ b/src/trio/_core/_instrumentation.py @@ -91,11 +91,7 @@ def remove_instrument(self, instrument: Instrument) -> None: if not instruments: del self[hookname] - def call( - self, - hookname: str, - *args: object, - ) -> None: + def call(self, hookname: str, *args: object) -> None: """Call hookname(*args) on each applicable instrument. You must first check whether there are any instruments installed for diff --git a/src/trio/_core/_io_epoll.py b/src/trio/_core/_io_epoll.py index 5e05f0813..29b378a01 100644 --- a/src/trio/_core/_io_epoll.py +++ b/src/trio/_core/_io_epoll.py @@ -205,7 +205,7 @@ class EpollIOManager: _epoll: select.epoll = attrs.Factory(lambda: select.epoll()) # {fd: EpollWaiters} _registered: defaultdict[int, EpollWaiters] = attrs.Factory( - lambda: defaultdict(EpollWaiters), + lambda: defaultdict(EpollWaiters) ) _force_wakeup: WakeupSocketpair = attrs.Factory(WakeupSocketpair) _force_wakeup_fd: int | None = None @@ -298,7 +298,7 @@ async def _epoll_wait(self, fd: int | _HasFileNo, attr_name: str) -> None: waiters = self._registered[fd] if getattr(waiters, attr_name) is not None: raise _core.BusyResourceError( - "another task is already reading / writing this fd", + "another task is already reading / writing this fd" ) setattr(waiters, attr_name, _core.current_task()) self._update_registrations(fd) diff --git a/src/trio/_core/_io_kqueue.py b/src/trio/_core/_io_kqueue.py index 6c440920d..766be38d1 100644 --- a/src/trio/_core/_io_kqueue.py +++ b/src/trio/_core/_io_kqueue.py @@ -45,9 +45,7 @@ class KqueueIOManager: def __attrs_post_init__(self) -> None: force_wakeup_event = select.kevent( - self._force_wakeup.wakeup_sock, - select.KQ_FILTER_READ, - select.KQ_EV_ADD, + self._force_wakeup.wakeup_sock, select.KQ_FILTER_READ, select.KQ_EV_ADD ) self._kqueue.control([force_wakeup_event], 0) self._force_wakeup_fd = self._force_wakeup.wakeup_sock.fileno() @@ -122,9 +120,7 @@ def current_kqueue(self) -> select.kqueue: @contextmanager @_public def monitor_kevent( - self, - ident: int, - filter: int, + self, ident: int, filter: int ) -> Iterator[_core.UnboundedQueue[select.kevent]]: """TODO: these are implemented, but are currently more of a sketch than anything real. See `#26 @@ -133,7 +129,7 @@ def monitor_kevent( key = (ident, filter) if key in self._registered: raise _core.BusyResourceError( - "attempt to register multiple listeners for same ident/filter pair", + "attempt to register multiple listeners for same ident/filter pair" ) q = _core.UnboundedQueue[select.kevent]() self._registered[key] = q @@ -144,10 +140,7 @@ def monitor_kevent( @_public async def wait_kevent( - self, - ident: int, - filter: int, - abort_func: Callable[[RaiseCancelT], Abort], + self, ident: int, filter: int, abort_func: Callable[[RaiseCancelT], Abort] ) -> Abort: """TODO: these are implemented, but are currently more of a sketch than anything real. See `#26 @@ -156,7 +149,7 @@ async def wait_kevent( key = (ident, filter) if key in self._registered: raise _core.BusyResourceError( - "attempt to register multiple listeners for same ident/filter pair", + "attempt to register multiple listeners for same ident/filter pair" ) self._registered[key] = _core.current_task() @@ -169,11 +162,7 @@ def abort(raise_cancel: RaiseCancelT) -> Abort: # wait_task_rescheduled does not have its return type typed return await _core.wait_task_rescheduled(abort) # type: ignore[no-any-return] - async def _wait_common( - self, - fd: int | _HasFileNo, - filter: int, - ) -> None: + async def _wait_common(self, fd: int | _HasFileNo, filter: int) -> None: if not isinstance(fd, int): fd = fd.fileno() flags = select.KQ_EV_ADD | select.KQ_EV_ONESHOT @@ -290,5 +279,5 @@ def notify_closing(self, fd: int | _HasFileNo) -> None: # XX this is an interesting example of a case where being able # to close a queue would be useful... raise NotImplementedError( - "can't close an fd that monitor_kevent is using", + "can't close an fd that monitor_kevent is using" ) diff --git a/src/trio/_core/_io_windows.py b/src/trio/_core/_io_windows.py index c4325a286..64fec00fe 100644 --- a/src/trio/_core/_io_windows.py +++ b/src/trio/_core/_io_windows.py @@ -5,13 +5,7 @@ import socket import sys from contextlib import contextmanager -from typing import ( - TYPE_CHECKING, - Literal, - Protocol, - TypeVar, - cast, -) +from typing import TYPE_CHECKING, Literal, Protocol, TypeVar, cast import attrs from outcome import Value @@ -319,9 +313,7 @@ def _check(success: T) -> T: def _get_underlying_socket( - sock: _HasFileNo | int | Handle, - *, - which: WSAIoctls = WSAIoctls.SIO_BASE_HANDLE, + sock: _HasFileNo | int | Handle, *, which: WSAIoctls = WSAIoctls.SIO_BASE_HANDLE ) -> Handle: if hasattr(sock, "fileno"): sock = sock.fileno() @@ -372,8 +364,7 @@ def _get_base_socket(sock: _HasFileNo | int | Handle) -> Handle: sock = sock.fileno() sock = _handle(sock) next_sock = _get_underlying_socket( - sock, - which=WSAIoctls.SIO_BSP_HANDLE_POLL, + sock, which=WSAIoctls.SIO_BSP_HANDLE_POLL ) if next_sock == sock: # If BSP_HANDLE_POLL returns the same socket we already had, @@ -385,7 +376,7 @@ def _get_base_socket(sock: _HasFileNo | int | Handle) -> Handle: "return a different socket. Please file a bug at " "https://github.com/python-trio/trio/issues/new, " "and include the output of running: " - "netsh winsock show catalog", + "netsh winsock show catalog" ) from ex # Otherwise we've gotten at least one layer deeper, so # loop back around to keep digging. @@ -440,7 +431,7 @@ def __init__(self) -> None: self._all_afd_handles: list[Handle] = [] self._iocp = _check( - kernel32.CreateIoCompletionPort(INVALID_HANDLE_VALUE, ffi.NULL, 0, 0), + kernel32.CreateIoCompletionPort(INVALID_HANDLE_VALUE, ffi.NULL, 0, 0) ) self._events = ffi.new("OVERLAPPED_ENTRY[]", MAX_EVENTS) @@ -473,8 +464,7 @@ def __init__(self) -> None: # LSPs can in theory override this, but we believe that it never # actually happens in the wild (except Komodia) select_handle = _get_underlying_socket( - s, - which=WSAIoctls.SIO_BSP_HANDLE_SELECT, + s, which=WSAIoctls.SIO_BSP_HANDLE_SELECT ) try: # LSPs shouldn't override this... @@ -492,7 +482,7 @@ def __init__(self) -> None: "Please file a bug at " "https://github.com/python-trio/trio/issues/new, " "and include the output of running: " - "netsh winsock show catalog", + "netsh winsock show catalog" ) def close(self) -> None: @@ -528,11 +518,8 @@ def force_wakeup(self) -> None: assert self._iocp is not None _check( kernel32.PostQueuedCompletionStatus( - self._iocp, - 0, - CKeys.FORCE_WAKEUP, - ffi.NULL, - ), + self._iocp, 0, CKeys.FORCE_WAKEUP, ffi.NULL + ) ) def get_events(self, timeout: float) -> EventResult: @@ -544,13 +531,8 @@ def get_events(self, timeout: float) -> EventResult: assert self._iocp is not None _check( kernel32.GetQueuedCompletionStatusEx( - self._iocp, - self._events, - MAX_EVENTS, - received, - milliseconds, - 0, - ), + self._iocp, self._events, MAX_EVENTS, received, milliseconds, 0 + ) ) except OSError as exc: if exc.winerror != ErrorCodes.WAIT_TIMEOUT: # pragma: no cover @@ -591,8 +573,7 @@ def process_events(self, received: EventResult) -> None: overlapped = entry.lpOverlapped transferred = entry.dwNumberOfBytesTransferred info = CompletionKeyEventInfo( - lpOverlapped=overlapped, - dwNumberOfBytesTransferred=transferred, + lpOverlapped=overlapped, dwNumberOfBytesTransferred=transferred ) _core.reschedule(waiter, Value(info)) elif entry.lpCompletionKey == CKeys.LATE_CANCEL: @@ -615,7 +596,7 @@ def process_events(self, received: EventResult) -> None: exc = _core.TrioInternalError( f"Failed to cancel overlapped I/O in {waiter.name} and didn't " "receive the completion either. Did you forget to " - "call register_with_iocp()?", + "call register_with_iocp()?" ) # Raising this out of handle_io ensures that # the user will see our message even if some @@ -637,8 +618,7 @@ def process_events(self, received: EventResult) -> None: overlapped = int(ffi.cast("uintptr_t", entry.lpOverlapped)) transferred = entry.dwNumberOfBytesTransferred info = CompletionKeyEventInfo( - lpOverlapped=overlapped, - dwNumberOfBytesTransferred=transferred, + lpOverlapped=overlapped, dwNumberOfBytesTransferred=transferred ) queue.put_nowait(info) @@ -652,9 +632,8 @@ def _register_with_iocp(self, handle_: int | CData, completion_key: int) -> None # Ref: http://www.lenholgate.com/blog/2009/09/interesting-blog-posts-on-high-performance-servers.html _check( kernel32.SetFileCompletionNotificationModes( - handle, - CompletionModes.FILE_SKIP_SET_EVENT_ON_HANDLE, - ), + handle, CompletionModes.FILE_SKIP_SET_EVENT_ON_HANDLE + ) ) ################################################################ @@ -668,9 +647,8 @@ def _refresh_afd(self, base_handle: Handle) -> None: try: _check( kernel32.CancelIoEx( - afd_group.handle, - waiters.current_op.lpOverlapped, - ), + afd_group.handle, waiters.current_op.lpOverlapped + ) ) except OSError as exc: if exc.winerror != ErrorCodes.ERROR_NOT_FOUND: @@ -719,7 +697,7 @@ def _refresh_afd(self, base_handle: Handle) -> None: ffi.sizeof("AFD_POLL_INFO"), ffi.NULL, lpOverlapped, - ), + ) ) except OSError as exc: if exc.winerror != ErrorCodes.ERROR_IO_PENDING: @@ -845,9 +823,7 @@ def register_with_iocp(self, handle: int | CData) -> None: @_public async def wait_overlapped( - self, - handle_: int | CData, - lpOverlapped: CData | int, + self, handle_: int | CData, lpOverlapped: CData | int ) -> object: """TODO: these are implemented, but are currently more of a sketch than anything real. See `#26 @@ -859,7 +835,7 @@ async def wait_overlapped( lpOverlapped = ffi.cast("LPOVERLAPPED", lpOverlapped) if lpOverlapped in self._overlapped_waiters: raise _core.BusyResourceError( - "another task is already waiting on that lpOverlapped", + "another task is already waiting on that lpOverlapped" ) task = _core.current_task() self._overlapped_waiters[lpOverlapped] = task @@ -886,11 +862,8 @@ def abort(raise_cancel_: RaiseCancelT) -> Abort: # does, we'll assume the handle wasn't registered. _check( kernel32.PostQueuedCompletionStatus( - self._iocp, - 0, - CKeys.LATE_CANCEL, - lpOverlapped, - ), + self._iocp, 0, CKeys.LATE_CANCEL, lpOverlapped + ) ) # Keep the lpOverlapped referenced so its address # doesn't get reused until our posted completion @@ -900,7 +873,7 @@ def abort(raise_cancel_: RaiseCancelT) -> Abort: self._posted_too_late_to_cancel.add(lpOverlapped) else: # pragma: no cover raise _core.TrioInternalError( - "CancelIoEx failed with unexpected error", + "CancelIoEx failed with unexpected error" ) from exc return _core.Abort.FAILED @@ -925,9 +898,7 @@ def abort(raise_cancel_: RaiseCancelT) -> Abort: return info async def _perform_overlapped( - self, - handle: int | CData, - submit_fn: Callable[[_Overlapped], None], + self, handle: int | CData, submit_fn: Callable[[_Overlapped], None] ) -> _Overlapped: # submit_fn(lpOverlapped) submits some I/O # it may raise an OSError with ERROR_IO_PENDING @@ -948,10 +919,7 @@ async def _perform_overlapped( @_public async def write_overlapped( - self, - handle: int | CData, - data: Buffer, - file_offset: int = 0, + self, handle: int | CData, data: Buffer, file_offset: int = 0 ) -> int: """TODO: these are implemented, but are currently more of a sketch than anything real. See `#26 @@ -972,7 +940,7 @@ def submit_write(lpOverlapped: _Overlapped) -> None: len(cbuf), ffi.NULL, lpOverlapped, - ), + ) ) lpOverlapped = await self._perform_overlapped(handle, submit_write) @@ -981,10 +949,7 @@ def submit_write(lpOverlapped: _Overlapped) -> None: @_public async def readinto_overlapped( - self, - handle: int | CData, - buffer: Buffer, - file_offset: int = 0, + self, handle: int | CData, buffer: Buffer, file_offset: int = 0 ) -> int: """TODO: these are implemented, but are currently more of a sketch than anything real. See `#26 @@ -1004,7 +969,7 @@ def submit_read(lpOverlapped: _Overlapped) -> None: len(cbuf), ffi.NULL, lpOverlapped, - ), + ) ) lpOverlapped = await self._perform_overlapped(handle, submit_read) diff --git a/src/trio/_core/_ki.py b/src/trio/_core/_ki.py index 46a7fdf70..a2e913cb1 100644 --- a/src/trio/_core/_ki.py +++ b/src/trio/_core/_ki.py @@ -86,10 +86,7 @@ class _IdRef(weakref.ref[_T]): _hash: int def __new__( - cls, - ob: _T, - callback: Callable[[Self], object] | None = None, - /, + cls, ob: _T, callback: Callable[[Self], object] | None = None, / ) -> Self: self: Self = weakref.ref.__new__(cls, ob, callback) self._hash = object.__hash__(ob) @@ -131,7 +128,7 @@ def remove( selfref: weakref.ref[ WeakKeyIdentityDictionary[_KT, _VT] ] = weakref.ref( # noqa: B008 # function-call-in-default-argument - self, + self ), ) -> None: self = selfref() @@ -150,10 +147,9 @@ def __setitem__(self, k: _KT, v: _VT) -> None: self._data[_IdRef(k, self._remove)] = v -_CODE_KI_PROTECTION_STATUS_WMAP: WeakKeyIdentityDictionary[ - types.CodeType, - bool, -] = WeakKeyIdentityDictionary() +_CODE_KI_PROTECTION_STATUS_WMAP: WeakKeyIdentityDictionary[types.CodeType, bool] = ( + WeakKeyIdentityDictionary() +) # This is to support the async_generator package necessary for aclosing on <3.10 diff --git a/src/trio/_core/_parking_lot.py b/src/trio/_core/_parking_lot.py index af6ff610e..349b9119c 100644 --- a/src/trio/_core/_parking_lot.py +++ b/src/trio/_core/_parking_lot.py @@ -99,7 +99,7 @@ def add_parking_lot_breaker(task: Task, lot: ParkingLot) -> None: """ if inspect.getcoroutinestate(task.coro) == inspect.CORO_CLOSED: raise _core._exceptions.BrokenResourceError( - "Attempted to add already exited task as lot breaker.", + "Attempted to add already exited task as lot breaker." ) if task not in GLOBAL_PARKING_LOT_BREAKER: GLOBAL_PARKING_LOT_BREAKER[task] = [lot] @@ -113,7 +113,7 @@ def remove_parking_lot_breaker(task: Task, lot: ParkingLot) -> None: GLOBAL_PARKING_LOT_BREAKER[task].remove(lot) except (KeyError, ValueError): raise RuntimeError( - "Attempted to remove task as breaker for a lot it is not registered for", + "Attempted to remove task as breaker for a lot it is not registered for" ) from None if not GLOBAL_PARKING_LOT_BREAKER[task]: del GLOBAL_PARKING_LOT_BREAKER[task] @@ -177,7 +177,7 @@ async def park(self) -> None: """ if self.broken_by: raise _core.BrokenResourceError( - f"Attempted to park in parking lot broken by {self.broken_by}", + f"Attempted to park in parking lot broken by {self.broken_by}" ) task = _core.current_task() self._parked[task] = None @@ -224,10 +224,7 @@ def unpark_all(self) -> list[Task]: @_core.enable_ki_protection def repark( - self, - new_lot: ParkingLot, - *, - count: int | float = 1, # noqa: PYI041 + self, new_lot: ParkingLot, *, count: int | float = 1 # noqa: PYI041 ) -> None: """Move parked tasks from one :class:`ParkingLot` object to another. @@ -300,7 +297,7 @@ def break_lot(self, task: Task | None = None) -> None: _core.reschedule( parked_task, outcome.Error( - _core.BrokenResourceError(f"Parking lot broken by {task}"), + _core.BrokenResourceError(f"Parking lot broken by {task}") ), ) self._parked.clear() diff --git a/src/trio/_core/_run.py b/src/trio/_core/_run.py index 3d89ab404..0c11c79e4 100644 --- a/src/trio/_core/_run.py +++ b/src/trio/_core/_run.py @@ -14,15 +14,7 @@ from heapq import heapify, heappop, heappush from math import inf, isnan from time import perf_counter -from typing import ( - TYPE_CHECKING, - Any, - Final, - NoReturn, - Protocol, - cast, - overload, -) +from typing import TYPE_CHECKING, Any, Final, NoReturn, Protocol, cast, overload import attrs from outcome import Error, Outcome, Value, capture @@ -142,7 +134,7 @@ def function_with_unique_name_xyzzy() -> NoReturn: raise else: # pragma: no cover raise TrioInternalError( - "A ZeroDivisionError should have been raised, but it wasn't.", + "A ZeroDivisionError should have been raised, but it wasn't." ) ctx = copy_context() @@ -160,7 +152,7 @@ def function_with_unique_name_xyzzy() -> NoReturn: else: # pragma: no cover raise TrioInternalError( f"The purpose of {function_with_unique_name_xyzzy.__name__} is " - "to raise a ZeroDivisionError, but it didn't.", + "to raise a ZeroDivisionError, but it didn't." ) @@ -219,8 +211,7 @@ def collapse_exception_group( and NONSTRICT_EXCEPTIONGROUP_NOTE in getattr(excgroup, "__notes__", ()) ): exceptions[0].__traceback__ = concat_tb( - excgroup.__traceback__, - exceptions[0].__traceback__, + excgroup.__traceback__, exceptions[0].__traceback__ ) return exceptions[0] elif modified: @@ -555,16 +546,14 @@ def __attrs_post_init__(self) -> None: if self._relative_deadline < 0: raise ValueError("timeout must be non-negative") if self._relative_deadline != inf and self._deadline != inf: - raise ValueError( - "Cannot specify both a deadline and a relative deadline", - ) + raise ValueError("Cannot specify both a deadline and a relative deadline") @enable_ki_protection def __enter__(self) -> Self: task = _core.current_task() if self._has_been_entered: raise RuntimeError( - "Each CancelScope may only be used for a single 'with' block", + "Each CancelScope may only be used for a single 'with' block" ) self._has_been_entered = True @@ -584,7 +573,7 @@ def _close(self, exc: BaseException | None) -> BaseException | None: if self._cancel_status is None: new_exc = RuntimeError( f"Cancel scope stack corrupted: attempted to exit {self!r} " - "which had already been exited", + "which had already been exited" ) new_exc.__context__ = exc return new_exc @@ -606,7 +595,7 @@ def _close(self, exc: BaseException | None) -> BaseException | None: # without changing any state. new_exc = RuntimeError( f"Cancel scope stack corrupted: attempted to exit {self!r} " - f"from unrelated {scope_task!r}\n{MISNESTING_ADVICE}", + f"from unrelated {scope_task!r}\n{MISNESTING_ADVICE}" ) new_exc.__context__ = exc return new_exc @@ -618,7 +607,7 @@ def _close(self, exc: BaseException | None) -> BaseException | None: # pass silently. new_exc = RuntimeError( f"Cancel scope stack corrupted: attempted to exit {self!r} " - f"in {scope_task!r} that's still within its child {scope_task._cancel_status._scope!r}\n{MISNESTING_ADVICE}", + f"in {scope_task!r} that's still within its child {scope_task._cancel_status._scope!r}\n{MISNESTING_ADVICE}" ) new_exc.__context__ = exc exc = new_exc @@ -757,7 +746,7 @@ def deadline(self) -> float: assert self._deadline == inf warnings.warn( DeprecationWarning( - "unentered relative cancel scope does not have an absolute deadline. Use `.relative_deadline`", + "unentered relative cancel scope does not have an absolute deadline. Use `.relative_deadline`" ), stacklevel=2, ) @@ -772,7 +761,7 @@ def deadline(self, new_deadline: float) -> None: assert self._deadline == inf warnings.warn( DeprecationWarning( - "unentered relative cancel scope does not have an absolute deadline. Transforming into an absolute cancel scope. First set `.relative_deadline = math.inf` if you do want an absolute cancel scope.", + "unentered relative cancel scope does not have an absolute deadline. Transforming into an absolute cancel scope. First set `.relative_deadline = math.inf` if you do want an absolute cancel scope." ), stacklevel=2, ) @@ -787,7 +776,7 @@ def relative_deadline(self) -> float: elif self._deadline != inf: assert self._relative_deadline == inf raise RuntimeError( - "unentered non-relative cancel scope does not have a relative deadline", + "unentered non-relative cancel scope does not have a relative deadline" ) return self._relative_deadline @@ -803,7 +792,7 @@ def relative_deadline(self, new_relative_deadline: float) -> None: elif self._deadline != inf: assert self._relative_deadline == inf raise RuntimeError( - "unentered non-relative cancel scope does not have a relative deadline", + "unentered non-relative cancel scope does not have a relative deadline" ) else: self._relative_deadline = new_relative_deadline @@ -1009,9 +998,7 @@ async def __aenter__(self) -> Nursery: self._scope = CancelScope() self._scope.__enter__() self._nursery = Nursery._create( - current_task(), - self._scope, - self.strict_exception_groups, + current_task(), self._scope, self.strict_exception_groups ) return self._nursery @@ -1049,7 +1036,7 @@ async def __aexit__( def __enter__(self) -> NoReturn: raise RuntimeError( - "use 'async with open_nursery(...)', not 'with open_nursery(...)'", + "use 'async with open_nursery(...)', not 'with open_nursery(...)'" ) def __exit__( @@ -1171,19 +1158,14 @@ def _check_nursery_closed(self) -> None: self._parent_waiting_in_aexit = False GLOBAL_RUN_CONTEXT.runner.reschedule(self._parent_task) - def _child_finished( - self, - task: Task, - outcome: Outcome[object], - ) -> None: + def _child_finished(self, task: Task, outcome: Outcome[object]) -> None: self._children.remove(task) if isinstance(outcome, Error): self._add_exc(outcome.error) self._check_nursery_closed() async def _nested_child_finished( - self, - nested_child_exc: BaseException | None, + self, nested_child_exc: BaseException | None ) -> BaseException | None: # Returns ExceptionGroup instance (or any exception if the nursery is in loose mode # and there is just one contained exception) if there are pending exceptions @@ -1222,8 +1204,7 @@ def aborted(raise_cancel: _core.RaiseCancelT) -> Abort: if not self._strict_exception_groups and len(self._pending_excs) == 1: return self._pending_excs[0] exception = BaseExceptionGroup( - "Exceptions from Trio nursery", - self._pending_excs, + "Exceptions from Trio nursery", self._pending_excs ) if not self._strict_exception_groups: exception.add_note(NONSTRICT_EXCEPTIONGROUP_NOTE) @@ -1340,15 +1321,11 @@ async def async_fn(arg1, arg2, *, task_status=trio.TASK_STATUS_IGNORED): # *this* nursery's exceptiongroup async with open_nursery(strict_exception_groups=True) as old_nursery: task_status: _TaskStatus[object | None] = _TaskStatus( - old_nursery, - self, + old_nursery, self ) thunk = functools.partial(async_fn, task_status=task_status) task = GLOBAL_RUN_CONTEXT.runner.spawn_impl( - thunk, - args, - old_nursery, - name, + thunk, args, old_nursery, name ) task._eventual_parent_nursery = self # Wait for either TaskStatus.started or an exception to @@ -1359,7 +1336,7 @@ async def async_fn(arg1, arg2, *, task_status=trio.TASK_STATUS_IGNORED): raise TrioInternalError( "Internal nursery should not have multiple tasks. This can be " 'caused by the user managing to access the "old" nursery in ' - "`task_status` and spawning tasks in it.", + "`task_status` and spawning tasks in it." ) from exc # If we get here, then the child either got reparented or exited @@ -1648,8 +1625,7 @@ def guest_tick(self) -> None: # Optimization: try to skip going into the thread if we can avoid it events_outcome: Value[EventResult] | Error = capture( - self.runner.io_manager.get_events, - 0, + self.runner.io_manager.get_events, 0 ) if timeout <= 0 or isinstance(events_outcome, Error) or events_outcome.value: # No need to go into the thread @@ -1921,7 +1897,7 @@ def task_exited(self, task: Task, outcome: Outcome[object]) -> None: # traceback frame included raise RuntimeError( "Cancel scope stack corrupted: cancel scope surrounding " - f"{task!r} was closed before the task exited\n{MISNESTING_ADVICE}", + f"{task!r} was closed before the task exited\n{MISNESTING_ADVICE}" ) except RuntimeError as new_exc: if isinstance(outcome, Error): @@ -2013,12 +1989,7 @@ def spawn_system_task( """ return self.spawn_impl( - async_fn, - args, - self.system_nursery, - name, - system_task=True, - context=context, + async_fn, args, self.system_nursery, name, system_task=True, context=context ) async def init( @@ -2034,10 +2005,7 @@ async def init( async with open_nursery() as main_task_nursery: try: self.main_task = self.spawn_impl( - async_fn, - args, - main_task_nursery, - None, + async_fn, args, main_task_nursery, None ) except BaseException as exc: self.main_task_outcome = Error(exc) @@ -2531,8 +2499,7 @@ def my_done_callback(run_outcome): # this time, so it shouldn't be possible to get an exception here, # except for a TrioInternalError. next_send = cast( - EventResult, - None, + EventResult, None ) # First iteration must be `None`, every iteration after that is EventResult for _tick in range(5): # expected need is 2 iterations + leave some wiggle room if runner.system_nursery is not None: @@ -2542,13 +2509,13 @@ def my_done_callback(run_outcome): timeout = guest_state.unrolled_run_gen.send(next_send) except StopIteration: # pragma: no cover raise TrioInternalError( - "Guest runner exited before system nursery was initialized", + "Guest runner exited before system nursery was initialized" ) from None if timeout != 0: # pragma: no cover guest_state.unrolled_run_gen.throw( TrioInternalError( - "Guest runner blocked before system nursery was initialized", - ), + "Guest runner blocked before system nursery was initialized" + ) ) # next_send should be the return value of # IOManager.get_events() if no I/O was waiting, which is @@ -2562,8 +2529,8 @@ def my_done_callback(run_outcome): guest_state.unrolled_run_gen.throw( TrioInternalError( "Guest runner yielded too many times before " - "system nursery was initialized", - ), + "system nursery was initialized" + ) ) guest_state.unrolled_run_next_send = Value(next_send) @@ -2596,11 +2563,7 @@ def unrolled_run( runner.instruments.call("before_run") runner.clock.start_clock() runner.init_task = runner.spawn_impl( - runner.init, - (async_fn, args), - None, - "", - system_task=True, + runner.init, (async_fn, args), None, "", system_task=True ) # You know how people talk about "event loops"? This 'while' loop right @@ -2778,7 +2741,7 @@ def unrolled_run( f"trio.run received unrecognized yield message {msg!r}. " "Are you trying to use a library written for some " "other framework like asyncio? That won't work " - "without some kind of compatibility shim.", + "without some kind of compatibility shim." ) # The foreign library probably doesn't adhere to our # protocol of unwrapping whatever outcome gets sent in. @@ -2802,7 +2765,7 @@ def unrolled_run( warnings.warn( RuntimeWarning( "Trio guest run got abandoned without properly finishing... " - "weird stuff might happen", + "weird stuff might happen" ), stacklevel=1, ) diff --git a/src/trio/_core/_tests/test_asyncgen.py b/src/trio/_core/_tests/test_asyncgen.py index 5db88d792..af13391b8 100644 --- a/src/trio/_core/_tests/test_asyncgen.py +++ b/src/trio/_core/_tests/test_asyncgen.py @@ -43,8 +43,7 @@ async def example(cause: str) -> AsyncGenerator[int, None]: async def async_main() -> None: # GC'ed before exhausted with pytest.warns( - ResourceWarning, - match="Async generator.*collected before.*exhausted", + ResourceWarning, match="Async generator.*collected before.*exhausted" ): assert await example("abandoned").asend(None) == 42 gc_collect_harder() @@ -154,8 +153,7 @@ async def innermost() -> AsyncGenerator[int, None]: record.append("innermost") async def agen( - label: int, - inner: AsyncGenerator[int, None], + label: int, inner: AsyncGenerator[int, None] ) -> AsyncGenerator[int, None]: try: yield await inner.asend(None) @@ -199,8 +197,7 @@ def collect_at_opportune_moment(token: _core._entry_queue.TrioToken) -> None: runner = _core._run.GLOBAL_RUN_CONTEXT.runner assert runner.system_nursery is not None if runner.system_nursery._closed and isinstance( - runner.asyncgens.alive, - weakref.WeakSet, + runner.asyncgens.alive, weakref.WeakSet ): saved.clear() record.append("final collection") @@ -238,7 +235,7 @@ async def async_main() -> None: else: # pragma: no cover pytest.fail( "Didn't manage to hit the trailing_finalizer_asyncgens case " - f"despite trying {_attempt} times", + f"despite trying {_attempt} times" ) diff --git a/src/trio/_core/_tests/test_exceptiongroup_gc.py b/src/trio/_core/_tests/test_exceptiongroup_gc.py index 885ef6862..8957a581a 100644 --- a/src/trio/_core/_tests/test_exceptiongroup_gc.py +++ b/src/trio/_core/_tests/test_exceptiongroup_gc.py @@ -76,8 +76,7 @@ def test_concat_tb() -> None: # Unclear if this can still fail, removing the `del` from _concat_tb.copy_tb does not seem # to trigger it (on a platform where the `del` is executed) @pytest.mark.skipif( - sys.implementation.name != "cpython", - reason="Only makes sense with refcounting GC", + sys.implementation.name != "cpython", reason="Only makes sense with refcounting GC" ) def test_ExceptionGroup_catch_doesnt_create_cyclic_garbage() -> None: # https://github.com/python-trio/trio/pull/2063 diff --git a/src/trio/_core/_tests/test_guest_mode.py b/src/trio/_core/_tests/test_guest_mode.py index 1a4f87464..2fb0fbdcd 100644 --- a/src/trio/_core/_tests/test_guest_mode.py +++ b/src/trio/_core/_tests/test_guest_mode.py @@ -14,12 +14,7 @@ from collections.abc import AsyncGenerator, Awaitable, Callable, Sequence from functools import partial from math import inf -from typing import ( - TYPE_CHECKING, - NoReturn, - TypeVar, - cast, -) +from typing import TYPE_CHECKING, NoReturn, TypeVar, cast import pytest import sniffio @@ -64,8 +59,7 @@ def run_sync_soon_threadsafe(fn: Callable[[], object]) -> None: nonlocal todo if host_thread is threading.current_thread(): # pragma: no cover crash = partial( - pytest.fail, - "run_sync_soon_threadsafe called from host thread", + pytest.fail, "run_sync_soon_threadsafe called from host thread" ) todo.put(("run", crash)) todo.put(("run", fn)) @@ -74,8 +68,7 @@ def run_sync_soon_not_threadsafe(fn: Callable[[], object]) -> None: nonlocal todo if host_thread is not threading.current_thread(): # pragma: no cover crash = partial( - pytest.fail, - "run_sync_soon_not_threadsafe called from worker thread", + pytest.fail, "run_sync_soon_not_threadsafe called from worker thread" ) todo.put(("run", crash)) todo.put(("run", fn)) @@ -195,9 +188,7 @@ def after_start_never_runs() -> None: # pragma: no cover # are raised out of start_guest_run, not out of the done_callback with pytest.raises(trio.TrioInternalError): trivial_guest_run( - trio_main, - clock=BadClock(), - in_host_after_start=after_start_never_runs, + trio_main, clock=BadClock(), in_host_after_start=after_start_never_runs ) @@ -348,7 +339,7 @@ async def sit_in_wait_all_tasks_blocked(watb_cscope: trio.CancelScope) -> None: await trio.testing.wait_all_tasks_blocked(cushion=9999) raise AssertionError( # pragma: no cover "wait_all_tasks_blocked should *not* return normally, " - "only by cancellation.", + "only by cancellation." ) assert watb_cscope.cancelled_caught @@ -516,8 +507,7 @@ async def trio_main() -> str: raise AssertionError("should never be reached") # pragma: no cover async def aio_pingpong( - from_trio: asyncio.Queue[int], - to_trio: MemorySendChannel[int], + from_trio: asyncio.Queue[int], to_trio: MemorySendChannel[int] ) -> None: print("aio_pingpong!") @@ -556,8 +546,7 @@ async def aio_pingpong( def test_guest_mode_internal_errors( - monkeypatch: pytest.MonkeyPatch, - recwarn: pytest.WarningsRecorder, + monkeypatch: pytest.MonkeyPatch, recwarn: pytest.WarningsRecorder ) -> None: with monkeypatch.context() as m: @@ -584,8 +573,7 @@ async def crash_in_worker_thread_io(in_host: InHost) -> None: old_get_events = trio._core._run.TheIOManager.get_events def bad_get_events( - self: trio._core._run.TheIOManager, - timeout: float, + self: trio._core._run.TheIOManager, timeout: float ) -> trio._core._run.EventResult: if threading.current_thread() is not t: raise ValueError("oh no!") diff --git a/src/trio/_core/_tests/test_io.py b/src/trio/_core/_tests/test_io.py index 48b99d387..b8419fc9f 100644 --- a/src/trio/_core/_tests/test_io.py +++ b/src/trio/_core/_tests/test_io.py @@ -55,7 +55,7 @@ def socketpair() -> Generator[SocketPair, None, None]: def also_using_fileno( - fn: Callable[[stdlib_socket.socket | int], RetT], + fn: Callable[[stdlib_socket.socket | int], RetT] ) -> list[Callable[[stdlib_socket.socket], RetT]]: def fileno_wrapper(fileobj: stdlib_socket.socket) -> RetT: return fn(fileobj.fileno()) @@ -92,9 +92,7 @@ def fileno_wrapper(fileobj: stdlib_socket.socket) -> RetT: @read_socket_test @write_socket_test async def test_wait_basic( - socketpair: SocketPair, - wait_readable: WaitSocket, - wait_writable: WaitSocket, + socketpair: SocketPair, wait_readable: WaitSocket, wait_writable: WaitSocket ) -> None: a, b = socketpair @@ -218,9 +216,7 @@ async def writer() -> None: @read_socket_test @write_socket_test async def test_socket_simultaneous_read_write( - socketpair: SocketPair, - wait_readable: WaitSocket, - wait_writable: WaitSocket, + socketpair: SocketPair, wait_readable: WaitSocket, wait_writable: WaitSocket ) -> None: record: list[str] = [] @@ -250,9 +246,7 @@ async def w_task(sock: stdlib_socket.socket) -> None: @read_socket_test @write_socket_test async def test_socket_actual_streaming( - socketpair: SocketPair, - wait_readable: WaitSocket, - wait_writable: WaitSocket, + socketpair: SocketPair, wait_readable: WaitSocket, wait_writable: WaitSocket ) -> None: a, b = socketpair diff --git a/src/trio/_core/_tests/test_ki.py b/src/trio/_core/_tests/test_ki.py index 67c83e835..4a12f9491 100644 --- a/src/trio/_core/_tests/test_ki.py +++ b/src/trio/_core/_tests/test_ki.py @@ -679,7 +679,7 @@ async def _consume_async_generator(agen: AsyncGenerator[None, None]) -> None: # Explicit .../"Any" is not allowed def _consume_function_for_coverage( # type: ignore[misc] - fn: Callable[..., object], + fn: Callable[..., object] ) -> None: result = fn() if inspect.isasyncgen(result): diff --git a/src/trio/_core/_tests/test_parking_lot.py b/src/trio/_core/_tests/test_parking_lot.py index 809fb2824..073f6e0cd 100644 --- a/src/trio/_core/_tests/test_parking_lot.py +++ b/src/trio/_core/_tests/test_parking_lot.py @@ -47,8 +47,7 @@ async def waiter(i: int, lot: ParkingLot) -> None: assert len(record) == 6 check_sequence_matches( - record, - [{"sleep 0", "sleep 1", "sleep 2"}, {"wake 0", "wake 1", "wake 2"}], + record, [{"sleep 0", "sleep 1", "sleep 2"}, {"wake 0", "wake 1", "wake 2"}] ) async with _core.open_nursery() as nursery: @@ -61,14 +60,7 @@ async def waiter(i: int, lot: ParkingLot) -> None: lot.unpark() await wait_all_tasks_blocked() # 1-by-1 wakeups are strict FIFO - assert record == [ - "sleep 0", - "sleep 1", - "sleep 2", - "wake 0", - "wake 1", - "wake 2", - ] + assert record == ["sleep 0", "sleep 1", "sleep 2", "wake 0", "wake 1", "wake 2"] # It's legal (but a no-op) to try and unpark while there's nothing parked lot.unpark() @@ -84,23 +76,18 @@ async def waiter(i: int, lot: ParkingLot) -> None: lot.unpark(count=2) await wait_all_tasks_blocked() check_sequence_matches( - record, - ["sleep 0", "sleep 1", "sleep 2", {"wake 0", "wake 1"}], + record, ["sleep 0", "sleep 1", "sleep 2", {"wake 0", "wake 1"}] ) lot.unpark_all() with pytest.raises( - ValueError, - match=r"^Cannot pop a non-integer number of tasks\.$", + ValueError, match=r"^Cannot pop a non-integer number of tasks\.$" ): lot.unpark(count=1.5) async def cancellable_waiter( - name: T, - lot: ParkingLot, - scopes: dict[T, _core.CancelScope], - record: list[str], + name: T, lot: ParkingLot, scopes: dict[T, _core.CancelScope], record: list[str] ) -> None: with _core.CancelScope() as scope: scopes[name] = scope @@ -135,8 +122,7 @@ async def test_parking_lot_cancel() -> None: assert len(record) == 6 check_sequence_matches( - record, - ["sleep 1", "sleep 2", "sleep 3", "cancelled 2", {"wake 1", "wake 3"}], + record, ["sleep 1", "sleep 2", "sleep 3", "cancelled 2", {"wake 1", "wake 3"}] ) @@ -174,13 +160,7 @@ async def test_parking_lot_repark() -> None: scopes[2].cancel() await wait_all_tasks_blocked() assert len(lot2) == 1 - assert record == [ - "sleep 1", - "sleep 2", - "sleep 3", - "wake 1", - "cancelled 2", - ] + assert record == ["sleep 1", "sleep 2", "sleep 3", "wake 1", "cancelled 2"] lot2.unpark_all() await wait_all_tasks_blocked() @@ -216,13 +196,7 @@ async def test_parking_lot_repark_with_count() -> None: while lot2: lot2.unpark() await wait_all_tasks_blocked() - assert record == [ - "sleep 1", - "sleep 2", - "sleep 3", - "wake 1", - "wake 2", - ] + assert record == ["sleep 1", "sleep 2", "sleep 3", "wake 1", "wake 2"] lot1.unpark_all() @@ -268,7 +242,7 @@ async def bad_parker(lot: ParkingLot, scope: _core.CancelScope) -> None: # check that parked task errors with RaisesGroup( - Matcher(_core.BrokenResourceError, match="^Parking lot broken by"), + Matcher(_core.BrokenResourceError, match="^Parking lot broken by") ): async with _core.open_nursery() as nursery: nursery.start_soon(bad_parker, lot, cs) @@ -383,7 +357,7 @@ async def return_me_and_park( lot = ParkingLot() with RaisesGroup( - Matcher(_core.BrokenResourceError, match="^Parking lot broken by"), + Matcher(_core.BrokenResourceError, match="^Parking lot broken by") ): async with _core.open_nursery() as nursery: child_task = await nursery.start(return_me_and_park, lot) diff --git a/src/trio/_core/_tests/test_run.py b/src/trio/_core/_tests/test_run.py index f7ac155ba..de19b616b 100644 --- a/src/trio/_core/_tests/test_run.py +++ b/src/trio/_core/_tests/test_run.py @@ -116,7 +116,7 @@ async def test_nursery_warn_use_async_with() -> None: with on: # type: ignore pass # pragma: no cover excinfo.match( - r"use 'async with open_nursery\(...\)', not 'with open_nursery\(...\)'", + r"use 'async with open_nursery\(...\)', not 'with open_nursery\(...\)'" ) # avoid unawaited coro. @@ -156,8 +156,7 @@ async def looper(whoami: str, record: list[tuple[str, int]]) -> None: nursery.start_soon(looper, "b", record) check_sequence_matches( - record, - [{("a", 0), ("b", 0)}, {("a", 1), ("b", 1)}, {("a", 2), ("b", 2)}], + record, [{("a", 0), ("b", 0)}, {("a", 1), ("b", 1)}, {("a", 2), ("b", 2)}] ) @@ -367,8 +366,7 @@ async def test_cancel_scope_repr(mock_clock: _core.MockClock) -> None: async def test_cancel_scope_validation() -> None: with pytest.raises( - ValueError, - match="^Cannot specify both a deadline and a relative deadline$", + ValueError, match="^Cannot specify both a deadline and a relative deadline$" ): _core.CancelScope(deadline=7, relative_deadline=3) scope = _core.CancelScope() @@ -456,10 +454,7 @@ async def crasher() -> NoReturn: # nursery block continue propagating to reach the # outer scope. with RaisesGroup( - _core.Cancelled, - _core.Cancelled, - _core.Cancelled, - KeyError, + _core.Cancelled, _core.Cancelled, _core.Cancelled, KeyError ) as excinfo: async with _core.open_nursery() as nursery: # Two children that get cancelled by the nursery scope @@ -794,8 +789,7 @@ async def task2() -> None: nursery.cancel_scope.__exit__(None, None, None) finally: with pytest.raises( - RuntimeError, - match="which had already been exited", + RuntimeError, match="which had already been exited" ) as exc_info: await nursery_mgr.__aexit__(*sys.exc_info()) @@ -974,7 +968,7 @@ async def main() -> None: # the second exceptiongroup is from the second nursery opened in Runner.init() # the third exceptongroup is from the nursery defined in `system_task` above assert RaisesGroup(RaisesGroup(RaisesGroup(KeyError, ValueError))).matches( - excinfo.value.__cause__, + excinfo.value.__cause__ ) @@ -1004,7 +998,7 @@ async def main() -> None: # See explanation for triple-wrap in test_system_task_crash_ExceptionGroup assert RaisesGroup(RaisesGroup(RaisesGroup(ValueError))).matches( - excinfo.value.__cause__, + excinfo.value.__cause__ ) @@ -1154,18 +1148,13 @@ async def child() -> None: await sleep_forever() with RaisesGroup( - Matcher( - ValueError, - "error text", - lambda e: isinstance(e.__context__, KeyError), - ), + Matcher(ValueError, "error text", lambda e: isinstance(e.__context__, KeyError)) ): async with _core.open_nursery() as nursery: nursery.start_soon(child) await wait_all_tasks_blocked() _core.reschedule( - not_none(child_task), - outcome.Error(ValueError("error text")), + not_none(child_task), outcome.Error(ValueError("error text")) ) @@ -1228,14 +1217,13 @@ async def inner() -> None: "^Unique Text$", lambda e: isinstance(e.__context__, IndexError) and isinstance(e.__context__.__context__, KeyError), - ), + ) ): async with _core.open_nursery() as nursery: nursery.start_soon(child) await wait_all_tasks_blocked() _core.reschedule( - not_none(child_task), - outcome.Error(ValueError("Unique Text")), + not_none(child_task), outcome.Error(ValueError("Unique Text")) ) @@ -1595,8 +1583,7 @@ async def child2() -> None: assert tasks["child2"].child_nurseries == [] async def child1( - *, - task_status: _core.TaskStatus[None] = _core.TASK_STATUS_IGNORED, + *, task_status: _core.TaskStatus[None] = _core.TASK_STATUS_IGNORED ) -> None: me = tasks["child1"] = _core.current_task() assert not_none(me.parent_nursery).parent_task is tasks["parent"] @@ -1649,9 +1636,7 @@ async def func2() -> None: # pragma: no cover pass # Explicit .../"Any" is not allowed - async def check( # type: ignore[misc] - spawn_fn: Callable[..., object], - ) -> None: + async def check(spawn_fn: Callable[..., object]) -> None: # type: ignore[misc] spawn_fn(func1, "func1") spawn_fn(func1, "func2", name=func2) spawn_fn(func1, "func3", name="func3") @@ -1688,14 +1673,12 @@ async def test_current_effective_deadline(mock_clock: _core.MockClock) -> None: def test_nice_error_on_bad_calls_to_run_or_spawn() -> None: # Explicit .../"Any" is not allowed def bad_call_run( # type: ignore[misc] - func: Callable[..., Awaitable[object]], - *args: tuple[object, ...], + func: Callable[..., Awaitable[object]], *args: tuple[object, ...] ) -> None: _core.run(func, *args) def bad_call_spawn( # type: ignore[misc] - func: Callable[..., Awaitable[object]], - *args: tuple[object, ...], + func: Callable[..., Awaitable[object]], *args: tuple[object, ...] ) -> None: async def main() -> None: async with _core.open_nursery() as nursery: @@ -1718,8 +1701,7 @@ async def async_gen(arg: T) -> AsyncGenerator[T, None]: # pragma: no cover ): bad_call_run(f()) # type: ignore[arg-type] with pytest.raises( - TypeError, - match="expected an async function but got an async generator", + TypeError, match="expected an async function but got an async generator" ): bad_call_run(async_gen, 0) # type: ignore @@ -1729,7 +1711,7 @@ async def async_gen(arg: T) -> AsyncGenerator[T, None]: # pragma: no cover bad_call_spawn(f()) # type: ignore[arg-type] with RaisesGroup( - Matcher(TypeError, "expected an async function but got an async generator"), + Matcher(TypeError, "expected an async function but got an async generator") ): bad_call_spawn(async_gen, 0) # type: ignore @@ -1807,9 +1789,7 @@ async def no_args() -> None: # pragma: no cover await nursery.start(no_args) async def sleep_then_start( - seconds: int, - *, - task_status: _core.TaskStatus[int] = _core.TASK_STATUS_IGNORED, + seconds: int, *, task_status: _core.TaskStatus[int] = _core.TASK_STATUS_IGNORED ) -> None: repr(task_status) # smoke test await sleep(seconds) @@ -1836,8 +1816,7 @@ async def sleep_then_start( # calling started twice async def double_started( - *, - task_status: _core.TaskStatus[None] = _core.TASK_STATUS_IGNORED, + *, task_status: _core.TaskStatus[None] = _core.TASK_STATUS_IGNORED ) -> None: task_status.started() with pytest.raises(RuntimeError): @@ -1848,8 +1827,7 @@ async def double_started( # child crashes before calling started -> error comes out of .start() async def raise_keyerror( - *, - task_status: _core.TaskStatus[None] = _core.TASK_STATUS_IGNORED, + *, task_status: _core.TaskStatus[None] = _core.TASK_STATUS_IGNORED ) -> None: raise KeyError("oops") @@ -1859,8 +1837,7 @@ async def raise_keyerror( # child exiting cleanly before calling started -> triggers a RuntimeError async def nothing( - *, - task_status: _core.TaskStatus[None] = _core.TASK_STATUS_IGNORED, + *, task_status: _core.TaskStatus[None] = _core.TASK_STATUS_IGNORED ) -> None: return @@ -1873,8 +1850,7 @@ async def nothing( # nothing -- the child keeps executing under start(). The value it passed # is ignored; start() raises Cancelled. async def just_started( - *, - task_status: _core.TaskStatus[str] = _core.TASK_STATUS_IGNORED, + *, task_status: _core.TaskStatus[str] = _core.TASK_STATUS_IGNORED ) -> None: task_status.started("hi") await _core.checkpoint() @@ -1888,8 +1864,7 @@ async def just_started( # but if the task does not execute any checkpoints, and exits, then start() # doesn't raise Cancelled, since the task completed successfully. async def started_with_no_checkpoint( - *, - task_status: _core.TaskStatus[None] = _core.TASK_STATUS_IGNORED, + *, task_status: _core.TaskStatus[None] = _core.TASK_STATUS_IGNORED ) -> None: task_status.started(None) @@ -1903,8 +1878,7 @@ async def started_with_no_checkpoint( # the child crashes after calling started(), the error can *still* come # out of start() async def raise_keyerror_after_started( - *, - task_status: _core.TaskStatus[None] = _core.TASK_STATUS_IGNORED, + *, task_status: _core.TaskStatus[None] = _core.TASK_STATUS_IGNORED ) -> None: task_status.started() raise KeyError("whoopsiedaisy") @@ -1969,8 +1943,7 @@ async def sleeping_children( assert isinstance(value, _core.Nursery) target_nursery: _core.Nursery = value await target_nursery.start( - sleeping_children, - target_nursery.cancel_scope.cancel, + sleeping_children, target_nursery.cancel_scope.cancel ) # Cancelling the setup_nursery just *after* calling started() @@ -2062,10 +2035,7 @@ def __init__(self, *largs: it) -> None: self.nexts = [obj.__anext__ for obj in largs] async def _accumulate( - self, - f: Callable[[], Awaitable[int]], - items: list[int], - i: int, + self, f: Callable[[], Awaitable[int]], items: list[int], i: int ) -> None: items[i] = await f() @@ -2087,8 +2057,7 @@ async def __anext__(self) -> list[int]: # We could also use RaisesGroup, but that's primarily meant as # test infra, not as a runtime tool. if len(e.exceptions) == 1 and isinstance( - e.exceptions[0], - StopAsyncIteration, + e.exceptions[0], StopAsyncIteration ): raise e.exceptions[0] from None else: # pragma: no cover @@ -2289,16 +2258,14 @@ async def test_permanently_detach_coroutine_object() -> None: pdco_outcome: outcome.Outcome[str] | None = None async def detachable_coroutine( - task_outcome: outcome.Outcome[None], - yield_value: object, + task_outcome: outcome.Outcome[None], yield_value: object ) -> None: await sleep(0) nonlocal task, pdco_outcome task = _core.current_task() # `No overload variant of "acapture" matches argument types "Callable[[Outcome[object]], Coroutine[Any, Any, object]]", "Outcome[None]"` pdco_outcome = await outcome.acapture( # type: ignore[call-overload] - _core.permanently_detach_coroutine_object, - task_outcome, + _core.permanently_detach_coroutine_object, task_outcome ) await async_yield(yield_value) @@ -2363,8 +2330,7 @@ def abort_fn(_: _core.RaiseCancelT) -> _core.Abort: # pragma: no cover with pytest.raises(RuntimeError) as excinfo: await _core.reattach_detached_coroutine_object( - not_none(unrelated_task), - None, + not_none(unrelated_task), None ) assert "does not match" in str(excinfo.value) @@ -2467,8 +2433,7 @@ async def test_cancel_scope_deadline_duplicates() -> None: # refer to this only seems to break test_cancel_scope_exit_doesnt_create_cyclic_garbage # We're keeping it for now to cover Outcome and potential future refactoring @pytest.mark.skipif( - sys.implementation.name != "cpython", - reason="Only makes sense with refcounting GC", + sys.implementation.name != "cpython", reason="Only makes sense with refcounting GC" ) async def test_simple_cancel_scope_usage_doesnt_create_cyclic_garbage() -> None: # https://github.com/python-trio/trio/issues/1770 @@ -2507,8 +2472,7 @@ async def crasher() -> NoReturn: @pytest.mark.skipif( - sys.implementation.name != "cpython", - reason="Only makes sense with refcounting GC", + sys.implementation.name != "cpython", reason="Only makes sense with refcounting GC" ) async def test_cancel_scope_exit_doesnt_create_cyclic_garbage() -> None: # https://github.com/python-trio/trio/pull/2063 @@ -2546,8 +2510,7 @@ async def crasher() -> NoReturn: @pytest.mark.skipif( - sys.implementation.name != "cpython", - reason="Only makes sense with refcounting GC", + sys.implementation.name != "cpython", reason="Only makes sense with refcounting GC" ) async def test_nursery_cancel_doesnt_create_cyclic_garbage() -> None: collected = False @@ -2583,8 +2546,7 @@ def toggle_collected() -> None: @pytest.mark.skipif( - sys.implementation.name != "cpython", - reason="Only makes sense with refcounting GC", + sys.implementation.name != "cpython", reason="Only makes sense with refcounting GC" ) async def test_locals_destroyed_promptly_on_cancel() -> None: destroyed = False @@ -2616,15 +2578,13 @@ def _create_kwargs(strictness: bool | None) -> dict[str, bool]: @pytest.mark.filterwarnings( - "ignore:.*strict_exception_groups=False:trio.TrioDeprecationWarning", + "ignore:.*strict_exception_groups=False:trio.TrioDeprecationWarning" ) @pytest.mark.parametrize("run_strict", [True, False, None]) @pytest.mark.parametrize("open_nursery_strict", [True, False, None]) @pytest.mark.parametrize("multiple_exceptions", [True, False]) def test_setting_strict_exception_groups( - run_strict: bool | None, - open_nursery_strict: bool | None, - multiple_exceptions: bool, + run_strict: bool | None, open_nursery_strict: bool | None, multiple_exceptions: bool ) -> None: """ Test default values and that nurseries can both inherit and override the global context @@ -2661,7 +2621,7 @@ def run_main() -> None: @pytest.mark.filterwarnings( - "ignore:.*strict_exception_groups=False:trio.TrioDeprecationWarning", + "ignore:.*strict_exception_groups=False:trio.TrioDeprecationWarning" ) @pytest.mark.parametrize("strict", [True, False, None]) async def test_nursery_collapse(strict: bool | None) -> None: @@ -2703,7 +2663,7 @@ async def test_cancel_scope_no_cancellederror() -> None: @pytest.mark.filterwarnings( - "ignore:.*strict_exception_groups=False:trio.TrioDeprecationWarning", + "ignore:.*strict_exception_groups=False:trio.TrioDeprecationWarning" ) @pytest.mark.parametrize("run_strict", [False, True]) @pytest.mark.parametrize("start_raiser_strict", [False, True, None]) @@ -2738,7 +2698,7 @@ async def raiser(*, task_status: _core.TaskStatus[None]) -> None: async def start_raiser() -> None: try: async with _core.open_nursery( - strict_exception_groups=start_raiser_strict, + strict_exception_groups=start_raiser_strict ) as nursery: await nursery.start(raiser) except BaseExceptionGroup as exc_group: @@ -2748,8 +2708,7 @@ async def start_raiser() -> None: # exception group raised by trio with a more specific one (subtype, # different message, etc.). raise BaseExceptionGroup( - "start_raiser nursery custom message", - exc_group.exceptions, + "start_raiser nursery custom message", exc_group.exceptions ) from None raise @@ -2806,8 +2765,7 @@ def no_other_refs() -> list[object]: @pytest.mark.skipif( - sys.implementation.name != "cpython", - reason="Only makes sense with refcounting GC", + sys.implementation.name != "cpython", reason="Only makes sense with refcounting GC" ) async def test_ki_protection_doesnt_leave_cyclic_garbage() -> None: class MyException(Exception): diff --git a/src/trio/_core/_tests/test_unbounded_queue.py b/src/trio/_core/_tests/test_unbounded_queue.py index e483ecd30..33eb41a5b 100644 --- a/src/trio/_core/_tests/test_unbounded_queue.py +++ b/src/trio/_core/_tests/test_unbounded_queue.py @@ -8,7 +8,7 @@ from ...testing import assert_checkpoints, wait_all_tasks_blocked pytestmark = pytest.mark.filterwarnings( - "ignore:.*UnboundedQueue:trio.TrioDeprecationWarning", + "ignore:.*UnboundedQueue:trio.TrioDeprecationWarning" ) diff --git a/src/trio/_core/_tests/test_windows.py b/src/trio/_core/_tests/test_windows.py index e4a1bab61..486a40559 100644 --- a/src/trio/_core/_tests/test_windows.py +++ b/src/trio/_core/_tests/test_windows.py @@ -54,8 +54,7 @@ def test_winerror(monkeypatch: pytest.MonkeyPatch) -> None: mock.return_value = (12, "test error") with pytest.raises( - OSError, - match=r"^\[WinError 12\] test error: 'file_1' -> 'file_2'$", + OSError, match=r"^\[WinError 12\] test error: 'file_1' -> 'file_2'$" ) as exc: raise_winerror(filename="file_1", filename2="file_2") mock.assert_called_once_with() @@ -67,8 +66,7 @@ def test_winerror(monkeypatch: pytest.MonkeyPatch) -> None: # With an explicit number passed in, it overrides what getwinerror() returns. with pytest.raises( - OSError, - match=r"^\[WinError 18\] test error: 'a/file' -> 'b/file'$", + OSError, match=r"^\[WinError 18\] test error: 'a/file' -> 'b/file'$" ) as exc: raise_winerror(18, filename="a/file", filename2="b/file") mock.assert_called_once_with(18) @@ -119,8 +117,7 @@ async def test_readinto_overlapped() -> None: with tempfile.TemporaryDirectory() as tdir: tfile = os.path.join(tdir, "numbers.txt") with open( # noqa: ASYNC230 # This is a test, synchronous is ok - tfile, - "wb", + tfile, "wb" ) as fp: fp.write(data) fp.flush() @@ -144,9 +141,7 @@ async def test_readinto_overlapped() -> None: async def read_region(start: int, end: int) -> None: await _core.readinto_overlapped( - handle, - buffer_view[start:end], - start, + handle, buffer_view[start:end], start ) _core.register_with_iocp(handle) @@ -189,10 +184,7 @@ async def main() -> None: try: async with _core.open_nursery() as nursery: nursery.start_soon( - _core.readinto_overlapped, - read_handle, - target, - name="xyz", + _core.readinto_overlapped, read_handle, target, name="xyz" ) await wait_all_tasks_blocked() nursery.cancel_scope.cancel() @@ -249,9 +241,7 @@ def test_lsp_that_hooks_select_gives_good_error( from .._windows_cffi import CData, WSAIoctls, _handle def patched_get_underlying( - sock: int | CData, - *, - which: int = WSAIoctls.SIO_BASE_HANDLE, + sock: int | CData, *, which: int = WSAIoctls.SIO_BASE_HANDLE ) -> CData: if hasattr(sock, "fileno"): # pragma: no branch sock = sock.fileno() @@ -262,8 +252,7 @@ def patched_get_underlying( monkeypatch.setattr(_io_windows, "_get_underlying_socket", patched_get_underlying) with pytest.raises( - RuntimeError, - match="SIO_BASE_HANDLE and SIO_BSP_HANDLE_SELECT differ", + RuntimeError, match="SIO_BASE_HANDLE and SIO_BSP_HANDLE_SELECT differ" ): _core.run(sleep, 0) @@ -280,9 +269,7 @@ def test_lsp_that_completely_hides_base_socket_gives_good_error( from .._windows_cffi import CData, WSAIoctls, _handle def patched_get_underlying( - sock: int | CData, - *, - which: int = WSAIoctls.SIO_BASE_HANDLE, + sock: int | CData, *, which: int = WSAIoctls.SIO_BASE_HANDLE ) -> CData: if hasattr(sock, "fileno"): # pragma: no branch sock = sock.fileno() diff --git a/src/trio/_core/_tests/type_tests/nursery_start.py b/src/trio/_core/_tests/type_tests/nursery_start.py index 4ce03b272..6f1b6b18f 100644 --- a/src/trio/_core/_tests/type_tests/nursery_start.py +++ b/src/trio/_core/_tests/type_tests/nursery_start.py @@ -30,17 +30,12 @@ async def task_requires_kw(a: int, *, b: bool) -> None: ... async def task_startable_1( - a: str, - *, - task_status: TaskStatus[bool] = TASK_STATUS_IGNORED, + a: str, *, task_status: TaskStatus[bool] = TASK_STATUS_IGNORED ) -> None: ... async def task_startable_2( - a: str, - b: float, - *, - task_status: TaskStatus[bool] = TASK_STATUS_IGNORED, + a: str, b: float, *, task_status: TaskStatus[bool] = TASK_STATUS_IGNORED ) -> None: ... diff --git a/src/trio/_core/_tests/type_tests/run.py b/src/trio/_core/_tests/type_tests/run.py index 5c51b9149..66afdbb9d 100644 --- a/src/trio/_core/_tests/type_tests/run.py +++ b/src/trio/_core/_tests/type_tests/run.py @@ -32,9 +32,7 @@ async def foo_overloaded(arg: int | str) -> int | str: v = trio.run( - sleep_sort, - (1, 3, 5, 2, 4), - clock=trio.testing.MockClock(autojump_threshold=0), + sleep_sort, (1, 3, 5, 2, 4), clock=trio.testing.MockClock(autojump_threshold=0) ) assert_type(v, "list[float]") trio.run(sleep_sort, ["hi", "there"]) # type: ignore[arg-type] diff --git a/src/trio/_core/_thread_cache.py b/src/trio/_core/_thread_cache.py index 189d5a583..b262ef30e 100644 --- a/src/trio/_core/_thread_cache.py +++ b/src/trio/_core/_thread_cache.py @@ -26,9 +26,7 @@ def _to_os_thread_name(name: str) -> bytes: # called once on import def get_os_thread_name_func() -> Callable[[int | None, str], None] | None: def namefunc( - setname: Callable[[int, bytes], int], - ident: int | None, - name: str, + setname: Callable[[int, bytes], int], ident: int | None, name: str ) -> None: # Thread.ident is None "if it has not been started". Unclear if that can happen # with current usage. @@ -38,9 +36,7 @@ def namefunc( # namefunc on Mac also takes an ident, even if pthread_setname_np doesn't/can't use it # so the caller don't need to care about platform. def darwin_namefunc( - setname: Callable[[bytes], int], - ident: int | None, - name: str, + setname: Callable[[bytes], int], ident: int | None, name: str ) -> None: # I don't know if Mac can rename threads that hasn't been started, but default # to no to be on the safe side. diff --git a/src/trio/_core/_traps.py b/src/trio/_core/_traps.py index bef77b768..d21d4c612 100644 --- a/src/trio/_core/_traps.py +++ b/src/trio/_core/_traps.py @@ -58,17 +58,14 @@ class PermanentlyDetachCoroutineObject: # tracking machinery. Since our traps are public APIs, we make them real async # functions, and then this helper takes care of the actual yield: @types.coroutine -def _real_async_yield( - obj: MessageType, -) -> Generator[MessageType, None, None]: +def _real_async_yield(obj: MessageType) -> Generator[MessageType, None, None]: return (yield obj) # Real yield value is from trio's main loop, but type checkers can't # understand that, so we cast it to make type checkers understand. _async_yield = cast( - Callable[[MessageType], Awaitable[outcome.Outcome[object]]], - _real_async_yield, + Callable[[MessageType], Awaitable[outcome.Outcome[object]]], _real_async_yield ) @@ -107,7 +104,7 @@ class Abort(enum.Enum): # with a bad value. # Explicit "Any" is not allowed async def wait_task_rescheduled( # type: ignore[misc] - abort_func: Callable[[RaiseCancelT], Abort], + abort_func: Callable[[RaiseCancelT], Abort] ) -> Any: """Put the current task to sleep, with cancellation support. @@ -238,13 +235,13 @@ async def permanently_detach_coroutine_object( """ if _run.current_task().child_nurseries: raise RuntimeError( - "can't permanently detach a coroutine object with open nurseries", + "can't permanently detach a coroutine object with open nurseries" ) return await _async_yield(PermanentlyDetachCoroutineObject(final_outcome)) async def temporarily_detach_coroutine_object( - abort_func: Callable[[RaiseCancelT], Abort], + abort_func: Callable[[RaiseCancelT], Abort] ) -> object: """Temporarily detach the current coroutine object from the Trio scheduler. diff --git a/src/trio/_core/_unbounded_queue.py b/src/trio/_core/_unbounded_queue.py index b9e797484..b9ebe484d 100644 --- a/src/trio/_core/_unbounded_queue.py +++ b/src/trio/_core/_unbounded_queue.py @@ -152,8 +152,7 @@ async def get_batch(self) -> list[T]: def statistics(self) -> UnboundedQueueStatistics: """Return an :class:`UnboundedQueueStatistics` object containing debugging information.""" return UnboundedQueueStatistics( - qsize=len(self._data), - tasks_waiting=self._lot.statistics().tasks_waiting, + qsize=len(self._data), tasks_waiting=self._lot.statistics().tasks_waiting ) def __aiter__(self) -> Self: diff --git a/src/trio/_core/_wakeup_socketpair.py b/src/trio/_core/_wakeup_socketpair.py index ea4567017..fb821a23e 100644 --- a/src/trio/_core/_wakeup_socketpair.py +++ b/src/trio/_core/_wakeup_socketpair.py @@ -63,7 +63,7 @@ def wakeup_on_signals(self) -> None: "running Trio in guest mode, then this might mean you " "should set host_uses_signal_set_wakeup_fd=True. " "Otherwise, file a bug on Trio and we'll help you figure " - "out what's going on.", + "out what's going on." ), stacklevel=1, ) diff --git a/src/trio/_core/_windows_cffi.py b/src/trio/_core/_windows_cffi.py index 453b4beda..9529a69f5 100644 --- a/src/trio/_core/_windows_cffi.py +++ b/src/trio/_core/_windows_cffi.py @@ -210,7 +210,7 @@ # cribbed from pywincffi # programmatically strips out those annotations MSDN likes, like _In_ REGEX_SAL_ANNOTATION = re.compile( - r"\b(_In_|_Inout_|_Out_|_Outptr_|_Reserved_)(opt_)?\b", + r"\b(_In_|_Inout_|_Out_|_Outptr_|_Reserved_)(opt_)?\b" ) LIB = REGEX_SAL_ANNOTATION.sub(" ", LIB) @@ -253,10 +253,7 @@ def CreateEventA( ) -> Handle: ... def SetFileCompletionNotificationModes( - self, - handle: Handle, - flags: CompletionModes, - /, + self, handle: Handle, flags: CompletionModes, / ) -> int: ... def PostQueuedCompletionStatus( @@ -269,10 +266,7 @@ def PostQueuedCompletionStatus( ) -> bool: ... def CancelIoEx( - self, - hFile: Handle, - lpOverlapped: CData | AlwaysNull, - /, + self, hFile: Handle, lpOverlapped: CData | AlwaysNull, / ) -> bool: ... def WriteFile( diff --git a/src/trio/_deprecate.py b/src/trio/_deprecate.py index 51c51f737..f49ae2893 100644 --- a/src/trio/_deprecate.py +++ b/src/trio/_deprecate.py @@ -123,11 +123,7 @@ def wrapper(*args: ArgsT.args, **kwargs: ArgsT.kwargs) -> RetT: def deprecated_alias( - old_qualname: str, - new_fn: Callable[ArgsT, RetT], - version: str, - *, - issue: int | None, + old_qualname: str, new_fn: Callable[ArgsT, RetT], version: str, *, issue: int | None ) -> Callable[ArgsT, RetT]: @deprecated(version, issue=issue, instead=new_fn) @wraps(new_fn, assigned=("__module__", "__annotations__")) diff --git a/src/trio/_dtls.py b/src/trio/_dtls.py index 7f4bccc9e..c5c266ed2 100644 --- a/src/trio/_dtls.py +++ b/src/trio/_dtls.py @@ -17,12 +17,7 @@ import warnings import weakref from itertools import count -from typing import ( - TYPE_CHECKING, - Generic, - TypeVar, - Union, -) +from typing import TYPE_CHECKING, Generic, TypeVar, Union from weakref import ReferenceType, WeakValueDictionary import attrs @@ -185,10 +180,7 @@ def records_untrusted(packet: bytes) -> Iterator[Record]: def encode_record(record: Record) -> bytes: header = RECORD_HEADER.pack( - record.content_type, - record.version, - record.epoch_seqno, - len(record.payload), + record.content_type, record.version, record.epoch_seqno, len(record.payload) ) return header + record.payload @@ -215,13 +207,9 @@ class HandshakeFragment: def decode_handshake_fragment_untrusted(payload: bytes) -> HandshakeFragment: # Raises BadPacket if decoding fails try: - ( - msg_type, - msg_len_bytes, - msg_seq, - frag_offset_bytes, - frag_len_bytes, - ) = HANDSHAKE_MESSAGE_HEADER.unpack_from(payload) + (msg_type, msg_len_bytes, msg_seq, frag_offset_bytes, frag_len_bytes) = ( + HANDSHAKE_MESSAGE_HEADER.unpack_from(payload) + ) except struct.error as exc: raise BadPacket("bad handshake message header") from exc # 'struct' doesn't have built-in support for 24-bit integers, so we @@ -232,14 +220,7 @@ def decode_handshake_fragment_untrusted(payload: bytes) -> HandshakeFragment: frag = payload[HANDSHAKE_MESSAGE_HEADER.size :] if len(frag) != frag_len: raise BadPacket("handshake fragment length doesn't match record length") - return HandshakeFragment( - msg_type, - msg_len, - msg_seq, - frag_offset, - frag_len, - frag, - ) + return HandshakeFragment(msg_type, msg_len, msg_seq, frag_offset, frag_len, frag) def encode_handshake_fragment(hsf: HandshakeFragment) -> bytes: @@ -350,9 +331,7 @@ class OpaqueHandshakeMessage: _AnyHandshakeMessage: TypeAlias = Union[ - HandshakeMessage, - PseudoHandshakeMessage, - OpaqueHandshakeMessage, + HandshakeMessage, PseudoHandshakeMessage, OpaqueHandshakeMessage ] @@ -360,9 +339,7 @@ class OpaqueHandshakeMessage: # reconstructs the handshake messages inside it, so that we can repack them # into records while retransmitting. So the data ought to be well-behaved -- # it's not coming from the network. -def decode_volley_trusted( - volley: bytes, -) -> list[_AnyHandshakeMessage]: +def decode_volley_trusted(volley: bytes) -> list[_AnyHandshakeMessage]: messages: list[_AnyHandshakeMessage] = [] messages_by_seq = {} for record in records_untrusted(volley): @@ -377,10 +354,8 @@ def decode_volley_trusted( elif record.content_type in (ContentType.change_cipher_spec, ContentType.alert): messages.append( PseudoHandshakeMessage( - record.version, - record.content_type, - record.payload, - ), + record.version, record.content_type, record.payload + ) ) else: assert record.content_type == ContentType.handshake @@ -416,9 +391,7 @@ def set_first_record_number(self, n: int) -> None: self._record_seq = count(n) def encode_volley( - self, - messages: Iterable[_AnyHandshakeMessage], - mtu: int, + self, messages: Iterable[_AnyHandshakeMessage], mtu: int ) -> list[bytearray]: packets = [] packet = bytearray() @@ -565,11 +538,7 @@ def _signable(*fields: bytes) -> bytes: def _make_cookie( - key: bytes, - salt: bytes, - tick: int, - address: AddressFormat, - client_hello_bits: bytes, + key: bytes, salt: bytes, tick: int, address: AddressFormat, client_hello_bits: bytes ) -> bytes: assert len(salt) == SALT_BYTES assert len(key) == KEY_BYTES @@ -587,10 +556,7 @@ def _make_cookie( def valid_cookie( - key: bytes, - cookie: bytes, - address: AddressFormat, - client_hello_bits: bytes, + key: bytes, cookie: bytes, address: AddressFormat, client_hello_bits: bytes ) -> bool: if len(cookie) > SALT_BYTES: salt = cookie[:SALT_BYTES] @@ -599,28 +565,20 @@ def valid_cookie( cur_cookie = _make_cookie(key, salt, tick, address, client_hello_bits) old_cookie = _make_cookie( - key, - salt, - max(tick - 1, 0), - address, - client_hello_bits, + key, salt, max(tick - 1, 0), address, client_hello_bits ) # I doubt using a short-circuiting 'or' here would leak any meaningful # information, but why risk it when '|' is just as easy. return hmac.compare_digest(cookie, cur_cookie) | hmac.compare_digest( - cookie, - old_cookie, + cookie, old_cookie ) else: return False def challenge_for( - key: bytes, - address: AddressFormat, - epoch_seqno: int, - client_hello_bits: bytes, + key: bytes, address: AddressFormat, epoch_seqno: int, client_hello_bits: bytes ) -> bytes: salt = os.urandom(SALT_BYTES) tick = _current_cookie_tick() @@ -656,7 +614,7 @@ def challenge_for( payload = encode_handshake_fragment(hs) packet = encode_record( - Record(ContentType.handshake, ProtocolVersion.DTLS10, epoch_seqno, payload), + Record(ContentType.handshake, ProtocolVersion.DTLS10, epoch_seqno, payload) ) return packet @@ -681,9 +639,7 @@ def _read_loop(read_fn: Callable[[int], bytes]) -> bytes: async def handle_client_hello_untrusted( - endpoint: DTLSEndpoint, - address: AddressFormat, - packet: bytes, + endpoint: DTLSEndpoint, address: AddressFormat, packet: bytes ) -> None: # it's trivial to write a simple function that directly calls this to # get code coverage, but it should maybe: @@ -703,10 +659,7 @@ async def handle_client_hello_untrusted( if not valid_cookie(endpoint._listening_key, cookie, address, bits): challenge_packet = challenge_for( - endpoint._listening_key, - address, - epoch_seqno, - bits, + endpoint._listening_key, address, epoch_seqno, bits ) try: async with endpoint._send_lock: @@ -749,8 +702,7 @@ async def handle_client_hello_untrusted( async def dtls_receive_loop( - endpoint_ref: ReferenceType[DTLSEndpoint], - sock: SocketType, + endpoint_ref: ReferenceType[DTLSEndpoint], sock: SocketType ) -> None: try: while True: @@ -841,10 +793,7 @@ class DTLSChannel(trio.abc.Channel[bytes], metaclass=NoPublicConstructor): """ def __init__( - self, - endpoint: DTLSEndpoint, - peer_address: AddressFormat, - ctx: SSL.Context, + self, endpoint: DTLSEndpoint, peer_address: AddressFormat, ctx: SSL.Context ) -> None: self.endpoint = endpoint self.peer_address = peer_address @@ -857,7 +806,7 @@ def __init__( # support and isn't useful anyway -- especially for DTLS where it's equivalent # to just performing a new handshake. ctx.set_options( - SSL.OP_NO_QUERY_MTU | SSL.OP_NO_RENEGOTIATION, # type: ignore[attr-defined] + SSL.OP_NO_QUERY_MTU | SSL.OP_NO_RENEGOTIATION # type: ignore[attr-defined] ) self._ssl = SSL.Connection(ctx) self._handshake_mtu = 0 @@ -881,7 +830,7 @@ def _set_replaced(self) -> None: def _check_replaced(self) -> None: if self._replaced: raise trio.BrokenResourceError( - "peer tore down this connection to start a new one", + "peer tore down this connection to start a new one" ) # XX on systems where we can (maybe just Linux?) take advantage of the kernel's PMTU @@ -935,8 +884,7 @@ async def aclose(self) -> None: async def _send_volley(self, volley_messages: list[_AnyHandshakeMessage]) -> None: packets = self._record_encoder.encode_volley( - volley_messages, - self._handshake_mtu, + volley_messages, self._handshake_mtu ) for packet in packets: async with self.endpoint._send_lock: @@ -1071,8 +1019,7 @@ def read_volley() -> list[_AnyHandshakeMessage]: # PMTU estimate is wrong? Let's try dropping it to the minimum # and hope that helps. self._handshake_mtu = min( - self._handshake_mtu, - worst_case_mtu(self.endpoint.socket), + self._handshake_mtu, worst_case_mtu(self.endpoint.socket) ) async def send(self, data: bytes) -> None: @@ -1088,8 +1035,7 @@ async def send(self, data: bytes) -> None: self._ssl.write(data) async with self.endpoint._send_lock: await self.endpoint.socket.sendto( - _read_loop(self._ssl.bio_read), - self.peer_address, + _read_loop(self._ssl.bio_read), self.peer_address ) async def receive(self) -> bytes: @@ -1195,10 +1141,7 @@ class DTLSEndpoint: """ def __init__( - self, - socket: SocketType, - *, - incoming_packets_buffer: int = 10, + self, socket: SocketType, *, incoming_packets_buffer: int = 10 ) -> None: # We do this lazily on first construction, so only people who actually use DTLS # have to install PyOpenSSL. @@ -1235,9 +1178,7 @@ def _ensure_receive_loop(self) -> None: # after we send our first packet. if not self._receive_loop_spawned: trio.lowlevel.spawn_system_task( - dtls_receive_loop, - weakref.ref(self), - self.socket, + dtls_receive_loop, weakref.ref(self), self.socket ) self._receive_loop_spawned = True @@ -1329,7 +1270,7 @@ async def handler(dtls_channel): except OSError: # TODO: Write test that triggers this raise RuntimeError( # pragma: no cover - "DTLS socket must be bound before it can serve", + "DTLS socket must be bound before it can serve" ) from None self._ensure_receive_loop() # We do cookie verification ourselves, so tell OpenSSL not to worry about it. @@ -1350,9 +1291,7 @@ async def handler_wrapper(stream: DTLSChannel) -> None: self._listening_context = None def connect( - self, - address: tuple[str, int], - ssl_context: SSL.Context, + self, address: tuple[str, int], ssl_context: SSL.Context ) -> DTLSChannel: """Initiate an outgoing DTLS connection. diff --git a/src/trio/_file_io.py b/src/trio/_file_io.py index 5a612ffb0..46e97daa5 100644 --- a/src/trio/_file_io.py +++ b/src/trio/_file_io.py @@ -469,16 +469,8 @@ async def open_file( """ _file = wrap_file( await trio.to_thread.run_sync( - io.open, - file, - mode, - buffering, - encoding, - errors, - newline, - closefd, - opener, - ), + io.open, file, mode, buffering, encoding, errors, newline, closefd, opener + ) ) return _file @@ -507,7 +499,7 @@ def has(attr: str) -> bool: if not (has("close") and (has("read") or has("write"))): raise TypeError( f"{file} does not implement required duck-file methods: " - "close and (read or write)", + "close and (read or write)" ) return AsyncIOWrapper(file) diff --git a/src/trio/_highlevel_generic.py b/src/trio/_highlevel_generic.py index 041a684c6..ea540e31d 100644 --- a/src/trio/_highlevel_generic.py +++ b/src/trio/_highlevel_generic.py @@ -54,10 +54,7 @@ def _is_halfclosable(stream: SendStream) -> TypeGuard[HalfCloseableStream]: @final @attrs.define(eq=False, slots=False) -class StapledStream( - HalfCloseableStream, - Generic[SendStreamT, ReceiveStreamT], -): +class StapledStream(HalfCloseableStream, Generic[SendStreamT, ReceiveStreamT]): """This class `staples `__ together two unidirectional streams to make single bidirectional stream. diff --git a/src/trio/_highlevel_open_tcp_listeners.py b/src/trio/_highlevel_open_tcp_listeners.py index 2e71ca554..7b301191a 100644 --- a/src/trio/_highlevel_open_tcp_listeners.py +++ b/src/trio/_highlevel_open_tcp_listeners.py @@ -55,10 +55,7 @@ def _compute_backlog(backlog: int | None) -> int: async def open_tcp_listeners( - port: int, - *, - host: str | bytes | None = None, - backlog: int | None = None, + port: int, *, host: str | bytes | None = None, backlog: int | None = None ) -> list[trio.SocketListener]: """Create :class:`SocketListener` objects to listen for TCP connections. @@ -112,10 +109,7 @@ async def open_tcp_listeners( computed_backlog = _compute_backlog(backlog) addresses = await tsocket.getaddrinfo( - host, - port, - type=tsocket.SOCK_STREAM, - flags=tsocket.AI_PASSIVE, + host, port, type=tsocket.SOCK_STREAM, flags=tsocket.AI_PASSIVE ) listeners = [] @@ -162,8 +156,7 @@ async def open_tcp_listeners( "socket that that address could use" ) raise OSError(errno.EAFNOSUPPORT, msg) from ExceptionGroup( - msg, - unsupported_address_families, + msg, unsupported_address_families ) return listeners @@ -244,8 +237,5 @@ async def serve_tcp( """ listeners = await trio.open_tcp_listeners(port, host=host, backlog=backlog) await trio.serve_listeners( - handler, - listeners, - handler_nursery=handler_nursery, - task_status=task_status, + handler, listeners, handler_nursery=handler_nursery, task_status=task_status ) diff --git a/src/trio/_highlevel_open_tcp_stream.py b/src/trio/_highlevel_open_tcp_stream.py index d4ec98355..3397aeba8 100644 --- a/src/trio/_highlevel_open_tcp_stream.py +++ b/src/trio/_highlevel_open_tcp_stream.py @@ -136,7 +136,7 @@ def close_all() -> Generator[set[SocketType], None, None]: # Explicit "Any" is not allowed def reorder_for_rfc_6555_section_5_4( # type: ignore[misc] - targets: list[tuple[AddressFamily, SocketKind, int, str, Any]], + targets: list[tuple[AddressFamily, SocketKind, int, str, Any]] ) -> None: # RFC 6555 section 5.4 says that if getaddrinfo returns multiple address # families (e.g. IPv4 and IPv6), then you should make sure that your first @@ -341,16 +341,14 @@ async def attempt_connect( # better job of it because it knows the remote IP/port. with suppress(OSError, AttributeError): sock.setsockopt( - trio.socket.IPPROTO_IP, - trio.socket.IP_BIND_ADDRESS_NO_PORT, - 1, + trio.socket.IPPROTO_IP, trio.socket.IP_BIND_ADDRESS_NO_PORT, 1 ) try: await sock.bind((local_address, 0)) except OSError: raise OSError( f"local_address={local_address!r} is incompatible " - f"with remote address {sockaddr!r}", + f"with remote address {sockaddr!r}" ) from None await sock.connect(sockaddr) @@ -379,9 +377,7 @@ async def attempt_connect( # workaround to check types until typing of nursery.start_soon improved if TYPE_CHECKING: await attempt_connect( - (address_family, socket_type, proto), - addr, - attempt_failed, + (address_family, socket_type, proto), addr, attempt_failed ) nursery.start_soon( diff --git a/src/trio/_highlevel_serve_listeners.py b/src/trio/_highlevel_serve_listeners.py index 9b17f8d53..f6e39fde4 100644 --- a/src/trio/_highlevel_serve_listeners.py +++ b/src/trio/_highlevel_serve_listeners.py @@ -10,12 +10,7 @@ # Errors that accept(2) can return, and which indicate that the system is # overloaded -ACCEPT_CAPACITY_ERRNOS = { - errno.EMFILE, - errno.ENFILE, - errno.ENOMEM, - errno.ENOBUFS, -} +ACCEPT_CAPACITY_ERRNOS = {errno.EMFILE, errno.ENFILE, errno.ENOMEM, errno.ENOBUFS} # How long to sleep when we get one of those errors SLEEP_TIME = 0.100 @@ -146,5 +141,5 @@ async def serve_listeners( # type: ignore[misc] task_status.started(listeners) raise AssertionError( - "_serve_one_listener should never complete", + "_serve_one_listener should never complete" ) # pragma: no cover diff --git a/src/trio/_highlevel_socket.py b/src/trio/_highlevel_socket.py index c04e66e1b..0fb6e2393 100644 --- a/src/trio/_highlevel_socket.py +++ b/src/trio/_highlevel_socket.py @@ -76,7 +76,7 @@ def __init__(self, socket: SocketType) -> None: self.socket = socket self._send_conflict_detector = ConflictDetector( - "another task is currently sending data on this SocketStream", + "another task is currently sending data on this SocketStream" ) # Socket defaults: @@ -167,12 +167,12 @@ def setsockopt( if length is None: if value is None: raise TypeError( - "invalid value for argument 'value', must not be None when specifying length", + "invalid value for argument 'value', must not be None when specifying length" ) return self.socket.setsockopt(level, option, value) if value is not None: raise TypeError( - f"invalid value for argument 'value': {value!r}, must be None when specifying optlen", + f"invalid value for argument 'value': {value!r}, must be None when specifying optlen" ) return self.socket.setsockopt(level, option, value, length) diff --git a/src/trio/_highlevel_ssl_helpers.py b/src/trio/_highlevel_ssl_helpers.py index 1239491a4..e95300911 100644 --- a/src/trio/_highlevel_ssl_helpers.py +++ b/src/trio/_highlevel_ssl_helpers.py @@ -59,9 +59,7 @@ async def open_ssl_over_tcp_stream( """ tcp_stream = await trio.open_tcp_stream( - host, - port, - happy_eyeballs_delay=happy_eyeballs_delay, + host, port, happy_eyeballs_delay=happy_eyeballs_delay ) if ssl_context is None: ssl_context = ssl.create_default_context() @@ -70,10 +68,7 @@ async def open_ssl_over_tcp_stream( ssl_context.options &= ~ssl.OP_IGNORE_UNEXPECTED_EOF return trio.SSLStream( - tcp_stream, - ssl_context, - server_hostname=host, - https_compatible=https_compatible, + tcp_stream, ssl_context, server_hostname=host, https_compatible=https_compatible ) @@ -166,15 +161,8 @@ async def serve_ssl_over_tcp( """ listeners = await trio.open_ssl_over_tcp_listeners( - port, - ssl_context, - host=host, - https_compatible=https_compatible, - backlog=backlog, + port, ssl_context, host=host, https_compatible=https_compatible, backlog=backlog ) await trio.serve_listeners( - handler, - listeners, - handler_nursery=handler_nursery, - task_status=task_status, + handler, listeners, handler_nursery=handler_nursery, task_status=task_status ) diff --git a/src/trio/_path.py b/src/trio/_path.py index a58136b75..b00f4cdc3 100644 --- a/src/trio/_path.py +++ b/src/trio/_path.py @@ -32,7 +32,7 @@ # Explicit .../"Any" is not allowed def _wraps_async( # type: ignore[misc] - wrapped: Callable[..., object], + wrapped: Callable[..., object] ) -> Callable[[Callable[P, T]], Callable[P, Awaitable[T]]]: def decorator(fn: Callable[P, T]) -> Callable[P, Awaitable[T]]: async def wrapper(*args: P.args, **kwargs: P.kwargs) -> T: @@ -51,7 +51,7 @@ async def wrapper(*args: P.args, **kwargs: P.kwargs) -> T: def _wrap_method( - fn: Callable[Concatenate[pathlib.Path, P], T], + fn: Callable[Concatenate[pathlib.Path, P], T] ) -> Callable[Concatenate[Path, P], Awaitable[T]]: @_wraps_async(fn) def wrapper(self: Path, /, *args: P.args, **kwargs: P.kwargs) -> T: @@ -61,7 +61,7 @@ def wrapper(self: Path, /, *args: P.args, **kwargs: P.kwargs) -> T: def _wrap_method_path( - fn: Callable[Concatenate[pathlib.Path, P], pathlib.Path], + fn: Callable[Concatenate[pathlib.Path, P], pathlib.Path] ) -> Callable[Concatenate[PathT, P], Awaitable[PathT]]: @_wraps_async(fn) def wrapper(self: PathT, /, *args: P.args, **kwargs: P.kwargs) -> PathT: @@ -71,7 +71,7 @@ def wrapper(self: PathT, /, *args: P.args, **kwargs: P.kwargs) -> PathT: def _wrap_method_path_iterable( - fn: Callable[Concatenate[pathlib.Path, P], Iterable[pathlib.Path]], + fn: Callable[Concatenate[pathlib.Path, P], Iterable[pathlib.Path]] ) -> Callable[Concatenate[PathT, P], Awaitable[Iterable[PathT]]]: @_wraps_async(fn) def wrapper(self: PathT, /, *args: P.args, **kwargs: P.kwargs) -> Iterable[PathT]: diff --git a/src/trio/_signals.py b/src/trio/_signals.py index 729c48ad4..017368b63 100644 --- a/src/trio/_signals.py +++ b/src/trio/_signals.py @@ -72,7 +72,7 @@ def __init__(self) -> None: self._pending: OrderedDict[int, None] = OrderedDict() self._lot = trio.lowlevel.ParkingLot() self._conflict_detector = ConflictDetector( - "only one task can iterate on a signal receiver at a time", + "only one task can iterate on a signal receiver at a time" ) self._closed = False @@ -170,7 +170,7 @@ def open_signal_receiver( if not is_main_thread(): raise RuntimeError( "Sorry, open_signal_receiver is only possible when running in " - "Python interpreter's main thread", + "Python interpreter's main thread" ) token = trio.lowlevel.current_trio_token() queue = SignalReceiver() diff --git a/src/trio/_socket.py b/src/trio/_socket.py index 259992b71..47825769c 100644 --- a/src/trio/_socket.py +++ b/src/trio/_socket.py @@ -9,14 +9,7 @@ import sys from operator import index from socket import AddressFamily, SocketKind -from typing import ( - TYPE_CHECKING, - Any, - SupportsIndex, - TypeVar, - Union, - overload, -) +from typing import TYPE_CHECKING, Any, SupportsIndex, TypeVar, Union, overload import idna as _idna @@ -63,8 +56,7 @@ # class _try_sync: def __init__( - self, - blocking_exc_override: Callable[[BaseException], bool] | None = None, + self, blocking_exc_override: Callable[[BaseException], bool] | None = None ) -> None: self._blocking_exc_override = blocking_exc_override @@ -181,11 +173,7 @@ async def getaddrinfo( flags: int = 0, ) -> list[ tuple[ - AddressFamily, - SocketKind, - int, - str, - tuple[str, int] | tuple[str, int, int, int], + AddressFamily, SocketKind, int, str, tuple[str, int] | tuple[str, int, int, int] ] ]: """Look up a numeric address given a name. @@ -216,12 +204,7 @@ def numeric_only_failure(exc: BaseException) -> bool: async with _try_sync(numeric_only_failure): return _stdlib_socket.getaddrinfo( - host, - port, - family, - type, - proto, - flags | _NUMERIC_ONLY, + host, port, family, type, proto, flags | _NUMERIC_ONLY ) # That failed; it's a real hostname. We better use a thread. # @@ -256,8 +239,7 @@ def numeric_only_failure(exc: BaseException) -> bool: async def getnameinfo( - sockaddr: tuple[str, int] | tuple[str, int, int, int], - flags: int, + sockaddr: tuple[str, int] | tuple[str, int, int, int], flags: int ) -> tuple[str, str]: """Look up a name given a numeric address. @@ -273,10 +255,7 @@ async def getnameinfo( return await hr.getnameinfo(sockaddr, flags) else: return await trio.to_thread.run_sync( - _stdlib_socket.getnameinfo, - sockaddr, - flags, - abandon_on_cancel=True, + _stdlib_socket.getnameinfo, sockaddr, flags, abandon_on_cancel=True ) @@ -287,9 +266,7 @@ async def getprotobyname(name: str) -> int: """ return await trio.to_thread.run_sync( - _stdlib_socket.getprotobyname, - name, - abandon_on_cancel=True, + _stdlib_socket.getprotobyname, name, abandon_on_cancel=True ) @@ -374,20 +351,14 @@ def socket( return sf.socket(family, type, proto) else: family, type, proto = _sniff_sockopts_for_fileno( # noqa: A001 - family, - type, - proto, - fileno, + family, type, proto, fileno ) stdlib_socket = _stdlib_socket.socket(family, type, proto, fileno) return from_stdlib_socket(stdlib_socket) def _sniff_sockopts_for_fileno( - family: AddressFamily | int, - type_: SocketKind | int, - proto: int, - fileno: int | None, + family: AddressFamily | int, type_: SocketKind | int, proto: int, fileno: int | None ) -> tuple[AddressFamily | int, SocketKind | int, int]: """Correct SOCKOPTS for given fileno, falling back to provided values.""" # Wrap the raw fileno into a Python socket object @@ -485,7 +456,7 @@ async def _resolve_address_nocp( elif family == _stdlib_socket.AF_INET6: if not isinstance(address, tuple) or not 2 <= len(address) <= 4: raise ValueError( - "address should be a (host, port, [flowinfo, [scopeid]]) tuple", + "address should be a (host, port, [flowinfo, [scopeid]]) tuple" ) elif hasattr(_stdlib_socket, "AF_UNIX") and family == _stdlib_socket.AF_UNIX: # unwrap path-likes @@ -551,7 +522,7 @@ def __init__(self) -> None: if type(self) is SocketType: raise TypeError( "SocketType is an abstract class; use trio.socket.socket if you " - "want to construct a socket object", + "want to construct a socket object" ) def detach(self) -> int: @@ -573,11 +544,7 @@ def getsockopt(self, /, level: int, optname: int) -> int: ... def getsockopt(self, /, level: int, optname: int, buflen: int) -> bytes: ... def getsockopt( - self, - /, - level: int, - optname: int, - buflen: int | None = None, + self, /, level: int, optname: int, buflen: int | None = None ) -> int | bytes: raise NotImplementedError @@ -586,12 +553,7 @@ def setsockopt(self, /, level: int, optname: int, value: int | Buffer) -> None: @overload def setsockopt( - self, - /, - level: int, - optname: int, - value: None, - optlen: int, + self, /, level: int, optname: int, value: None, optlen: int ) -> None: ... def setsockopt( @@ -681,27 +643,19 @@ def recv(__self, __buflen: int, __flags: int = 0) -> Awaitable[bytes]: raise NotImplementedError def recv_into( - __self, - buffer: Buffer, - nbytes: int = 0, - flags: int = 0, + __self, buffer: Buffer, nbytes: int = 0, flags: int = 0 ) -> Awaitable[int]: raise NotImplementedError # return type of socket.socket.recvfrom in typeshed is tuple[bytes, Any] def recvfrom( - __self, - __bufsize: int, - __flags: int = 0, + __self, __bufsize: int, __flags: int = 0 ) -> Awaitable[tuple[bytes, AddressFormat]]: raise NotImplementedError # return type of socket.socket.recvfrom_into in typeshed is tuple[bytes, Any] def recvfrom_into( - __self, - buffer: Buffer, - nbytes: int = 0, - flags: int = 0, + __self, buffer: Buffer, nbytes: int = 0, flags: int = 0 ) -> Awaitable[tuple[int, AddressFormat]]: raise NotImplementedError @@ -710,10 +664,7 @@ def recvfrom_into( ): def recvmsg( - __self, - __bufsize: int, - __ancbufsize: int = 0, - __flags: int = 0, + __self, __bufsize: int, __ancbufsize: int = 0, __flags: int = 0 ) -> Awaitable[tuple[bytes, list[tuple[int, int, bytes]], int, object]]: raise NotImplementedError @@ -722,10 +673,7 @@ def recvmsg( ): def recvmsg_into( - __self, - __buffers: Iterable[Buffer], - __ancbufsize: int = 0, - __flags: int = 0, + __self, __buffers: Iterable[Buffer], __ancbufsize: int = 0, __flags: int = 0 ) -> Awaitable[tuple[int, list[tuple[int, int, bytes]], int, object]]: raise NotImplementedError @@ -734,17 +682,12 @@ def send(__self, __bytes: Buffer, __flags: int = 0) -> Awaitable[int]: @overload async def sendto( - self, - __data: Buffer, - __address: tuple[object, ...] | str | Buffer, + self, __data: Buffer, __address: tuple[object, ...] | str | Buffer ) -> int: ... @overload async def sendto( - self, - __data: Buffer, - __flags: int, - __address: tuple[object, ...] | str | Buffer, + self, __data: Buffer, __flags: int, __address: tuple[object, ...] | str | Buffer ) -> int: ... async def sendto(self, *args: object) -> int: @@ -786,7 +729,7 @@ def __init__(self, sock: _stdlib_socket.socket) -> None: # For example, ssl.SSLSocket subclasses socket.socket, but we # certainly don't want to blindly wrap one of those. raise TypeError( - f"expected object of type 'socket.socket', not '{type(sock).__name__}'", + f"expected object of type 'socket.socket', not '{type(sock).__name__}'" ) self._sock = sock self._sock.setblocking(False) @@ -816,11 +759,7 @@ def getsockopt(self, /, level: int, optname: int) -> int: ... def getsockopt(self, /, level: int, optname: int, buflen: int) -> bytes: ... def getsockopt( - self, - /, - level: int, - optname: int, - buflen: int | None = None, + self, /, level: int, optname: int, buflen: int | None = None ) -> int | bytes: if buflen is None: return self._sock.getsockopt(level, optname) @@ -831,12 +770,7 @@ def setsockopt(self, /, level: int, optname: int, value: int | Buffer) -> None: @overload def setsockopt( - self, - /, - level: int, - optname: int, - value: None, - optlen: int, + self, /, level: int, optname: int, value: None, optlen: int ) -> None: ... def setsockopt( @@ -850,12 +784,12 @@ def setsockopt( if optlen is None: if value is None: raise TypeError( - "invalid value for argument 'value', must not be None when specifying optlen", + "invalid value for argument 'value', must not be None when specifying optlen" ) return self._sock.setsockopt(level, optname, value) if value is not None: raise TypeError( - f"invalid value for argument 'value': {value!r}, must be None when specifying optlen", + f"invalid value for argument 'value': {value!r}, must be None when specifying optlen" ) # Note: PyPy may crash here due to setsockopt only supporting @@ -955,15 +889,11 @@ async def wait_writable(self) -> None: await _core.wait_writable(self._sock) async def _resolve_address_nocp( - self, - address: AddressFormat, - *, - local: bool, + self, address: AddressFormat, *, local: bool ) -> AddressFormat: if self.family == _stdlib_socket.AF_INET6: ipv6_v6only = self._sock.getsockopt( - _stdlib_socket.IPPROTO_IPV6, - _stdlib_socket.IPV6_V6ONLY, + _stdlib_socket.IPPROTO_IPV6, _stdlib_socket.IPV6_V6ONLY ) else: ipv6_v6only = False @@ -1025,8 +955,7 @@ async def _nonblocking_helper( ################################################################ _accept = _make_simple_sock_method_wrapper( - _stdlib_socket.socket.accept, - _core.wait_readable, + _stdlib_socket.socket.accept, _core.wait_readable ) async def accept(self) -> tuple[SocketType, AddressFormat]: @@ -1124,8 +1053,7 @@ def recv(__self, __buflen: int, __flags: int = 0) -> Awaitable[bytes]: ... # this requires that we refrain from using `/` to specify pos-only # args, or mypy thinks the signature differs from typeshed. recv = _make_simple_sock_method_wrapper( - _stdlib_socket.socket.recv, - _core.wait_readable, + _stdlib_socket.socket.recv, _core.wait_readable ) ################################################################ @@ -1135,15 +1063,11 @@ def recv(__self, __buflen: int, __flags: int = 0) -> Awaitable[bytes]: ... if TYPE_CHECKING: def recv_into( - __self, - buffer: Buffer, - nbytes: int = 0, - flags: int = 0, + __self, buffer: Buffer, nbytes: int = 0, flags: int = 0 ) -> Awaitable[int]: ... recv_into = _make_simple_sock_method_wrapper( - _stdlib_socket.socket.recv_into, - _core.wait_readable, + _stdlib_socket.socket.recv_into, _core.wait_readable ) ################################################################ @@ -1153,14 +1077,11 @@ def recv_into( if TYPE_CHECKING: # return type of socket.socket.recvfrom in typeshed is tuple[bytes, Any] def recvfrom( - __self, - __bufsize: int, - __flags: int = 0, + __self, __bufsize: int, __flags: int = 0 ) -> Awaitable[tuple[bytes, AddressFormat]]: ... recvfrom = _make_simple_sock_method_wrapper( - _stdlib_socket.socket.recvfrom, - _core.wait_readable, + _stdlib_socket.socket.recvfrom, _core.wait_readable ) ################################################################ @@ -1170,15 +1091,11 @@ def recvfrom( if TYPE_CHECKING: # return type of socket.socket.recvfrom_into in typeshed is tuple[bytes, Any] def recvfrom_into( - __self, - buffer: Buffer, - nbytes: int = 0, - flags: int = 0, + __self, buffer: Buffer, nbytes: int = 0, flags: int = 0 ) -> Awaitable[tuple[int, AddressFormat]]: ... recvfrom_into = _make_simple_sock_method_wrapper( - _stdlib_socket.socket.recvfrom_into, - _core.wait_readable, + _stdlib_socket.socket.recvfrom_into, _core.wait_readable ) ################################################################ @@ -1191,16 +1108,11 @@ def recvfrom_into( if TYPE_CHECKING: def recvmsg( - __self, - __bufsize: int, - __ancbufsize: int = 0, - __flags: int = 0, + __self, __bufsize: int, __ancbufsize: int = 0, __flags: int = 0 ) -> Awaitable[tuple[bytes, list[tuple[int, int, bytes]], int, object]]: ... recvmsg = _make_simple_sock_method_wrapper( - _stdlib_socket.socket.recvmsg, - _core.wait_readable, - maybe_avail=True, + _stdlib_socket.socket.recvmsg, _core.wait_readable, maybe_avail=True ) ################################################################ @@ -1220,9 +1132,7 @@ def recvmsg_into( ) -> Awaitable[tuple[int, list[tuple[int, int, bytes]], int, object]]: ... recvmsg_into = _make_simple_sock_method_wrapper( - _stdlib_socket.socket.recvmsg_into, - _core.wait_readable, - maybe_avail=True, + _stdlib_socket.socket.recvmsg_into, _core.wait_readable, maybe_avail=True ) ################################################################ @@ -1234,8 +1144,7 @@ def recvmsg_into( def send(__self, __bytes: Buffer, __flags: int = 0) -> Awaitable[int]: ... send = _make_simple_sock_method_wrapper( - _stdlib_socket.socket.send, - _core.wait_writable, + _stdlib_socket.socket.send, _core.wait_writable ) ################################################################ @@ -1244,17 +1153,12 @@ def send(__self, __bytes: Buffer, __flags: int = 0) -> Awaitable[int]: ... @overload async def sendto( - self, - __data: Buffer, - __address: tuple[object, ...] | str | Buffer, + self, __data: Buffer, __address: tuple[object, ...] | str | Buffer ) -> int: ... @overload async def sendto( - self, - __data: Buffer, - __flags: int, - __address: tuple[object, ...] | str | Buffer, + self, __data: Buffer, __flags: int, __address: tuple[object, ...] | str | Buffer ) -> int: ... @_wraps(_stdlib_socket.socket.sendto, assigned=(), updated=()) diff --git a/src/trio/_ssl.py b/src/trio/_ssl.py index 0a0419fbc..210725d08 100644 --- a/src/trio/_ssl.py +++ b/src/trio/_ssl.py @@ -226,9 +226,7 @@ class _Once: __slots__ = ("_afn", "_args", "_done", "started") def __init__( - self, - afn: Callable[[*Ts], Awaitable[object]], - *args: Unpack[Ts], + self, afn: Callable[[*Ts], Awaitable[object]], *args: Unpack[Ts] ) -> None: self._afn = afn self._args = args @@ -386,10 +384,10 @@ def __init__( # multiple concurrent calls to send_all/wait_send_all_might_not_block # or to receive_some. self._outer_send_conflict_detector = ConflictDetector( - "another task is currently sending data on this SSLStream", + "another task is currently sending data on this SSLStream" ) self._outer_recv_conflict_detector = ConflictDetector( - "another task is currently receiving data on this SSLStream", + "another task is currently receiving data on this SSLStream" ) self._estimated_receive_size = STARTING_RECEIVE_SIZE @@ -424,10 +422,7 @@ def __init__( } # Explicit "Any" is not allowed - def __getattr__( # type: ignore[misc] - self, - name: str, - ) -> Any: + def __getattr__(self, name: str) -> Any: # type: ignore[misc] if name in self._forwarded: if name in self._after_handshake and not self._handshook.done: raise NeedHandshakeError(f"call do_handshake() before calling {name!r}") @@ -629,8 +624,7 @@ async def _retry( self._incoming.write_eof() else: self._estimated_receive_size = max( - self._estimated_receive_size, - len(data), + self._estimated_receive_size, len(data) ) self._incoming.write(data) self._inner_recv_count += 1 diff --git a/src/trio/_subprocess.py b/src/trio/_subprocess.py index ff5cc8d39..ea1b310ca 100644 --- a/src/trio/_subprocess.py +++ b/src/trio/_subprocess.py @@ -233,7 +233,7 @@ async def wait(self) -> int: if self.poll() is None: if self._pidfd is not None: with contextlib.suppress( - ClosedResourceError, + ClosedResourceError ): # something else (probably a call to poll) already closed the pidfd await trio.lowlevel.wait_readable(self._pidfd.fileno()) else: @@ -358,7 +358,7 @@ async def _open_process( if options.get(key): raise TypeError( "trio.Process only supports communicating over " - f"unbuffered byte streams; the '{key}' option is not supported", + f"unbuffered byte streams; the '{key}' option is not supported" ) if os.name == "posix": @@ -366,12 +366,12 @@ async def _open_process( if isinstance(command, (str, bytes)) and not options.get("shell"): raise TypeError( "command must be a sequence (not a string or bytes) if " - "shell=False on UNIX systems", + "shell=False on UNIX systems" ) if not isinstance(command, (str, bytes)) and options.get("shell"): raise TypeError( "command must be a string or bytes (not a sequence) if " - "shell=True on UNIX systems", + "shell=True on UNIX systems" ) trio_stdin: ClosableSendStream | None = None @@ -414,7 +414,7 @@ async def _open_process( stdout=stdout, stderr=stderr, **options, - ), + ) ) # We did not fail, so dismiss the stack for the trio ends cleanup_on_fail.pop_all() @@ -441,7 +441,7 @@ async def _posix_deliver_cancel(p: Process) -> None: RuntimeWarning( f"process {p!r} ignored SIGTERM for 5 seconds. " "(Maybe you should pass a custom deliver_cancel?) " - "Trying SIGKILL.", + "Trying SIGKILL." ), stacklevel=1, ) @@ -669,17 +669,17 @@ async def my_deliver_cancel(process): raise ValueError( "stdout=subprocess.PIPE is only valid with nursery.start, " "since that's the only way to access the pipe; use nursery.start " - "or pass the data you want to write directly", + "or pass the data you want to write directly" ) if options.get("stdout") is subprocess.PIPE: raise ValueError( "stdout=subprocess.PIPE is only valid with nursery.start, " - "since that's the only way to access the pipe", + "since that's the only way to access the pipe" ) if options.get("stderr") is subprocess.PIPE: raise ValueError( "stderr=subprocess.PIPE is only valid with nursery.start, " - "since that's the only way to access the pipe", + "since that's the only way to access the pipe" ) if isinstance(stdin, (bytes, bytearray, memoryview)): input_ = stdin @@ -719,8 +719,7 @@ async def feed_input(stream: SendStream) -> None: pass async def read_output( - stream: ReceiveStream, - chunks: list[bytes | bytearray], + stream: ReceiveStream, chunks: list[bytes | bytearray] ) -> None: async with stream: async for chunk in stream: @@ -766,10 +765,7 @@ async def killer() -> None: if proc.returncode and check: raise subprocess.CalledProcessError( - proc.returncode, - proc.args, - output=stdout, - stderr=stderr, + proc.returncode, proc.args, output=stdout, stderr=stderr ) else: assert proc.returncode is not None diff --git a/src/trio/_subprocess_platform/kqueue.py b/src/trio/_subprocess_platform/kqueue.py index 2283bb536..fcf72650e 100644 --- a/src/trio/_subprocess_platform/kqueue.py +++ b/src/trio/_subprocess_platform/kqueue.py @@ -21,10 +21,7 @@ async def wait_child_exiting(process: _subprocess.Process) -> None: def make_event(flags: int) -> select.kevent: return select.kevent( - process.pid, - filter=select.KQ_FILTER_PROC, - flags=flags, - fflags=KQ_NOTE_EXIT, + process.pid, filter=select.KQ_FILTER_PROC, flags=flags, fflags=KQ_NOTE_EXIT ) try: diff --git a/src/trio/_subprocess_platform/waitid.py b/src/trio/_subprocess_platform/waitid.py index ebf83b480..44c826107 100644 --- a/src/trio/_subprocess_platform/waitid.py +++ b/src/trio/_subprocess_platform/waitid.py @@ -40,7 +40,7 @@ def sync_wait_reapable(pid: int) -> None: int pad[26]; } siginfo_t; int waitid(int idtype, int id, siginfo_t* result, int options); -""", +""" ) waitid_cffi = waitid_ffi.dlopen(None).waitid # type: ignore[attr-defined] @@ -79,10 +79,7 @@ async def _waitid_system_task(pid: int, event: Event) -> None: try: await to_thread_run_sync( - sync_wait_reapable, - pid, - abandon_on_cancel=True, - limiter=waitid_limiter, + sync_wait_reapable, pid, abandon_on_cancel=True, limiter=waitid_limiter ) except OSError: # If waitid fails, waitpid will fail too, so it still makes diff --git a/src/trio/_sync.py b/src/trio/_sync.py index ca373922b..7080b6c91 100644 --- a/src/trio/_sync.py +++ b/src/trio/_sync.py @@ -304,7 +304,7 @@ def acquire_on_behalf_of_nowait(self, borrower: Task | object) -> None: """ if borrower in self._borrowers: raise RuntimeError( - "this borrower is already holding one of this CapacityLimiter's tokens", + "this borrower is already holding one of this CapacityLimiter's tokens" ) if len(self._borrowers) < self._total_tokens and not self._lot: self._borrowers.add(borrower) @@ -373,7 +373,7 @@ def release_on_behalf_of(self, borrower: Task | object) -> None: """ if borrower not in self._borrowers: raise RuntimeError( - "this borrower isn't holding any of this CapacityLimiter's tokens", + "this borrower isn't holding any of this CapacityLimiter's tokens" ) self._borrowers.remove(borrower) self._wake_waiters() @@ -605,7 +605,7 @@ async def acquire(self) -> None: await self._lot.park() except trio.BrokenResourceError: raise trio.BrokenResourceError( - f"Owner of this lock exited without releasing: {self._owner}", + f"Owner of this lock exited without releasing: {self._owner}" ) from None else: await trio.lowlevel.cancel_shielded_checkpoint() @@ -641,9 +641,7 @@ def statistics(self) -> LockStatistics: """ return LockStatistics( - locked=self.locked(), - owner=self._owner, - tasks_waiting=len(self._lot), + locked=self.locked(), owner=self._owner, tasks_waiting=len(self._lot) ) @@ -871,6 +869,5 @@ def statistics(self) -> ConditionStatistics: """ return ConditionStatistics( - tasks_waiting=len(self._lot), - lock_statistics=self._lock.statistics(), + tasks_waiting=len(self._lot), lock_statistics=self._lock.statistics() ) diff --git a/src/trio/_tests/check_type_completeness.py b/src/trio/_tests/check_type_completeness.py index ea53aa0e3..d188f8bc9 100755 --- a/src/trio/_tests/check_type_completeness.py +++ b/src/trio/_tests/check_type_completeness.py @@ -111,9 +111,7 @@ def has_docstring_at_runtime(name: str) -> bool: def check_type( - platform: str, - full_diagnostics_file: Path | None, - expected_errors: list[object], + platform: str, full_diagnostics_file: Path | None, expected_errors: list[object] ) -> list[object]: # convince isort we use the trio import assert trio @@ -146,7 +144,7 @@ def check_type( if message.startswith("No docstring found for"): continue if message.startswith( - "Type is missing type annotation and could be inferred differently by type checkers", + "Type is missing type annotation and could be inferred differently by type checkers" ): continue diff --git a/src/trio/_tests/module_with_deprecations.py b/src/trio/_tests/module_with_deprecations.py index afe418719..73184d11e 100644 --- a/src/trio/_tests/module_with_deprecations.py +++ b/src/trio/_tests/module_with_deprecations.py @@ -16,9 +16,6 @@ __deprecated_attributes__ = { "dep1": _deprecate.DeprecatedAttribute("value1", "1.1", issue=1), "dep2": _deprecate.DeprecatedAttribute( - "value2", - "1.2", - issue=1, - instead="instead-string", + "value2", "1.2", issue=1, instead="instead-string" ), } diff --git a/src/trio/_tests/test_channel.py b/src/trio/_tests/test_channel.py index 001f07568..68879523f 100644 --- a/src/trio/_tests/test_channel.py +++ b/src/trio/_tests/test_channel.py @@ -107,8 +107,7 @@ async def consumer(receive_channel: trio.MemoryReceiveChannel[int], i: int) -> N async def test_close_basics() -> None: async def send_block( - s: trio.MemorySendChannel[None], - expect: type[BaseException], + s: trio.MemorySendChannel[None], expect: type[BaseException] ) -> None: with pytest.raises(expect): await s.send(None) @@ -165,8 +164,7 @@ async def receive_block(r: trio.MemoryReceiveChannel[int]) -> None: async def test_close_sync() -> None: async def send_block( - s: trio.MemorySendChannel[None], - expect: type[BaseException], + s: trio.MemorySendChannel[None], expect: type[BaseException] ) -> None: with pytest.raises(expect): await s.send(None) diff --git a/src/trio/_tests/test_contextvars.py b/src/trio/_tests/test_contextvars.py index 63965e1e1..ae0c25f87 100644 --- a/src/trio/_tests/test_contextvars.py +++ b/src/trio/_tests/test_contextvars.py @@ -5,7 +5,7 @@ from .. import _core trio_testing_contextvar: contextvars.ContextVar[str] = contextvars.ContextVar( - "trio_testing_contextvar", + "trio_testing_contextvar" ) diff --git a/src/trio/_tests/test_deprecate.py b/src/trio/_tests/test_deprecate.py index 1da1549d3..fa5d7cbfe 100644 --- a/src/trio/_tests/test_deprecate.py +++ b/src/trio/_tests/test_deprecate.py @@ -161,10 +161,7 @@ def new_hotness_method(self) -> str: return "new hotness method" old_hotness_method = deprecated_alias( - "Alias.old_hotness_method", - new_hotness_method, - "3.21", - issue=1, + "Alias.old_hotness_method", new_hotness_method, "3.21", issue=1 ) @@ -275,9 +272,5 @@ def test_warning_class() -> None: with pytest.warns(TrioDeprecationWarning): warn_deprecated( - "foo", - "bar", - issue=None, - instead=None, - use_triodeprecationwarning=True, + "foo", "bar", issue=None, instead=None, use_triodeprecationwarning=True ) diff --git a/src/trio/_tests/test_deprecate_strict_exception_groups_false.py b/src/trio/_tests/test_deprecate_strict_exception_groups_false.py index 1b02c9ee7..8317b043c 100644 --- a/src/trio/_tests/test_deprecate_strict_exception_groups_false.py +++ b/src/trio/_tests/test_deprecate_strict_exception_groups_false.py @@ -7,8 +7,7 @@ async def test_deprecation_warning_open_nursery() -> None: with pytest.warns( - trio.TrioDeprecationWarning, - match="strict_exception_groups=False", + trio.TrioDeprecationWarning, match="strict_exception_groups=False" ) as record: async with trio.open_nursery(strict_exception_groups=False): ... @@ -34,8 +33,7 @@ async def foo_loose_nursery() -> None: def helper(fun: Callable[[], Awaitable[None]], num: int) -> None: with pytest.warns( - trio.TrioDeprecationWarning, - match="strict_exception_groups=False", + trio.TrioDeprecationWarning, match="strict_exception_groups=False" ) as record: trio.run(fun, strict_exception_groups=False) assert len(record) == num @@ -54,11 +52,7 @@ async def trio_return(in_host: object) -> str: return "ok" with pytest.warns( - trio.TrioDeprecationWarning, - match="strict_exception_groups=False", + trio.TrioDeprecationWarning, match="strict_exception_groups=False" ) as record: - trivial_guest_run( - trio_return, - strict_exception_groups=False, - ) + trivial_guest_run(trio_return, strict_exception_groups=False) assert len(record) == 1 diff --git a/src/trio/_tests/test_dtls.py b/src/trio/_tests/test_dtls.py index 3f8ee2f05..22a795106 100644 --- a/src/trio/_tests/test_dtls.py +++ b/src/trio/_tests/test_dtls.py @@ -38,9 +38,7 @@ parametrize_ipv6 = pytest.mark.parametrize( - "ipv6", - [False, pytest.param(True, marks=binds_ipv6)], - ids=["ipv4", "ipv6"], + "ipv6", [False, pytest.param(True, marks=binds_ipv6)], ids=["ipv4", "ipv6"] ) @@ -53,10 +51,7 @@ def endpoint(**kwargs: int | bool) -> DTLSEndpoint: @asynccontextmanager async def dtls_echo_server( - *, - autocancel: bool = True, - mtu: int | None = None, - ipv6: bool = False, + *, autocancel: bool = True, mtu: int | None = None, ipv6: bool = False ) -> AsyncGenerator[tuple[DTLSEndpoint, tuple[str, int]], None]: with endpoint(ipv6=ipv6) as server: localhost = "::1" if ipv6 else "127.0.0.1" @@ -67,7 +62,7 @@ async def echo_handler(dtls_channel: DTLSChannel) -> None: print( "echo handler started: " f"server {dtls_channel.endpoint.socket.getsockname()!r} " - f"client {dtls_channel.peer_address!r}", + f"client {dtls_channel.peer_address!r}" ) if mtu is not None: dtls_channel.set_ciphertext_mtu(mtu) @@ -104,8 +99,7 @@ async def test_smoke(ipv6: bool) -> None: assert await client_channel.receive() == b"goodbye" with pytest.raises( - ValueError, - match="^openssl doesn't support sending empty DTLS packets$", + ValueError, match="^openssl doesn't support sending empty DTLS packets$" ): await client_channel.send(b"") @@ -171,7 +165,7 @@ async def route_packet(packet: UDPPacket) -> None: assert op == "deliver" print( f"{packet.source} -> {packet.destination}: delivered" - f" {packet.payload.hex()}", + f" {packet.payload.hex()}" ) fn.deliver_packet(packet) break @@ -231,8 +225,7 @@ async def handler(channel: DTLSChannel) -> None: await server_nursery.start(server_endpoint.serve, server_ctx, handler) client = client_endpoint.connect( - server_endpoint.socket.getsockname(), - client_ctx, + server_endpoint.socket.getsockname(), client_ctx ) async with trio.open_nursery() as nursery: nursery.start_soon(client.send, b"from client") @@ -379,9 +372,9 @@ async def test_server_socket_doesnt_crash_on_garbage( frag_offset=0, frag_len=10, frag=bytes(10), - ), + ) ), - ), + ) ) client_hello_extended = client_hello + b"\x00" @@ -404,9 +397,9 @@ async def test_server_socket_doesnt_crash_on_garbage( frag_offset=0, frag_len=10, frag=bytes(10), - ), + ) ), - ), + ) ) client_hello_trailing_data_in_record = encode_record( @@ -422,10 +415,10 @@ async def test_server_socket_doesnt_crash_on_garbage( frag_offset=0, frag_len=10, frag=bytes(10), - ), + ) ) + b"\x00", - ), + ) ) handshake_empty = encode_record( @@ -434,7 +427,7 @@ async def test_server_socket_doesnt_crash_on_garbage( version=ProtocolVersion.DTLS10, epoch_seqno=0, payload=b"", - ), + ) ) client_hello_truncated_in_cookie = encode_record( @@ -443,7 +436,7 @@ async def test_server_socket_doesnt_crash_on_garbage( version=ProtocolVersion.DTLS10, epoch_seqno=0, payload=bytes(2 + 32 + 1) + b"\xff", - ), + ) ) async with dtls_echo_server() as (_, address): @@ -627,8 +620,7 @@ async def connecter() -> None: # notices the timeout has expired blackholed = False await server_endpoint.socket.sendto( - b"xxx", - client_endpoint.socket.getsockname(), + b"xxx", client_endpoint.socket.getsockname() ) # now the client task should finish connecting and exit cleanly @@ -690,8 +682,7 @@ def route_packet(packet: UDPPacket) -> None: @parametrize_ipv6 async def test_handshake_handles_minimum_network_mtu( - ipv6: bool, - autojump_clock: trio.abc.Clock, + ipv6: bool, autojump_clock: trio.abc.Clock ) -> None: # Fake network that has the minimum allowable MTU for whatever protocol we're using. fn = FakeNet() diff --git a/src/trio/_tests/test_exports.py b/src/trio/_tests/test_exports.py index de2449755..bd677281e 100644 --- a/src/trio/_tests/test_exports.py +++ b/src/trio/_tests/test_exports.py @@ -55,7 +55,7 @@ def _ensure_mypy_cache_updated() -> None: "--no-error-summary", "-c", "import trio", - ], + ] ) assert not result[1] # stderr assert not result[0] # stdout @@ -72,8 +72,7 @@ def test_core_is_properly_reexported() -> None: found = 0 for source in sources: if symbol in dir(source) and getattr(source, symbol) is getattr( - _core, - symbol, + _core, symbol ): found += 1 print(symbol, found) @@ -92,8 +91,7 @@ def class_is_final(cls: type) -> bool: def iter_modules( - module: types.ModuleType, - only_public: bool, + module: types.ModuleType, only_public: bool ) -> Iterator[types.ModuleType]: yield module for name, class_ in module.__dict__.items(): @@ -128,7 +126,7 @@ def iter_modules( @pytest.mark.parametrize("tool", ["pylint", "jedi", "mypy", "pyright_verifytypes"]) @pytest.mark.filterwarnings( # https://github.com/pypa/setuptools/issues/3274 - "ignore:module 'sre_constants' is deprecated:DeprecationWarning", + "ignore:module 'sre_constants' is deprecated:DeprecationWarning" ) def test_static_tool_sees_all_symbols(tool: str, modname: str, tmp_path: Path) -> None: module = importlib.import_module(modname) @@ -207,8 +205,7 @@ def no_underscores(symbols: Iterable[str]) -> set[str]: import subprocess res = subprocess.run( - ["pyright", f"--verifytypes={modname}", "--outputjson"], - capture_output=True, + ["pyright", f"--verifytypes={modname}", "--outputjson"], capture_output=True ) current_result = json.loads(res.stdout) @@ -253,9 +250,7 @@ def no_underscores(symbols: Iterable[str]) -> set[str]: @pytest.mark.parametrize("module_name", PUBLIC_MODULE_NAMES) @pytest.mark.parametrize("tool", ["jedi", "mypy"]) def test_static_tool_sees_class_members( - tool: str, - module_name: str, - tmp_path: Path, + tool: str, module_name: str, tmp_path: Path ) -> None: module = PUBLIC_MODULES[PUBLIC_MODULE_NAMES.index(module_name)] @@ -377,7 +372,7 @@ def lookup_symbol(symbol: str) -> dict[str, str]: skip_if_optional_else_raise(error) script = jedi.Script( - f"from {module_name} import {class_name}; {class_name}.", + f"from {module_name} import {class_name}; {class_name}." ) completions = script.complete() static_names = no_hidden(c.name for c in completions) - ignore_names @@ -459,11 +454,7 @@ def lookup_symbol(symbol: str) -> dict[str, str]: "send_all_hook", "wait_send_all_might_not_block_hook", }, - trio.testing.Matcher: { - "exception_type", - "match", - "check", - }, + trio.testing.Matcher: {"exception_type", "match", "check"}, } if tool == "mypy" and class_ in EXTRAS: before = len(extra) @@ -511,10 +502,7 @@ def lookup_symbol(symbol: str) -> dict[str, str]: missing.remove("with_segments") if missing or extra: # pragma: no cover - errors[f"{module_name}.{class_name}"] = { - "missing": missing, - "extra": extra, - } + errors[f"{module_name}.{class_name}"] = {"missing": missing, "extra": extra} # `assert not errors` will not print the full content of errors, even with # `--verbose`, so we manually print it diff --git a/src/trio/_tests/test_fakenet.py b/src/trio/_tests/test_fakenet.py index 7a3c328e8..d52a762f0 100644 --- a/src/trio/_tests/test_fakenet.py +++ b/src/trio/_tests/test_fakenet.py @@ -34,16 +34,14 @@ async def test_basic_udp() -> None: assert port != 0 with pytest.raises( - OSError, - match=r"^\[\w+ \d+\] Invalid argument$", + OSError, match=r"^\[\w+ \d+\] Invalid argument$" ) as exc: # Cannot rebind. await s1.bind(("192.0.2.1", 0)) assert exc.value.errno == errno.EINVAL # Cannot bind multiple sockets to the same address with pytest.raises( - OSError, - match=r"^\[\w+ \d+\] (Address (already )?in use|Unknown error)$", + OSError, match=r"^\[\w+ \d+\] (Address (already )?in use|Unknown error)$" ) as exc: await s2.bind(("127.0.0.1", port)) assert exc.value.errno == errno.EADDRINUSE @@ -133,8 +131,7 @@ async def test_recv_methods() -> None: @pytest.mark.skipif( - sys.platform == "win32", - reason="functions not in socket on windows", + sys.platform == "win32", reason="functions not in socket on windows" ) async def test_nonwindows_functionality() -> None: # mypy doesn't support a good way of aborting typechecking on different platforms @@ -183,15 +180,13 @@ async def test_nonwindows_functionality() -> None: assert addr == s1.getsockname() with pytest.raises( - AttributeError, - match="^'FakeSocket' object has no attribute 'share'$", + AttributeError, match="^'FakeSocket' object has no attribute 'share'$" ): await s1.share(0) # type: ignore[attr-defined] @pytest.mark.skipif( - sys.platform != "win32", - reason="windows-specific fakesocket testing", + sys.platform != "win32", reason="windows-specific fakesocket testing" ) async def test_windows_functionality() -> None: # mypy doesn't support a good way of aborting typechecking on different platforms @@ -201,13 +196,11 @@ async def test_windows_functionality() -> None: s2 = trio.socket.socket(type=trio.socket.SOCK_DGRAM) await s1.bind(("127.0.0.1", 0)) with pytest.raises( - AttributeError, - match="^'FakeSocket' object has no attribute 'sendmsg'$", + AttributeError, match="^'FakeSocket' object has no attribute 'sendmsg'$" ): await s1.sendmsg([b"jkl"], (), 0, s2.getsockname()) # type: ignore[attr-defined] with pytest.raises( - AttributeError, - match="^'FakeSocket' object has no attribute 'recvmsg'$", + AttributeError, match="^'FakeSocket' object has no attribute 'recvmsg'$" ): s2.recvmsg(0) # type: ignore[attr-defined] with pytest.raises( @@ -231,33 +224,28 @@ async def test_not_implemented_functions() -> None: # getsockopt with pytest.raises( - OSError, - match=r"^FakeNet doesn't implement getsockopt\(\d, \d\)$", + OSError, match=r"^FakeNet doesn't implement getsockopt\(\d, \d\)$" ): s1.getsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY) # setsockopt with pytest.raises( - NotImplementedError, - match="^FakeNet always has IPV6_V6ONLY=True$", + NotImplementedError, match="^FakeNet always has IPV6_V6ONLY=True$" ): s1.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, False) with pytest.raises( - OSError, - match=r"^FakeNet doesn't implement setsockopt\(\d+, \d+, \.\.\.\)$", + OSError, match=r"^FakeNet doesn't implement setsockopt\(\d+, \d+, \.\.\.\)$" ): s1.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, True) with pytest.raises( - OSError, - match=r"^FakeNet doesn't implement setsockopt\(\d+, \d+, \.\.\.\)$", + OSError, match=r"^FakeNet doesn't implement setsockopt\(\d+, \d+, \.\.\.\)$" ): s1.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # set_inheritable s1.set_inheritable(False) with pytest.raises( - NotImplementedError, - match="^FakeNet can't make inheritable sockets$", + NotImplementedError, match="^FakeNet can't make inheritable sockets$" ): s1.set_inheritable(True) @@ -286,7 +274,7 @@ async def test_init() -> None: with pytest.raises( NotImplementedError, match=re.escape( - f"FakeNet doesn't (yet) support type={trio.socket.SOCK_STREAM}", + f"FakeNet doesn't (yet) support type={trio.socket.SOCK_STREAM}" ), ): s1 = trio.socket.socket() diff --git a/src/trio/_tests/test_file_io.py b/src/trio/_tests/test_file_io.py index 390a81ce6..df945dc83 100644 --- a/src/trio/_tests/test_file_io.py +++ b/src/trio/_tests/test_file_io.py @@ -59,15 +59,13 @@ def write(self) -> None: # pragma: no cover def test_wrapped_property( - async_file: AsyncIOWrapper[mock.Mock], - wrapped: mock.Mock, + async_file: AsyncIOWrapper[mock.Mock], wrapped: mock.Mock ) -> None: assert async_file.wrapped is wrapped def test_dir_matches_wrapped( - async_file: AsyncIOWrapper[mock.Mock], - wrapped: mock.Mock, + async_file: AsyncIOWrapper[mock.Mock], wrapped: mock.Mock ) -> None: attrs = _FILE_SYNC_ATTRS.union(_FILE_ASYNC_METHODS) @@ -134,8 +132,7 @@ def test_type_stubs_match_lists() -> None: def test_sync_attrs_forwarded( - async_file: AsyncIOWrapper[mock.Mock], - wrapped: mock.Mock, + async_file: AsyncIOWrapper[mock.Mock], wrapped: mock.Mock ) -> None: for attr_name in _FILE_SYNC_ATTRS: if attr_name not in dir(async_file): @@ -145,8 +142,7 @@ def test_sync_attrs_forwarded( def test_sync_attrs_match_wrapper( - async_file: AsyncIOWrapper[mock.Mock], - wrapped: mock.Mock, + async_file: AsyncIOWrapper[mock.Mock], wrapped: mock.Mock ) -> None: for attr_name in _FILE_SYNC_ATTRS: if attr_name in dir(async_file): @@ -178,8 +174,7 @@ def test_async_methods_signature(async_file: AsyncIOWrapper[mock.Mock]) -> None: async def test_async_methods_wrap( - async_file: AsyncIOWrapper[mock.Mock], - wrapped: mock.Mock, + async_file: AsyncIOWrapper[mock.Mock], wrapped: mock.Mock ) -> None: for meth_name in _FILE_ASYNC_METHODS: if meth_name not in dir(async_file): @@ -191,8 +186,7 @@ async def test_async_methods_wrap( value = await meth(sentinel.argument, keyword=sentinel.keyword) wrapped_meth.assert_called_once_with( - sentinel.argument, - keyword=sentinel.keyword, + sentinel.argument, keyword=sentinel.keyword ) assert value == wrapped_meth() @@ -200,8 +194,7 @@ async def test_async_methods_wrap( def test_async_methods_match_wrapper( - async_file: AsyncIOWrapper[mock.Mock], - wrapped: mock.Mock, + async_file: AsyncIOWrapper[mock.Mock], wrapped: mock.Mock ) -> None: for meth_name in _FILE_ASYNC_METHODS: if meth_name in dir(async_file): diff --git a/src/trio/_tests/test_highlevel_generic.py b/src/trio/_tests/test_highlevel_generic.py index 1fcedba74..0cad05266 100644 --- a/src/trio/_tests/test_highlevel_generic.py +++ b/src/trio/_tests/test_highlevel_generic.py @@ -45,10 +45,7 @@ async def test_StapledStream() -> None: await stapled.send_all(b"foo") await stapled.wait_send_all_might_not_block() - assert send_stream.record == [ - ("send_all", b"foo"), - "wait_send_all_might_not_block", - ] + assert send_stream.record == [("send_all", b"foo"), "wait_send_all_might_not_block"] send_stream.record.clear() await stapled.send_eof() diff --git a/src/trio/_tests/test_highlevel_open_tcp_listeners.py b/src/trio/_tests/test_highlevel_open_tcp_listeners.py index 61abd43f0..dba33f5d7 100644 --- a/src/trio/_tests/test_highlevel_open_tcp_listeners.py +++ b/src/trio/_tests/test_highlevel_open_tcp_listeners.py @@ -10,12 +10,7 @@ import pytest import trio -from trio import ( - SocketListener, - open_tcp_listeners, - open_tcp_stream, - serve_tcp, -) +from trio import SocketListener, open_tcp_listeners, open_tcp_stream, serve_tcp from trio.abc import HostnameResolver, SendStream, SocketFactory from trio.testing import open_stream_to_socket_listener @@ -120,14 +115,7 @@ async def test_open_tcp_listeners_rebind() -> None: assert s_established.socket.getsockname() == sockaddr2 assert c_time_wait.socket.getpeername() == sockaddr2 - for resource in [ - l1, - l2, - c_established, - s_established, - c_time_wait, - s_time_wait, - ]: + for resource in [l1, l2, c_established, s_established, c_time_wait, s_time_wait]: await resource.aclose() @@ -164,11 +152,7 @@ def getsockopt(self, /, level: int, optname: int) -> int: ... def getsockopt(self, /, level: int, optname: int, buflen: int) -> bytes: ... def getsockopt( - self, - /, - level: int, - optname: int, - buflen: int | None = None, + self, /, level: int, optname: int, buflen: int | None = None ) -> int | bytes: if (level, optname) == (tsocket.SOL_SOCKET, tsocket.SO_ACCEPTCONN): return True @@ -179,12 +163,7 @@ def setsockopt(self, /, level: int, optname: int, value: int | Buffer) -> None: @overload def setsockopt( - self, - /, - level: int, - optname: int, - value: None, - optlen: int, + self, /, level: int, optname: int, value: None, optlen: int ) -> None: ... def setsockopt( @@ -265,9 +244,7 @@ async def getaddrinfo( ] async def getnameinfo( - self, - sockaddr: tuple[str, int] | tuple[str, int, int, int], - flags: int, + self, sockaddr: tuple[str, int] | tuple[str, int, int, int], flags: int ) -> tuple[str, str]: raise NotImplementedError() @@ -283,8 +260,8 @@ async def test_open_tcp_listeners_multiple_host_cleanup_on_error() -> None: (tsocket.AF_INET, "1.1.1.1"), (tsocket.AF_INET, "2.2.2.2"), (tsocket.AF_INET, "3.3.3.3"), - ], - ), + ] + ) ) with pytest.raises(FakeOSError): @@ -330,16 +307,14 @@ async def handler(stream: SendStream) -> None: [{tsocket.AF_INET}, {tsocket.AF_INET6}, {tsocket.AF_INET, tsocket.AF_INET6}], ) async def test_open_tcp_listeners_some_address_families_unavailable( - try_families: set[AddressFamily], - fail_families: set[AddressFamily], + try_families: set[AddressFamily], fail_families: set[AddressFamily] ) -> None: fsf = FakeSocketFactory( - 10, - raise_on_family=dict.fromkeys(fail_families, errno.EAFNOSUPPORT), + 10, raise_on_family=dict.fromkeys(fail_families, errno.EAFNOSUPPORT) ) tsocket.set_custom_socket_factory(fsf) tsocket.set_custom_hostname_resolver( - FakeHostnameResolver([(family, "foo") for family in try_families]), + FakeHostnameResolver([(family, "foo") for family in try_families]) ) should_succeed = try_families - fail_families @@ -371,7 +346,7 @@ async def test_open_tcp_listeners_socket_fails_not_afnosupport() -> None: ) tsocket.set_custom_socket_factory(fsf) tsocket.set_custom_hostname_resolver( - FakeHostnameResolver([(tsocket.AF_INET, "foo"), (tsocket.AF_INET6, "bar")]), + FakeHostnameResolver([(tsocket.AF_INET, "foo"), (tsocket.AF_INET6, "bar")]) ) with pytest.raises(OSError, match="nope") as exc_info: @@ -392,12 +367,7 @@ async def test_open_tcp_listeners_socket_fails_not_afnosupport() -> None: async def test_open_tcp_listeners_backlog() -> None: fsf = FakeSocketFactory(99) tsocket.set_custom_socket_factory(fsf) - for given, expected in [ - (None, 0xFFFF), - (99999999, 0xFFFF), - (10, 10), - (1, 1), - ]: + for given, expected in [(None, 0xFFFF), (99999999, 0xFFFF), (10, 10), (1, 1)]: listeners = await open_tcp_listeners(0, backlog=given) assert listeners for listener in listeners: @@ -410,7 +380,6 @@ async def test_open_tcp_listeners_backlog_float_error() -> None: tsocket.set_custom_socket_factory(fsf) for should_fail in (0.0, 2.18, 3.15, 9.75): with pytest.raises( - TypeError, - match=f"backlog must be an int or None, not {should_fail!r}", + TypeError, match=f"backlog must be an int or None, not {should_fail!r}" ): await open_tcp_listeners(0, backlog=should_fail) # type: ignore[arg-type] diff --git a/src/trio/_tests/test_highlevel_open_tcp_stream.py b/src/trio/_tests/test_highlevel_open_tcp_stream.py index 98adf7efe..4c3ee0b1c 100644 --- a/src/trio/_tests/test_highlevel_open_tcp_stream.py +++ b/src/trio/_tests/test_highlevel_open_tcp_stream.py @@ -62,13 +62,7 @@ def test_reorder_for_rfc_6555_section_5_4() -> None: def fake4( i: int, ) -> tuple[socket.AddressFamily, socket.SocketKind, int, str, tuple[str, int]]: - return ( - AF_INET, - SOCK_STREAM, - IPPROTO_TCP, - "", - (f"10.0.0.{i}", 80), - ) + return (AF_INET, SOCK_STREAM, IPPROTO_TCP, "", (f"10.0.0.{i}", 80)) def fake6( i: int, @@ -158,14 +152,12 @@ async def test_local_address_real() -> None: local_address = "127.0.0.2" if can_bind_127_0_0_2() else "127.0.0.1" async with await open_tcp_stream( - *listener.getsockname(), - local_address=local_address, + *listener.getsockname(), local_address=local_address ) as client_stream: assert client_stream.socket.getsockname()[0] == local_address if hasattr(trio.socket, "IP_BIND_ADDRESS_NO_PORT"): assert client_stream.socket.getsockopt( - trio.socket.IPPROTO_IP, - trio.socket.IP_BIND_ADDRESS_NO_PORT, + trio.socket.IPPROTO_IP, trio.socket.IP_BIND_ADDRESS_NO_PORT ) server_sock, remote_addr = await listener.accept() await client_stream.aclose() @@ -176,15 +168,13 @@ async def test_local_address_real() -> None: # Trying to connect to an ipv4 address with the ipv6 wildcard # local_address should fail with pytest.raises( - OSError, - match=r"^all attempts to connect* to *127\.0\.0\.\d:\d+ failed$", + OSError, match=r"^all attempts to connect* to *127\.0\.0\.\d:\d+ failed$" ): await open_tcp_stream(*listener.getsockname(), local_address="::") # But the ipv4 wildcard address should work async with await open_tcp_stream( - *listener.getsockname(), - local_address="0.0.0.0", + *listener.getsockname(), local_address="0.0.0.0" ) as client_stream: server_sock, remote_addr = await listener.accept() server_sock.close() @@ -282,12 +272,10 @@ def socket( self.socket_count += 1 return FakeSocket(self, family, type_, proto) - def _ip_to_gai_entry(self, ip: str) -> tuple[ - AddressFamily, - SocketKind, - int, - str, - tuple[str, int, int, int] | tuple[str, int], + def _ip_to_gai_entry( + self, ip: str + ) -> tuple[ + AddressFamily, SocketKind, int, str, tuple[str, int, int, int] | tuple[str, int] ]: sockaddr: tuple[str, int] | tuple[str, int, int, int] if ":" in ip: @@ -324,9 +312,7 @@ async def getaddrinfo( return [self._ip_to_gai_entry(ip) for ip in self.ip_order] async def getnameinfo( - self, - sockaddr: tuple[str, int] | tuple[str, int, int, int], - flags: int, + self, sockaddr: tuple[str, int] | tuple[str, int, int, int], flags: int ) -> tuple[str, str]: raise NotImplementedError @@ -405,9 +391,7 @@ async def test_one_host_slow_success(autojump_clock: MockClock) -> None: async def test_one_host_quick_fail(autojump_clock: MockClock) -> None: exc, _scenario = await run_scenario( - 82, - [("1.2.3.4", 0.123, "error")], - expect_error=OSError, + 82, [("1.2.3.4", 0.123, "error")], expect_error=OSError ) assert isinstance(exc, OSError) assert trio.current_time() == 0.123 @@ -415,9 +399,7 @@ async def test_one_host_quick_fail(autojump_clock: MockClock) -> None: async def test_one_host_slow_fail(autojump_clock: MockClock) -> None: exc, _scenario = await run_scenario( - 83, - [("1.2.3.4", 100, "error")], - expect_error=OSError, + 83, [("1.2.3.4", 100, "error")], expect_error=OSError ) assert isinstance(exc, OSError) assert trio.current_time() == 100 @@ -425,9 +407,7 @@ async def test_one_host_slow_fail(autojump_clock: MockClock) -> None: async def test_one_host_failed_after_connect(autojump_clock: MockClock) -> None: exc, _scenario = await run_scenario( - 83, - [("1.2.3.4", 1, "postconnect_fail")], - expect_error=KeyboardInterrupt, + 83, [("1.2.3.4", 1, "postconnect_fail")], expect_error=KeyboardInterrupt ) assert isinstance(exc, KeyboardInterrupt) @@ -446,11 +426,7 @@ async def test_basic_fallthrough(autojump_clock: MockClock) -> None: assert sock.ip == "3.3.3.3" # current time is default time + default time + connection time assert trio.current_time() == (0.250 + 0.250 + 0.2) - assert scenario.connect_times == { - "1.1.1.1": 0, - "2.2.2.2": 0.250, - "3.3.3.3": 0.500, - } + assert scenario.connect_times == {"1.1.1.1": 0, "2.2.2.2": 0.250, "3.3.3.3": 0.500} async def test_early_success(autojump_clock: MockClock) -> None: @@ -486,11 +462,7 @@ async def test_custom_delay(autojump_clock: MockClock) -> None: assert isinstance(sock, FakeSocket) assert sock.ip == "1.1.1.1" assert trio.current_time() == 1 - assert scenario.connect_times == { - "1.1.1.1": 0, - "2.2.2.2": 0.450, - "3.3.3.3": 0.900, - } + assert scenario.connect_times == {"1.1.1.1": 0, "2.2.2.2": 0.450, "3.3.3.3": 0.900} async def test_none_default(autojump_clock: MockClock) -> None: @@ -508,11 +480,7 @@ async def test_none_default(autojump_clock: MockClock) -> None: assert sock.ip == "3.3.3.3" # current time is default time + default time + connection time assert trio.current_time() == (0.250 + 0.250 + 0.2) - assert scenario.connect_times == { - "1.1.1.1": 0, - "2.2.2.2": 0.250, - "3.3.3.3": 0.500, - } + assert scenario.connect_times == {"1.1.1.1": 0, "2.2.2.2": 0.250, "3.3.3.3": 0.500} async def test_custom_errors_expedite(autojump_clock: MockClock) -> None: @@ -552,8 +520,7 @@ async def test_all_fail(autojump_clock: MockClock) -> None: subexceptions = (Matcher(OSError, match="^sorry$"),) * 4 assert RaisesGroup( - *subexceptions, - match="all attempts to connect to test.example.com:80 failed", + *subexceptions, match="all attempts to connect to test.example.com:80 failed" ).matches(exc.__cause__) assert trio.current_time() == (0.1 + 0.2 + 10) @@ -611,10 +578,7 @@ async def test_does_reorder(autojump_clock: MockClock) -> None: assert isinstance(sock, FakeSocket) assert sock.ip == "::3" assert trio.current_time() == 1 + 0.5 - assert scenario.connect_times == { - "1.1.1.1": 0, - "::3": 1, - } + assert scenario.connect_times == {"1.1.1.1": 0, "::3": 1} async def test_handles_no_ipv4(autojump_clock: MockClock) -> None: @@ -634,10 +598,7 @@ async def test_handles_no_ipv4(autojump_clock: MockClock) -> None: assert isinstance(sock, FakeSocket) assert sock.ip == "::3" assert trio.current_time() == 1 + 0.1 - assert scenario.connect_times == { - "::1": 0, - "::3": 1.0, - } + assert scenario.connect_times == {"::1": 0, "::3": 1.0} async def test_handles_no_ipv6(autojump_clock: MockClock) -> None: @@ -657,10 +618,7 @@ async def test_handles_no_ipv6(autojump_clock: MockClock) -> None: assert isinstance(sock, FakeSocket) assert sock.ip == "4.4.4.4" assert trio.current_time() == 1 + 0.1 - assert scenario.connect_times == { - "2.2.2.2": 0, - "4.4.4.4": 1.0, - } + assert scenario.connect_times == {"2.2.2.2": 0, "4.4.4.4": 1.0} async def test_no_hosts(autojump_clock: MockClock) -> None: diff --git a/src/trio/_tests/test_highlevel_open_unix_stream.py b/src/trio/_tests/test_highlevel_open_unix_stream.py index 4441d751d..38c31b8a4 100644 --- a/src/trio/_tests/test_highlevel_open_unix_stream.py +++ b/src/trio/_tests/test_highlevel_open_unix_stream.py @@ -12,8 +12,7 @@ assert not TYPE_CHECKING or sys.platform != "win32" skip_if_not_unix = pytest.mark.skipif( - not hasattr(socket, "AF_UNIX"), - reason="Needs unix socket support", + not hasattr(socket, "AF_UNIX"), reason="Needs unix socket support" ) @@ -80,7 +79,6 @@ async def test_open_unix_socket() -> None: @pytest.mark.skipif(hasattr(socket, "AF_UNIX"), reason="Test for non-unix platforms") async def test_error_on_no_unix() -> None: with pytest.raises( - RuntimeError, - match="^Unix sockets are not supported on this platform$", + RuntimeError, match="^Unix sockets are not supported on this platform$" ): await open_unix_socket("") diff --git a/src/trio/_tests/test_highlevel_serve_listeners.py b/src/trio/_tests/test_highlevel_serve_listeners.py index 013d13078..71e1400db 100644 --- a/src/trio/_tests/test_highlevel_serve_listeners.py +++ b/src/trio/_tests/test_highlevel_serve_listeners.py @@ -96,11 +96,7 @@ async def do_tests(parent_nursery: Nursery) -> None: parent_nursery.cancel_scope.cancel() async with trio.open_nursery() as nursery: - value = await nursery.start( - trio.serve_listeners, - handler, - listeners, - ) + value = await nursery.start(trio.serve_listeners, handler, listeners) assert isinstance(value, list) l2 = cast(list[MemoryListener], value) assert l2 == listeners @@ -129,8 +125,7 @@ def check_error(e: BaseException) -> bool: async def test_serve_listeners_accept_capacity_error( - autojump_clock: MockClock, - caplog: pytest.LogCaptureFixture, + autojump_clock: MockClock, caplog: pytest.LogCaptureFixture ) -> None: listener = MemoryListener() @@ -162,8 +157,7 @@ class Done(Exception): pass async def connection_watcher( - *, - task_status: TaskStatus[Nursery] = trio.TASK_STATUS_IGNORED, + *, task_status: TaskStatus[Nursery] = trio.TASK_STATUS_IGNORED ) -> NoReturn: async with trio.open_nursery() as nursery: task_status.started(nursery) @@ -183,7 +177,7 @@ async def connection_watcher( handler, [listener], handler_nursery=handler_nursery, - ), + ) ) for _ in range(10): nursery.start_soon(listener.connect) diff --git a/src/trio/_tests/test_highlevel_socket.py b/src/trio/_tests/test_highlevel_socket.py index 7e9d35245..85d664c40 100644 --- a/src/trio/_tests/test_highlevel_socket.py +++ b/src/trio/_tests/test_highlevel_socket.py @@ -30,8 +30,7 @@ async def test_SocketStream_basics() -> None: # DGRAM socket bad with tsocket.socket(type=tsocket.SOCK_DGRAM) as sock: with pytest.raises( - ValueError, - match="^SocketStream requires a SOCK_STREAM socket$", + ValueError, match="^SocketStream requires a SOCK_STREAM socket$" ): # TODO: does not raise an error? SocketStream(sock) @@ -134,10 +133,7 @@ async def waiter(nursery: _core.Nursery) -> None: async def test_SocketStream_generic() -> None: - async def stream_maker() -> tuple[ - SocketStream, - SocketStream, - ]: + async def stream_maker() -> tuple[SocketStream, SocketStream]: left, right = tsocket.socketpair() return SocketStream(left), SocketStream(right) @@ -162,8 +158,7 @@ async def test_SocketListener() -> None: with tsocket.socket(type=tsocket.SOCK_DGRAM) as s: await s.bind(("127.0.0.1", 0)) with pytest.raises( - ValueError, - match="^SocketListener requires a SOCK_STREAM socket$", + ValueError, match="^SocketListener requires a SOCK_STREAM socket$" ) as excinfo: SocketListener(s) excinfo.match(r".*SOCK_STREAM") @@ -174,8 +169,7 @@ async def test_SocketListener() -> None: with tsocket.socket() as s: await s.bind(("127.0.0.1", 0)) with pytest.raises( - ValueError, - match="^SocketListener requires a listening socket$", + ValueError, match="^SocketListener requires a listening socket$" ) as excinfo: SocketListener(s) excinfo.match(r".*listen") @@ -237,39 +231,22 @@ def getsockopt(self, /, level: int, optname: int) -> int: ... @overload def getsockopt( # noqa: F811 - self, - /, - level: int, - optname: int, - buflen: int, + self, /, level: int, optname: int, buflen: int ) -> bytes: ... def getsockopt( # noqa: F811 - self, - /, - level: int, - optname: int, - buflen: int | None = None, + self, /, level: int, optname: int, buflen: int | None = None ) -> int | bytes: return True @overload def setsockopt( - self, - /, - level: int, - optname: int, - value: int | Buffer, + self, /, level: int, optname: int, value: int | Buffer ) -> None: ... @overload def setsockopt( # noqa: F811 - self, - /, - level: int, - optname: int, - value: None, - optlen: int, + self, /, level: int, optname: int, value: None, optlen: int ) -> None: ... def setsockopt( # noqa: F811 @@ -302,7 +279,7 @@ async def accept(self) -> tuple[SocketType, object]: OSError(errno.EFAULT, "attempt to write to read-only memory"), OSError(errno.ENOBUFS, "out of buffers"), fake_server_sock, - ], + ] ) listener = SocketListener(fake_listen_sock) diff --git a/src/trio/_tests/test_highlevel_ssl_helpers.py b/src/trio/_tests/test_highlevel_ssl_helpers.py index 68aa47846..4508c6600 100644 --- a/src/trio/_tests/test_highlevel_ssl_helpers.py +++ b/src/trio/_tests/test_highlevel_ssl_helpers.py @@ -66,9 +66,7 @@ async def getaddrinfo( return [(AF_INET, SOCK_STREAM, IPPROTO_TCP, "", self.sockaddr)] async def getnameinfo( - self, - sockaddr: tuple[str, int] | tuple[str, int, int, int], - flags: int, + self, sockaddr: tuple[str, int] | tuple[str, int, int, int], flags: int ) -> NoReturn: # pragma: no cover raise NotImplementedError @@ -83,13 +81,7 @@ async def test_open_ssl_over_tcp_stream_and_everything_else( # according to current type hints, and probably for good reason. But there should # maybe be a different wrapper class/function that could be used instead? value = await nursery.start( - partial( - serve_ssl_over_tcp, - echo_handler, - 0, - SERVER_CTX, - host="127.0.0.1", - ), + partial(serve_ssl_over_tcp, echo_handler, 0, SERVER_CTX, host="127.0.0.1") ) assert isinstance(value, list) res = cast(list[SSLListener[SocketListener]], value) # type: ignore[type-var] @@ -112,9 +104,7 @@ async def test_open_ssl_over_tcp_stream_and_everything_else( # We have the trust but not the hostname # (checks custom ssl_context + hostname checking) stream = await open_ssl_over_tcp_stream( - "xyzzy.example.org", - 80, - ssl_context=client_ctx, + "xyzzy.example.org", 80, ssl_context=client_ctx ) async with stream: with pytest.raises(trio.BrokenResourceError): @@ -122,9 +112,7 @@ async def test_open_ssl_over_tcp_stream_and_everything_else( # This one should work! stream = await open_ssl_over_tcp_stream( - "trio-test-1.example.org", - 80, - ssl_context=client_ctx, + "trio-test-1.example.org", 80, ssl_context=client_ctx ) async with stream: assert isinstance(stream, trio.SSLStream) @@ -160,10 +148,7 @@ async def test_open_ssl_over_tcp_listeners() -> None: assert not listener._https_compatible (listener,) = await open_ssl_over_tcp_listeners( - 0, - SERVER_CTX, - host="127.0.0.1", - https_compatible=True, + 0, SERVER_CTX, host="127.0.0.1", https_compatible=True ) async with listener: assert listener._https_compatible diff --git a/src/trio/_tests/test_path.py b/src/trio/_tests/test_path.py index aa383e725..ea532f56a 100644 --- a/src/trio/_tests/test_path.py +++ b/src/trio/_tests/test_path.py @@ -19,8 +19,7 @@ def path(tmp_path: pathlib.Path) -> trio.Path: def method_pair( - path: str, - method_name: str, + path: str, method_name: str ) -> tuple[Callable[[], object], Callable[[], Awaitable[object]]]: sync_path = pathlib.Path(path) async_path = trio.Path(path) @@ -98,15 +97,10 @@ def test_div_magic(cls_a: PathOrStrType, cls_b: PathOrStrType) -> None: @pytest.mark.parametrize( - ("cls_a", "cls_b"), - [(trio.Path, pathlib.Path), (trio.Path, trio.Path)], + ("cls_a", "cls_b"), [(trio.Path, pathlib.Path), (trio.Path, trio.Path)] ) @pytest.mark.parametrize("path", ["foo", "foo/bar/baz", "./foo"]) -def test_hash_magic( - cls_a: EitherPathType, - cls_b: EitherPathType, - path: str, -) -> None: +def test_hash_magic(cls_a: EitherPathType, cls_b: EitherPathType, path: str) -> None: a, b = cls_a(path), cls_b(path) assert hash(a) == hash(b) @@ -182,8 +176,7 @@ def test_repr() -> None: @pytest.mark.parametrize("meth", [trio.Path.__init__, trio.Path.joinpath]) async def test_path_wraps_path( - path: trio.Path, - meth: Callable[[trio.Path, trio.Path], object], + path: trio.Path, meth: Callable[[trio.Path, trio.Path], object] ) -> None: wrapped = await path.absolute() result = meth(path, wrapped) @@ -267,7 +260,7 @@ async def test_classmethods() -> None: ], ) def test_wrapping_without_docstrings( - wrapper: Callable[[Callable[[], None]], Callable[[], None]], + wrapper: Callable[[Callable[[], None]], Callable[[], None]] ) -> None: @wrapper def func_without_docstring() -> None: ... # pragma: no cover diff --git a/src/trio/_tests/test_repl.py b/src/trio/_tests/test_repl.py index be9338ce4..3bc03d813 100644 --- a/src/trio/_tests/test_repl.py +++ b/src/trio/_tests/test_repl.py @@ -48,8 +48,7 @@ def build_locals() -> dict[str, object]: async def test_basic_interaction( - capsys: pytest.CaptureFixture[str], - monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], monkeypatch: pytest.MonkeyPatch ) -> None: """ Run some basic commands through the interpreter while capturing stdout. @@ -76,7 +75,7 @@ async def test_basic_interaction( # import works "import sys", "sys.stdout.write('hello stdout\\n')", - ], + ] ) monkeypatch.setattr(console, "raw_input", raw_input) await trio._repl.run_repl(console) @@ -86,19 +85,14 @@ async def test_basic_interaction( async def test_system_exits_quit_interpreter(monkeypatch: pytest.MonkeyPatch) -> None: console = trio._repl.TrioInteractiveConsole(repl_locals=build_locals()) - raw_input = build_raw_input( - [ - "raise SystemExit", - ], - ) + raw_input = build_raw_input(["raise SystemExit"]) monkeypatch.setattr(console, "raw_input", raw_input) with pytest.raises(SystemExit): await trio._repl.run_repl(console) async def test_KI_interrupts( - capsys: pytest.CaptureFixture[str], - monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], monkeypatch: pytest.MonkeyPatch ) -> None: console = trio._repl.TrioInteractiveConsole(repl_locals=build_locals()) raw_input = build_raw_input( @@ -114,7 +108,7 @@ async def test_KI_interrupts( "", "await f()", "print('AFTER KeyboardInterrupt')", - ], + ] ) monkeypatch.setattr(console, "raw_input", raw_input) await trio._repl.run_repl(console) @@ -125,8 +119,7 @@ async def test_KI_interrupts( async def test_system_exits_in_exc_group( - capsys: pytest.CaptureFixture[str], - monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], monkeypatch: pytest.MonkeyPatch ) -> None: console = trio._repl.TrioInteractiveConsole(repl_locals=build_locals()) raw_input = build_raw_input( @@ -137,7 +130,7 @@ async def test_system_exits_in_exc_group( "", "raise BaseExceptionGroup('', [RuntimeError(), SystemExit()])", "print('AFTER BaseExceptionGroup')", - ], + ] ) monkeypatch.setattr(console, "raw_input", raw_input) await trio._repl.run_repl(console) @@ -148,8 +141,7 @@ async def test_system_exits_in_exc_group( async def test_system_exits_in_nested_exc_group( - capsys: pytest.CaptureFixture[str], - monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], monkeypatch: pytest.MonkeyPatch ) -> None: console = trio._repl.TrioInteractiveConsole(repl_locals=build_locals()) raw_input = build_raw_input( @@ -161,7 +153,7 @@ async def test_system_exits_in_nested_exc_group( "raise BaseExceptionGroup(", " '', [BaseExceptionGroup('', [RuntimeError(), SystemExit()])])", "print('AFTER BaseExceptionGroup')", - ], + ] ) monkeypatch.setattr(console, "raw_input", raw_input) await trio._repl.run_repl(console) @@ -172,8 +164,7 @@ async def test_system_exits_in_nested_exc_group( async def test_base_exception_captured( - capsys: pytest.CaptureFixture[str], - monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], monkeypatch: pytest.MonkeyPatch ) -> None: console = trio._repl.TrioInteractiveConsole(repl_locals=build_locals()) raw_input = build_raw_input( @@ -181,7 +172,7 @@ async def test_base_exception_captured( # The statement after raise should still get executed "raise BaseException", "print('AFTER BaseException')", - ], + ] ) monkeypatch.setattr(console, "raw_input", raw_input) await trio._repl.run_repl(console) @@ -192,8 +183,7 @@ async def test_base_exception_captured( async def test_exc_group_captured( - capsys: pytest.CaptureFixture[str], - monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], monkeypatch: pytest.MonkeyPatch ) -> None: console = trio._repl.TrioInteractiveConsole(repl_locals=build_locals()) raw_input = build_raw_input( @@ -201,7 +191,7 @@ async def test_exc_group_captured( # The statement after raise should still get executed "raise ExceptionGroup('', [KeyError()])", "print('AFTER ExceptionGroup')", - ], + ] ) monkeypatch.setattr(console, "raw_input", raw_input) await trio._repl.run_repl(console) @@ -210,8 +200,7 @@ async def test_exc_group_captured( async def test_base_exception_capture_from_coroutine( - capsys: pytest.CaptureFixture[str], - monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], monkeypatch: pytest.MonkeyPatch ) -> None: console = trio._repl.TrioInteractiveConsole(repl_locals=build_locals()) raw_input = build_raw_input( @@ -223,7 +212,7 @@ async def test_base_exception_capture_from_coroutine( # be executed "await async_func_raises_base_exception()", "print('AFTER BaseException')", - ], + ] ) monkeypatch.setattr(console, "raw_input", raw_input) await trio._repl.run_repl(console) diff --git a/src/trio/_tests/test_signals.py b/src/trio/_tests/test_signals.py index d149b8657..3ece36b66 100644 --- a/src/trio/_tests/test_signals.py +++ b/src/trio/_tests/test_signals.py @@ -42,8 +42,7 @@ async def test_open_signal_receiver() -> None: async def test_open_signal_receiver_restore_handler_after_one_bad_signal() -> None: orig = signal.getsignal(signal.SIGILL) with pytest.raises( - ValueError, - match="(signal number out of range|invalid signal value)$", + ValueError, match="(signal number out of range|invalid signal value)$" ): with open_signal_receiver(signal.SIGILL, 1234567): pass # pragma: no cover diff --git a/src/trio/_tests/test_socket.py b/src/trio/_tests/test_socket.py index dc4bb467a..4d2ff4fa8 100644 --- a/src/trio/_tests/test_socket.py +++ b/src/trio/_tests/test_socket.py @@ -34,12 +34,7 @@ ] GetAddrInfoResponse: TypeAlias = list[GaiTuple] GetAddrInfoArgs: TypeAlias = tuple[ - Union[str, bytes, None], - Union[str, bytes, int, None], - int, - int, - int, - int, + Union[str, bytes, None], Union[str, bytes, int, None], int, int, int, int ] else: GaiTuple: object @@ -62,10 +57,7 @@ def __init__( ], ) -> None: self._orig_getaddrinfo = orig_getaddrinfo - self._responses: dict[ - GetAddrInfoArgs, - GetAddrInfoResponse | str, - ] = {} + self._responses: dict[GetAddrInfoArgs, GetAddrInfoResponse | str] = {} self.record: list[GetAddrInfoArgs] = [] # get a normalized getaddrinfo argument tuple @@ -97,12 +89,7 @@ def set( ) -> None: self._responses[ self._frozenbind( - host, - port, - family=family, - type=type, - proto=proto, - flags=flags, + host, port, family=family, type=type, proto=proto, flags=flags ) ] = response @@ -218,7 +205,7 @@ def filtered( tsocket.IPPROTO_TCP, "", ("127.0.0.1", 12345), - ), + ) ], ) @@ -233,7 +220,7 @@ def filtered( tsocket.IPPROTO_UDP, "", ("::1", 12345, 0, 0), - ), + ) ], ) @@ -530,8 +517,7 @@ async def test_SocketType_shutdown() -> None: ], ) async def test_SocketType_simple_server( - address: str, - socket_type: AddressFamily, + address: str, socket_type: AddressFamily ) -> None: # listen, bind, accept, connect, getpeername, getsockname listener = tsocket.socket(socket_type) @@ -615,8 +601,7 @@ def pad(addr: tuple[str | int, ...]) -> tuple[str | int, ...]: return addr def assert_eq( - actual: tuple[str | int, ...], - expected: tuple[str | int, ...], + actual: tuple[str | int, ...], expected: tuple[str | int, ...] ) -> None: assert pad(expected) == pad(actual) @@ -648,7 +633,7 @@ async def res( | tuple[str, str] | tuple[str, str, int] | tuple[str, str, int, int] - ), + ) ) -> tuple[str | int, ...]: value = await sock._resolve_address_nocp( args, @@ -701,8 +686,7 @@ async def res( # smoke test the basic functionality... try: netlink_sock = tsocket.socket( - family=tsocket.AF_NETLINK, - type=tsocket.SOCK_DGRAM, + family=tsocket.AF_NETLINK, type=tsocket.SOCK_DGRAM ) except (AttributeError, OSError): pass @@ -719,10 +703,7 @@ async def res( await res("1.2.3.4") # type: ignore[arg-type] with pytest.raises(ValueError, match=address): await res(("1.2.3.4",)) # type: ignore[arg-type] - with pytest.raises( - ValueError, - match=address, - ): + with pytest.raises(ValueError, match=address): if v6: await res(("1.2.3.4", 80, 0, 0, 0)) # type: ignore[arg-type] else: @@ -850,18 +831,13 @@ async def test_SocketType_connect_paths() -> None: # nose -- and then swap it back out again before we hit # wait_socket_writable, which insists on a real socket. class CancelSocket(stdlib_socket.socket): - def connect( - self, - address: AddressFormat, - ) -> None: + def connect(self, address: AddressFormat) -> None: # accessing private method only available in _SocketType assert isinstance(sock, _SocketType) cancel_scope.cancel() sock._sock = stdlib_socket.fromfd( - self.detach(), - self.family, - self.type, + self.detach(), self.family, self.type ) sock._sock.connect(address) # If connect *doesn't* raise, then pretend it did @@ -910,9 +886,7 @@ async def test_resolve_address_exception_in_connect_closes_socket() -> None: with tsocket.socket() as sock: async def _resolve_address_nocp( - address: AddressFormat, - *, - local: bool, + address: AddressFormat, *, local: bool ) -> None: assert address == "" assert not local @@ -1052,20 +1026,12 @@ async def test_custom_hostname_resolver(monkeygai: MonkeypatchedGAI) -> None: # This intentionally breaks the signatures used in HostnameResolver class CustomResolver: async def getaddrinfo( - self, - host: str, - port: str, - family: int, - type: int, - proto: int, - flags: int, + self, host: str, port: str, family: int, type: int, proto: int, flags: int ) -> tuple[str, str, str, int, int, int, int]: return ("custom_gai", host, port, family, type, proto, flags) async def getnameinfo( - self, - sockaddr: tuple[str, int] | tuple[str, int, int, int], - flags: int, + self, sockaddr: tuple[str, int] | tuple[str, int, int, int], flags: int ) -> tuple[str, tuple[str, int] | tuple[str, int, int, int], int]: return ("custom_gni", sockaddr, flags) @@ -1112,10 +1078,7 @@ async def getnameinfo( async def test_custom_socket_factory() -> None: class CustomSocketFactory: def socket( - self, - family: AddressFamily, - type: SocketKind, - proto: int, + self, family: AddressFamily, type: SocketKind, proto: int ) -> tuple[str, AddressFamily, SocketKind, int]: return ("hi", family, type, proto) diff --git a/src/trio/_tests/test_ssl.py b/src/trio/_tests/test_ssl.py index 2a16a0cd1..6a7f7017c 100644 --- a/src/trio/_tests/test_ssl.py +++ b/src/trio/_tests/test_ssl.py @@ -8,23 +8,14 @@ from contextlib import asynccontextmanager, contextmanager, suppress from functools import partial from ssl import SSLContext -from typing import ( - TYPE_CHECKING, - Any, - NoReturn, -) +from typing import TYPE_CHECKING, Any, NoReturn import pytest from trio import StapledStream from trio._tests.pytest_plugin import skip_if_optional_else_raise from trio.abc import ReceiveStream, SendStream -from trio.testing import ( - Matcher, - MemoryReceiveStream, - MemorySendStream, - RaisesGroup, -) +from trio.testing import Matcher, MemoryReceiveStream, MemorySendStream, RaisesGroup try: import trustme @@ -114,15 +105,11 @@ def client_ctx(request: pytest.FixtureRequest) -> ssl.SSLContext: # The blocking socket server. def ssl_echo_serve_sync( - sock: stdlib_socket.socket, - *, - expect_fail: bool = False, + sock: stdlib_socket.socket, *, expect_fail: bool = False ) -> None: try: wrapped = SERVER_CTX.wrap_socket( - sock, - server_side=True, - suppress_ragged_eofs=False, + sock, server_side=True, suppress_ragged_eofs=False ) with wrapped: wrapped.do_handshake() @@ -188,8 +175,7 @@ async def ssl_echo_server_raw(expect_fail: bool = False) -> AsyncIterator[Socket # echo server (running in a thread) @asynccontextmanager async def ssl_echo_server( - client_ctx: SSLContext, - expect_fail: bool = False, + client_ctx: SSLContext, expect_fail: bool = False ) -> AsyncIterator[SSLStream[Stream]]: async with ssl_echo_server_raw(expect_fail=expect_fail) as sock: yield SSLStream(sock, client_ctx, server_hostname="trio-test-1.example.org") @@ -201,10 +187,7 @@ async def ssl_echo_server( # jakkdl: it seems to implement all the abstract methods (now), so I made it inherit # from Stream for the sake of typechecking. class PyOpenSSLEchoStream(Stream): - def __init__( - self, - sleeper: Callable[[str], Awaitable[None]] | None = None, - ) -> None: + def __init__(self, sleeper: Callable[[str], Awaitable[None]] | None = None) -> None: ctx = SSL.Context(SSL.SSLv23_METHOD) # TLS 1.3 removes renegotiation support. Which is great for them, but # we still have to support versions before that, and that means we @@ -246,10 +229,10 @@ def __init__( self._pending_cleartext = bytearray() self._send_all_conflict_detector = ConflictDetector( - "simultaneous calls to PyOpenSSLEchoStream.send_all", + "simultaneous calls to PyOpenSSLEchoStream.send_all" ) self._receive_some_conflict_detector = ConflictDetector( - "simultaneous calls to PyOpenSSLEchoStream.receive_some", + "simultaneous calls to PyOpenSSLEchoStream.receive_some" ) self.sleeper: Callable[[str], Awaitable[None]] @@ -366,10 +349,7 @@ async def test_PyOpenSSLEchoStream_gives_resource_busy_errors() -> None: # PyOpenSSLEchoStream will notice and complain. async def do_test( - func1: str, - args1: tuple[object, ...], - func2: str, - args2: tuple[object, ...], + func1: str, args1: tuple[object, ...], func2: str, args2: tuple[object, ...] ) -> None: s = PyOpenSSLEchoStream() with RaisesGroup(Matcher(_core.BusyResourceError, "simultaneous")): @@ -380,18 +360,14 @@ async def do_test( await do_test("send_all", (b"x",), "send_all", (b"x",)) await do_test("send_all", (b"x",), "wait_send_all_might_not_block", ()) await do_test( - "wait_send_all_might_not_block", - (), - "wait_send_all_might_not_block", - (), + "wait_send_all_might_not_block", (), "wait_send_all_might_not_block", () ) await do_test("receive_some", (1,), "receive_some", (1,)) @contextmanager def virtual_ssl_echo_server( - client_ctx: SSLContext, - sleeper: Callable[[str], Awaitable[None]] | None = None, + client_ctx: SSLContext, sleeper: Callable[[str], Awaitable[None]] | None = None ) -> Iterator[SSLStream[PyOpenSSLEchoStream]]: fakesock = PyOpenSSLEchoStream(sleeper=sleeper) yield SSLStream(fakesock, client_ctx, server_hostname="trio-test-1.example.org") @@ -417,10 +393,7 @@ def ssl_wrap_pair( # type: ignore[misc] **client_kwargs, ) server_ssl = SSLStream( - server_transport, - SERVER_CTX, - server_side=True, - **server_kwargs, + server_transport, SERVER_CTX, server_side=True, **server_kwargs ) return client_ssl, server_ssl @@ -432,10 +405,7 @@ def ssl_memory_stream_pair( client_ctx: SSLContext, client_kwargs: dict[str, str | bytes | bool | None] | None = None, server_kwargs: dict[str, str | bytes | bool | None] | None = None, -) -> tuple[ - SSLStream[MemoryStapledStream], - SSLStream[MemoryStapledStream], -]: +) -> tuple[SSLStream[MemoryStapledStream], SSLStream[MemoryStapledStream]]: client_transport, server_transport = memory_stream_pair() return ssl_wrap_pair( client_ctx, @@ -453,10 +423,7 @@ def ssl_lockstep_stream_pair( client_ctx: SSLContext, client_kwargs: dict[str, str | bytes | bool | None] | None = None, server_kwargs: dict[str, str | bytes | bool | None] | None = None, -) -> tuple[ - SSLStream[MyStapledStream], - SSLStream[MyStapledStream], -]: +) -> tuple[SSLStream[MyStapledStream], SSLStream[MyStapledStream]]: client_transport, server_transport = lockstep_stream_pair() return ssl_wrap_pair( client_ctx, @@ -501,16 +468,13 @@ async def test_ssl_server_basics(client_ctx: SSLContext) -> None: with a, b: server_sock = tsocket.from_stdlib_socket(b) server_transport = SSLStream( - SocketStream(server_sock), - SERVER_CTX, - server_side=True, + SocketStream(server_sock), SERVER_CTX, server_side=True ) assert server_transport.server_side def client() -> None: with client_ctx.wrap_socket( - a, - server_hostname="trio-test-1.example.org", + a, server_hostname="trio-test-1.example.org" ) as client_sock: client_sock.sendall(b"x") assert client_sock.recv(1) == b"y" @@ -654,8 +618,7 @@ async def test_renegotiation_simple(client_ctx: SSLContext) -> None: @slow async def test_renegotiation_randomized( - mock_clock: MockClock, - client_ctx: SSLContext, + mock_clock: MockClock, client_ctx: SSLContext ) -> None: # The only blocking things in this function are our random sleeps, so 0 is # a good threshold. @@ -761,8 +724,7 @@ async def sleeper_with_slow_wait_writable_and_expect(method: str) -> None: await trio.sleep(1000) with virtual_ssl_echo_server( - client_ctx, - sleeper=sleeper_with_slow_wait_writable_and_expect, + client_ctx, sleeper=sleeper_with_slow_wait_writable_and_expect ) as s: await send(b"x") s.transport_stream.renegotiate() @@ -793,8 +755,7 @@ async def do_wait_send_all_might_not_block(s: S) -> None: await s.wait_send_all_might_not_block() async def do_test( - func1: Callable[[S], Awaitable[None]], - func2: Callable[[S], Awaitable[None]], + func1: Callable[[S], Awaitable[None]], func2: Callable[[S], Awaitable[None]] ) -> None: s, _ = ssl_lockstep_stream_pair(client_ctx) with RaisesGroup(Matcher(_core.BusyResourceError, "another task")): @@ -882,23 +843,20 @@ async def test_send_all_empty_string(client_ctx: SSLContext) -> None: @pytest.mark.parametrize("https_compatible", [False, True]) async def test_SSLStream_generic( - client_ctx: SSLContext, - https_compatible: bool, + client_ctx: SSLContext, https_compatible: bool ) -> None: - async def stream_maker() -> tuple[ - SSLStream[MemoryStapledStream], - SSLStream[MemoryStapledStream], - ]: + async def stream_maker() -> ( + tuple[SSLStream[MemoryStapledStream], SSLStream[MemoryStapledStream]] + ): return ssl_memory_stream_pair( client_ctx, client_kwargs={"https_compatible": https_compatible}, server_kwargs={"https_compatible": https_compatible}, ) - async def clogged_stream_maker() -> tuple[ - SSLStream[MyStapledStream], - SSLStream[MyStapledStream], - ]: + async def clogged_stream_maker() -> ( + tuple[SSLStream[MyStapledStream], SSLStream[MyStapledStream]] + ): client, server = ssl_lockstep_stream_pair(client_ctx) # If we don't do handshakes up front, then we run into a problem in # the following situation: @@ -1065,16 +1023,12 @@ async def test_ssl_over_ssl(client_ctx: SSLContext) -> None: client_0, server_0 = memory_stream_pair() client_1 = SSLStream( - client_0, - client_ctx, - server_hostname="trio-test-1.example.org", + client_0, client_ctx, server_hostname="trio-test-1.example.org" ) server_1 = SSLStream(server_0, SERVER_CTX, server_side=True) client_2 = SSLStream( - client_1, - client_ctx, - server_hostname="trio-test-1.example.org", + client_1, client_ctx, server_hostname="trio-test-1.example.org" ) server_2 = SSLStream(server_1, SERVER_CTX, server_side=True) @@ -1351,16 +1305,12 @@ async def setup( listen_sock.listen(1) socket_listener = SocketListener(listen_sock) ssl_listener = SSLListener( - socket_listener, - SERVER_CTX, - https_compatible=https_compatible, + socket_listener, SERVER_CTX, https_compatible=https_compatible ) transport_client = await open_tcp_stream(*listen_sock.getsockname()) ssl_client = SSLStream( - transport_client, - client_ctx, - server_hostname="trio-test-1.example.org", + transport_client, client_ctx, server_hostname="trio-test-1.example.org" ) return listen_sock, ssl_listener, ssl_client diff --git a/src/trio/_tests/test_subprocess.py b/src/trio/_tests/test_subprocess.py index 88623a430..576befa30 100644 --- a/src/trio/_tests/test_subprocess.py +++ b/src/trio/_tests/test_subprocess.py @@ -11,11 +11,7 @@ from functools import partial from pathlib import Path as SyncPath from signal import Signals -from typing import ( - TYPE_CHECKING, - Any, - NoReturn, -) +from typing import TYPE_CHECKING, Any, NoReturn import pytest @@ -89,10 +85,7 @@ def got_signal(proc: Process, sig: SignalType) -> bool: @asynccontextmanager # type: ignore[misc] # Any in decorated -async def open_process_then_kill( - *args: Any, - **kwargs: Any, -) -> AsyncIterator[Process]: +async def open_process_then_kill(*args: Any, **kwargs: Any) -> AsyncIterator[Process]: proc = await open_process(*args, **kwargs) try: yield proc @@ -102,10 +95,7 @@ async def open_process_then_kill( @asynccontextmanager # type: ignore[misc] # Any in decorated -async def run_process_in_nursery( - *args: Any, - **kwargs: Any, -) -> AsyncIterator[Process]: +async def run_process_in_nursery(*args: Any, **kwargs: Any) -> AsyncIterator[Process]: async with _core.open_nursery() as nursery: kwargs.setdefault("check", False) value = await nursery.start(partial(run_process, *args, **kwargs)) @@ -123,8 +113,7 @@ async def run_process_in_nursery( # Explicit .../"Any" is not allowed BackgroundProcessType: TypeAlias = Callable[ # type: ignore[misc] - ..., - AbstractAsyncContextManager[Process], + ..., AbstractAsyncContextManager[Process] ] @@ -141,8 +130,7 @@ async def test_basic(background_process: BackgroundProcessType) -> None: await proc.wait() assert proc.returncode == 1 assert repr(proc) == "".format( - EXIT_FALSE, - "exited with status 1", + EXIT_FALSE, "exited with status 1" ) @@ -184,7 +172,7 @@ async def test_multi_wait(background_process: BackgroundProcessType) -> None: COPY_STDIN_TO_STDOUT_AND_BACKWARD_TO_STDERR = python( "data = sys.stdin.buffer.read(); " "sys.stdout.buffer.write(data); " - "sys.stderr.buffer.write(data[::-1])", + "sys.stderr.buffer.write(data[::-1])" ) @@ -245,7 +233,7 @@ async def test_interactive(background_process: BackgroundProcessType) -> None: " request = int(line.strip())\n" " print(str(idx * 2) * request)\n" " print(str(idx * 2 + 1) * request * 2, file=sys.stderr)\n" - " idx += 1\n", + " idx += 1\n" ), stdin=subprocess.PIPE, stdout=subprocess.PIPE, @@ -257,9 +245,7 @@ async def expect(idx: int, request: int) -> None: async with _core.open_nursery() as nursery: async def drain_one( - stream: ReceiveStream, - count: int, - digit: int, + stream: ReceiveStream, count: int, digit: int ) -> None: while count > 0: result = await stream.receive_some(count) @@ -304,10 +290,7 @@ async def test_run() -> None: data = bytes(random.randint(0, 255) for _ in range(2**18)) result = await run_process( - CAT, - stdin=data, - capture_stdout=True, - capture_stderr=True, + CAT, stdin=data, capture_stdout=True, capture_stderr=True ) assert result.args == CAT assert result.returncode == 0 @@ -341,18 +324,15 @@ async def test_run() -> None: with pytest.raises(ValueError, match=pipe_stdout_error): await run_process(CAT, stdout=subprocess.PIPE) with pytest.raises( - ValueError, - match=pipe_stdout_error.replace("stdout", "stderr", 1), + ValueError, match=pipe_stdout_error.replace("stdout", "stderr", 1) ): await run_process(CAT, stderr=subprocess.PIPE) with pytest.raises( - ValueError, - match="^can't specify both stdout and capture_stdout$", + ValueError, match="^can't specify both stdout and capture_stdout$" ): await run_process(CAT, capture_stdout=True, stdout=subprocess.DEVNULL) with pytest.raises( - ValueError, - match="^can't specify both stderr and capture_stderr$", + ValueError, match="^can't specify both stderr and capture_stderr$" ): await run_process(CAT, capture_stderr=True, stderr=None) @@ -367,10 +347,7 @@ async def test_run_check() -> None: assert excinfo.value.stdout is None result = await run_process( - cmd, - capture_stdout=True, - capture_stderr=True, - check=False, + cmd, capture_stdout=True, capture_stderr=True, check=False ) assert result.args == cmd assert result.stdout == b"" @@ -381,8 +358,7 @@ async def test_run_check() -> None: @skip_if_fbsd_pipes_broken async def test_run_with_broken_pipe() -> None: result = await run_process( - [sys.executable, "-c", "import sys; sys.stdin.close()"], - stdin=b"x" * 131072, + [sys.executable, "-c", "import sys; sys.stdin.close()"], stdin=b"x" * 131072 ) assert result.returncode == 0 assert result.stdout is result.stderr is None @@ -425,9 +401,7 @@ async def test_stderr_stdout(background_process: BackgroundProcessType) -> None: # this one hits the branch where stderr=STDOUT but stdout # is not redirected async with background_process( - CAT, - stdin=subprocess.PIPE, - stderr=subprocess.STDOUT, + CAT, stdin=subprocess.PIPE, stderr=subprocess.STDOUT ) as proc: assert proc.stdout is None assert proc.stderr is None @@ -475,8 +449,7 @@ async def test_errors() -> None: @background_process_param async def test_signals(background_process: BackgroundProcessType) -> None: async def test_one_signal( - send_it: Callable[[Process], None], - signum: signal.Signals | None, + send_it: Callable[[Process], None], signum: signal.Signals | None ) -> None: with move_on_after(1.0) as scope: async with background_process(SLEEP(3600)) as proc: @@ -581,7 +554,7 @@ async def custom_deliver_cancel(proc: Process) -> None: async with _core.open_nursery() as nursery: nursery.start_soon( - partial(run_process, SLEEP(9999), deliver_cancel=custom_deliver_cancel), + partial(run_process, SLEEP(9999), deliver_cancel=custom_deliver_cancel) ) await wait_all_tasks_blocked() nursery.cancel_scope.cancel() @@ -597,7 +570,7 @@ async def custom_deliver_cancel(proc: Process) -> None: async def do_stuff() -> None: async with _core.open_nursery() as nursery: nursery.start_soon( - partial(run_process, SLEEP(9999), deliver_cancel=custom_deliver_cancel), + partial(run_process, SLEEP(9999), deliver_cancel=custom_deliver_cancel) ) await wait_all_tasks_blocked() nursery.cancel_scope.cancel() @@ -625,8 +598,7 @@ def broken_terminate(self: Process) -> NoReturn: @pytest.mark.skipif(not posix, reason="posix only") async def test_warn_on_cancel_SIGKILL_escalation( - autojump_clock: MockClock, - monkeypatch: pytest.MonkeyPatch, + autojump_clock: MockClock, monkeypatch: pytest.MonkeyPatch ) -> None: monkeypatch.setattr(Process, "terminate", lambda *args: None) diff --git a/src/trio/_tests/test_sync.py b/src/trio/_tests/test_sync.py index 77721226a..33b6ab75d 100644 --- a/src/trio/_tests/test_sync.py +++ b/src/trio/_tests/test_sync.py @@ -250,9 +250,7 @@ def test_Semaphore_bounded() -> None: @pytest.mark.parametrize("lockcls", [Lock, StrictFIFOLock], ids=lambda fn: fn.__name__) -async def test_Lock_and_StrictFIFOLock( - lockcls: type[Lock | StrictFIFOLock], -) -> None: +async def test_Lock_and_StrictFIFOLock(lockcls: type[Lock | StrictFIFOLock]) -> None: l = lockcls() # noqa assert not l.locked() @@ -498,9 +496,7 @@ def release(self) -> None: ] generic_lock_test = pytest.mark.parametrize( - "lock_factory", - lock_factories, - ids=lock_factory_names, + "lock_factory", lock_factories, ids=lock_factory_names ) LockLike: TypeAlias = Union[ @@ -618,7 +614,7 @@ async def test_lock_multiple_acquire() -> None: Matcher( trio.BrokenResourceError, match="^Owner of this lock exited without releasing: ", - ), + ) ): async with trio.open_nursery() as nursery: nursery.start_soon(lock.acquire) @@ -633,11 +629,7 @@ async def test_lock_handover() -> None: # this task acquires the lock lock.acquire_nowait() - assert GLOBAL_PARKING_LOT_BREAKER == { - _core.current_task(): [ - lock._lot, - ], - } + assert GLOBAL_PARKING_LOT_BREAKER == {_core.current_task(): [lock._lot]} async with trio.open_nursery() as nursery: nursery.start_soon(lock.acquire) diff --git a/src/trio/_tests/test_testing.py b/src/trio/_tests/test_testing.py index ab4721376..aba53ef27 100644 --- a/src/trio/_tests/test_testing.py +++ b/src/trio/_tests/test_testing.py @@ -393,9 +393,7 @@ def close_hook() -> None: record.append("close_hook") mss2 = MemorySendStream( - send_all_hook, - wait_send_all_might_not_block_hook, - close_hook, + send_all_hook, wait_send_all_might_not_block_hook, close_hook ) assert mss2.send_all_hook is send_all_hook @@ -604,10 +602,12 @@ async def one_way_stream_maker() -> tuple[MemorySendStream, MemoryReceiveStream] await check_one_way_stream(one_way_stream_maker, None) - async def half_closeable_stream_maker() -> tuple[ - StapledStream[MemorySendStream, MemoryReceiveStream], - StapledStream[MemorySendStream, MemoryReceiveStream], - ]: + async def half_closeable_stream_maker() -> ( + tuple[ + StapledStream[MemorySendStream, MemoryReceiveStream], + StapledStream[MemorySendStream, MemoryReceiveStream], + ] + ): return memory_stream_pair() await check_half_closeable_stream(half_closeable_stream_maker, None) @@ -619,10 +619,12 @@ async def one_way_stream_maker() -> tuple[SendStream, ReceiveStream]: await check_one_way_stream(one_way_stream_maker, one_way_stream_maker) - async def two_way_stream_maker() -> tuple[ - StapledStream[SendStream, ReceiveStream], - StapledStream[SendStream, ReceiveStream], - ]: + async def two_way_stream_maker() -> ( + tuple[ + StapledStream[SendStream, ReceiveStream], + StapledStream[SendStream, ReceiveStream], + ] + ): return lockstep_stream_pair() await check_two_way_stream(two_way_stream_maker, two_way_stream_maker) @@ -672,13 +674,10 @@ async def check(listener: SocketListener) -> None: def test_trio_test() -> None: async def busy_kitchen( - *, - mock_clock: object, - autojump_clock: object, + *, mock_clock: object, autojump_clock: object ) -> None: ... # pragma: no cover with pytest.raises(ValueError, match="^too many clocks spoil the broth!$"): trio_test(busy_kitchen)( - mock_clock=MockClock(), - autojump_clock=MockClock(autojump_threshold=0), + mock_clock=MockClock(), autojump_clock=MockClock(autojump_threshold=0) ) diff --git a/src/trio/_tests/test_testing_raisesgroup.py b/src/trio/_tests/test_testing_raisesgroup.py index 9ab84cd3b..292d38325 100644 --- a/src/trio/_tests/test_testing_raisesgroup.py +++ b/src/trio/_tests/test_testing_raisesgroup.py @@ -21,7 +21,7 @@ def test_raises_group() -> None: with pytest.raises( ValueError, match=wrap_escape( - f'Invalid argument "{TypeError()!r}" must be exception type, Matcher, or RaisesGroup.', + f'Invalid argument "{TypeError()!r}" must be exception type, Matcher, or RaisesGroup.' ), ): RaisesGroup(TypeError()) @@ -45,11 +45,7 @@ def test_raises_group() -> None: with RaisesGroup(RaisesGroup(ValueError)): raise ExceptionGroup("foo", (ExceptionGroup("bar", (ValueError(),)),)) - with RaisesGroup( - SyntaxError, - RaisesGroup(ValueError), - RaisesGroup(RuntimeError), - ): + with RaisesGroup(SyntaxError, RaisesGroup(ValueError), RaisesGroup(RuntimeError)): raise ExceptionGroup( "foo", ( @@ -93,8 +89,7 @@ def test_flatten_subgroups() -> None: raise ExceptionGroup("", (ExceptionGroup("", (ValueError(),)),)) with RaisesGroup(RaisesGroup(ValueError, flatten_subgroups=True)): raise ExceptionGroup( - "", - (ExceptionGroup("", (ExceptionGroup("", (ValueError(),)),)),), + "", (ExceptionGroup("", (ExceptionGroup("", (ValueError(),)),)),) ) with pytest.raises(ExceptionGroup): with RaisesGroup(RaisesGroup(ValueError, flatten_subgroups=True)): @@ -116,8 +111,7 @@ def test_catch_unwrapped_exceptions() -> None: # expecting multiple unwrapped exceptions is not possible with pytest.raises( - ValueError, - match="^You cannot specify multiple exceptions with", + ValueError, match="^You cannot specify multiple exceptions with" ): RaisesGroup(SyntaxError, ValueError, allow_unwrapped=True) # type: ignore[call-overload] # if users want one of several exception types they need to use a Matcher @@ -234,10 +228,7 @@ def test_RaisesGroup_matches() -> None: def test_message() -> None: - def check_message( - message: str, - body: RaisesGroup[BaseException], - ) -> None: + def check_message(message: str, body: RaisesGroup[BaseException]) -> None: with pytest.raises( AssertionError, match=f"^DID NOT RAISE any exception, expected {re.escape(message)}$", @@ -249,8 +240,7 @@ def check_message( check_message("ExceptionGroup(ValueError)", RaisesGroup(ValueError)) # multiple exceptions check_message( - "ExceptionGroup(ValueError, ValueError)", - RaisesGroup(ValueError, ValueError), + "ExceptionGroup(ValueError, ValueError)", RaisesGroup(ValueError, ValueError) ) # nested check_message( @@ -264,14 +254,12 @@ def check_message( RaisesGroup(Matcher(ValueError, "my_str")), ) check_message( - "ExceptionGroup(Matcher(match='my_str'))", - RaisesGroup(Matcher(match="my_str")), + "ExceptionGroup(Matcher(match='my_str'))", RaisesGroup(Matcher(match="my_str")) ) # BaseExceptionGroup check_message( - "BaseExceptionGroup(KeyboardInterrupt)", - RaisesGroup(KeyboardInterrupt), + "BaseExceptionGroup(KeyboardInterrupt)", RaisesGroup(KeyboardInterrupt) ) # BaseExceptionGroup with type inside Matcher check_message( @@ -292,8 +280,7 @@ def check_message( def test_matcher() -> None: with pytest.raises( - ValueError, - match="^You must specify at least one parameter to match on.$", + ValueError, match="^You must specify at least one parameter to match on.$" ): Matcher() # type: ignore[call-overload] with pytest.raises( diff --git a/src/trio/_tests/test_threads.py b/src/trio/_tests/test_threads.py index 75f9142d6..5f29160cb 100644 --- a/src/trio/_tests/test_threads.py +++ b/src/trio/_tests/test_threads.py @@ -8,12 +8,7 @@ import time import weakref from functools import partial -from typing import ( - TYPE_CHECKING, - NoReturn, - TypeVar, - Union, -) +from typing import TYPE_CHECKING, NoReturn, TypeVar, Union import pytest import sniffio @@ -253,11 +248,7 @@ def _get_thread_name(ident: int | None = None) -> str | None: assert pthread_getname_np # thankfully getname signature doesn't differ between platforms - pthread_getname_np.argtypes = [ - ctypes.c_void_p, - ctypes.c_char_p, - ctypes.c_size_t, - ] + pthread_getname_np.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_size_t] pthread_getname_np.restype = ctypes.c_int name_buffer = ctypes.create_string_buffer(b"", size=16) @@ -333,8 +324,7 @@ def g() -> NoReturn: raise ValueError(threading.current_thread()) with pytest.raises( - ValueError, - match=r"^$", + ValueError, match=r"^$" ) as excinfo: await to_thread_run_sync(g) print(excinfo.value.args) @@ -402,8 +392,7 @@ async def child(q: stdlib_queue.Queue[None], abandon_on_cancel: bool) -> None: # handled gracefully. (Requires that the thread result machinery be prepared # for call_soon to raise RunFinishedError.) def test_run_in_worker_thread_abandoned( - capfd: pytest.CaptureFixture[str], - monkeypatch: pytest.MonkeyPatch, + capfd: pytest.CaptureFixture[str], monkeypatch: pytest.MonkeyPatch ) -> None: monkeypatch.setattr(_core._thread_cache, "IDLE_TIMEOUT", 0.01) @@ -443,9 +432,7 @@ async def child() -> None: @pytest.mark.parametrize("cancel", [False, True]) @pytest.mark.parametrize("use_default_limiter", [False, True]) async def test_run_in_worker_thread_limiter( - MAX: int, - cancel: bool, - use_default_limiter: bool, + MAX: int, cancel: bool, use_default_limiter: bool ) -> None: # This test is a bit tricky. The goal is to make sure that if we set # limiter=CapacityLimiter(MAX), then in fact only MAX threads are ever @@ -648,7 +635,7 @@ async def async_fn() -> None: # pragma: no cover trio_test_contextvar: contextvars.ContextVar[str] = contextvars.ContextVar( - "trio_test_contextvar", + "trio_test_contextvar" ) @@ -672,11 +659,7 @@ def g() -> tuple[str, str, threading.Thread]: inner_value = trio_test_contextvar.get() with pytest.raises(sniffio.AsyncLibraryNotFoundError): sniffio.current_async_library() - return ( - parent_value, - inner_value, - threading.current_thread(), - ) + return (parent_value, inner_value, threading.current_thread()) parent_value, inner_value, child_thread = await to_thread_run_sync(g) current_value = trio_test_contextvar.get() @@ -855,8 +838,7 @@ async def async_back_in_main() -> tuple[str, str]: def test_run_fn_as_system_task_catched_badly_typed_token() -> None: with pytest.raises(RuntimeError): from_thread_run_sync( - _core.current_time, - trio_token="Not TrioTokentype", # type: ignore[arg-type] + _core.current_time, trio_token="Not TrioTokentype" # type: ignore[arg-type] ) @@ -880,7 +862,7 @@ async def agen(token: _core.TrioToken | None) -> AsyncGenerator[None, None]: with _core.CancelScope(shield=True): try: await to_thread_run_sync( - partial(from_thread_run, sleep, 0, trio_token=token), + partial(from_thread_run, sleep, 0, trio_token=token) ) except _core.RunFinishedError: record.append("finished") diff --git a/src/trio/_tests/test_timeouts.py b/src/trio/_tests/test_timeouts.py index bad439530..5c9ae4ccc 100644 --- a/src/trio/_tests/test_timeouts.py +++ b/src/trio/_tests/test_timeouts.py @@ -182,14 +182,9 @@ async def test_timeouts_raise_value_error() -> None: nan = float("nan") - for fun, val in ( - (sleep, -1), - (sleep, nan), - (sleep_until, nan), - ): + for fun, val in ((sleep, -1), (sleep, nan), (sleep_until, nan)): with pytest.raises( - ValueError, - match="^(deadline|`seconds`) must (not )*be (non-negative|NaN)$", + ValueError, match="^(deadline|`seconds`) must (not )*be (non-negative|NaN)$" ): await fun(val) @@ -202,8 +197,7 @@ async def test_timeouts_raise_value_error() -> None: (move_on_at, nan), ): with pytest.raises( - ValueError, - match="^(deadline|`seconds`) must (not )*be (non-negative|NaN)$", + ValueError, match="^(deadline|`seconds`) must (not )*be (non-negative|NaN)$" ): with cm(val): pass # pragma: no cover diff --git a/src/trio/_tests/test_unix_pipes.py b/src/trio/_tests/test_unix_pipes.py index c850ebefe..8acd31015 100644 --- a/src/trio/_tests/test_unix_pipes.py +++ b/src/trio/_tests/test_unix_pipes.py @@ -201,8 +201,7 @@ async def expect_closedresourceerror() -> None: orig_wait_readable = _core._run.TheIOManager.wait_readable async def patched_wait_readable( - self: _core._run.TheIOManager, - fd: int | _HasFileNo, + self: _core._run.TheIOManager, fd: int | _HasFileNo ) -> None: await orig_wait_readable(self, fd) await r.aclose() @@ -232,8 +231,7 @@ async def expect_closedresourceerror() -> None: orig_wait_writable = _core._run.TheIOManager.wait_writable async def patched_wait_writable( - self: _core._run.TheIOManager, - fd: int | _HasFileNo, + self: _core._run.TheIOManager, fd: int | _HasFileNo ) -> None: await orig_wait_writable(self, fd) await s.aclose() diff --git a/src/trio/_tests/test_util.py b/src/trio/_tests/test_util.py index 5036d76e5..8006bdbf7 100644 --- a/src/trio/_tests/test_util.py +++ b/src/trio/_tests/test_util.py @@ -235,12 +235,7 @@ def test_fixup_module_metadata() -> None: # We recurse into classes. mod.SomeClass = type( # type: ignore[attr-defined] - "SomeClass", - (), - { - "__init__": lambda self: None, - "method": lambda self: None, - }, + "SomeClass", (), {"__init__": lambda self: None, "method": lambda self: None} ) # Reference loop is fine. mod.SomeClass.recursion = mod.SomeClass # type: ignore[attr-defined] diff --git a/src/trio/_tests/test_wait_for_object.py b/src/trio/_tests/test_wait_for_object.py index 7a3472ba3..eeda3a75e 100644 --- a/src/trio/_tests/test_wait_for_object.py +++ b/src/trio/_tests/test_wait_for_object.py @@ -81,9 +81,7 @@ async def test_WaitForMultipleObjects_sync_slow() -> None: t0 = _core.current_time() async with _core.open_nursery() as nursery: nursery.start_soon( - trio.to_thread.run_sync, - WaitForMultipleObjects_sync, - handle1, + trio.to_thread.run_sync, WaitForMultipleObjects_sync, handle1 ) await _timeouts.sleep(TIMEOUT) # If we would comment the line below, the above thread will be stuck, @@ -100,10 +98,7 @@ async def test_WaitForMultipleObjects_sync_slow() -> None: t0 = _core.current_time() async with _core.open_nursery() as nursery: nursery.start_soon( - trio.to_thread.run_sync, - WaitForMultipleObjects_sync, - handle1, - handle2, + trio.to_thread.run_sync, WaitForMultipleObjects_sync, handle1, handle2 ) await _timeouts.sleep(TIMEOUT) kernel32.SetEvent(handle1) @@ -119,10 +114,7 @@ async def test_WaitForMultipleObjects_sync_slow() -> None: t0 = _core.current_time() async with _core.open_nursery() as nursery: nursery.start_soon( - trio.to_thread.run_sync, - WaitForMultipleObjects_sync, - handle1, - handle2, + trio.to_thread.run_sync, WaitForMultipleObjects_sync, handle1, handle2 ) await _timeouts.sleep(TIMEOUT) kernel32.SetEvent(handle2) diff --git a/src/trio/_tests/tools/test_gen_exports.py b/src/trio/_tests/tools/test_gen_exports.py index 669df968e..d0b1f3697 100644 --- a/src/trio/_tests/tools/test_gen_exports.py +++ b/src/trio/_tests/tools/test_gen_exports.py @@ -92,9 +92,7 @@ def test_create_pass_through_args() -> None: @skip_lints @pytest.mark.parametrize("imports", [IMPORT_1, IMPORT_2, IMPORT_3]) def test_process( - tmp_path: Path, - imports: str, - capsys: pytest.CaptureFixture[str], + tmp_path: Path, imports: str, capsys: pytest.CaptureFixture[str] ) -> None: try: import black # noqa: F401 diff --git a/src/trio/_tests/tools/test_mypy_annotate.py b/src/trio/_tests/tools/test_mypy_annotate.py index 09a57ce74..363c593fd 100644 --- a/src/trio/_tests/tools/test_mypy_annotate.py +++ b/src/trio/_tests/tools/test_mypy_annotate.py @@ -101,9 +101,7 @@ def test_export(capsys: pytest.CaptureFixture[str]) -> None: def test_endtoend( - tmp_path: Path, - monkeypatch: pytest.MonkeyPatch, - capsys: pytest.CaptureFixture[str], + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] ) -> None: import trio._tools.mypy_annotate as mypy_annotate @@ -119,7 +117,7 @@ def test_endtoend( monkeypatch.setattr(sys, "stdin", io.StringIO(inp_text)) mypy_annotate.main( - ["--dumpfile", str(result_file), "--platform", "SomePlatform"], + ["--dumpfile", str(result_file), "--platform", "SomePlatform"] ) std = capsys.readouterr() diff --git a/src/trio/_tests/type_tests/path.py b/src/trio/_tests/type_tests/path.py index 27dbdd2a9..a8b58daba 100644 --- a/src/trio/_tests/type_tests/path.py +++ b/src/trio/_tests/type_tests/path.py @@ -110,8 +110,7 @@ async def async_attrs(path: trio.Path) -> None: assert_type(await path.unlink(missing_ok=True), None) assert_type(await path.write_bytes(b"123"), int) assert_type( - await path.write_text("hello", encoding="utf32le", errors="ignore"), - int, + await path.write_text("hello", encoding="utf32le", errors="ignore"), int ) diff --git a/src/trio/_tests/type_tests/raisesgroup.py b/src/trio/_tests/type_tests/raisesgroup.py index e637ace07..5a1c2ece9 100644 --- a/src/trio/_tests/type_tests/raisesgroup.py +++ b/src/trio/_tests/type_tests/raisesgroup.py @@ -64,8 +64,7 @@ def check_matches_with_different_exception_type() -> None: # This should probably raise some type error somewhere, since # ValueError != KeyboardInterrupt e: BaseExceptionGroup[KeyboardInterrupt] = BaseExceptionGroup( - "", - (KeyboardInterrupt(),), + "", (KeyboardInterrupt(),) ) if RaisesGroup(ValueError).matches(e): assert_type(e, BaseExceptionGroup[ValueError]) @@ -177,10 +176,7 @@ def check_nested_raisesgroups_contextmanager() -> None: # but assert_type reveals the lies print(type(excinfo.value)) # would print "ExceptionGroup" # typing says it's a BaseExceptionGroup - assert_type( - excinfo.value, - BaseExceptionGroup[RaisesGroup[ValueError]], - ) + assert_type(excinfo.value, BaseExceptionGroup[RaisesGroup[ValueError]]) print(type(excinfo.value.exceptions[0])) # would print "ExceptionGroup" # but type checkers are utterly confused @@ -193,8 +189,7 @@ def check_nested_raisesgroups_contextmanager() -> None: def check_nested_raisesgroups_matches() -> None: """Check nested RaisesGroups with .matches""" exc: ExceptionGroup[ExceptionGroup[ValueError]] = ExceptionGroup( - "", - (ExceptionGroup("", (ValueError(),)),), + "", (ExceptionGroup("", (ValueError(),)),) ) # has the same problems as check_nested_raisesgroups_contextmanager if RaisesGroup(RaisesGroup(ValueError)).matches(exc): diff --git a/src/trio/_threads.py b/src/trio/_threads.py index 7afd7b612..eb9d7428d 100644 --- a/src/trio/_threads.py +++ b/src/trio/_threads.py @@ -151,12 +151,10 @@ class Run(Generic[RetT]): # type: ignore[misc] afn: Callable[..., Awaitable[RetT]] # type: ignore[misc] args: tuple[object, ...] context: contextvars.Context = attrs.field( - init=False, - factory=contextvars.copy_context, + init=False, factory=contextvars.copy_context ) queue: stdlib_queue.SimpleQueue[outcome.Outcome[RetT]] = attrs.field( - init=False, - factory=stdlib_queue.SimpleQueue, + init=False, factory=stdlib_queue.SimpleQueue ) @disable_ki_protection @@ -193,13 +191,11 @@ def run_in_system_nursery(self, token: TrioToken) -> None: def in_trio_thread() -> None: try: trio.lowlevel.spawn_system_task( - self.run_system, - name=self.afn, - context=self.context, + self.run_system, name=self.afn, context=self.context ) except RuntimeError: # system nursery is closed self.queue.put_nowait( - outcome.Error(trio.RunFinishedError("system nursery is closed")), + outcome.Error(trio.RunFinishedError("system nursery is closed")) ) token.run_sync_soon(in_trio_thread) @@ -211,12 +207,10 @@ class RunSync(Generic[RetT]): # type: ignore[misc] fn: Callable[..., RetT] # type: ignore[misc] args: tuple[object, ...] context: contextvars.Context = attrs.field( - init=False, - factory=contextvars.copy_context, + init=False, factory=contextvars.copy_context ) queue: stdlib_queue.SimpleQueue[outcome.Outcome[RetT]] = attrs.field( - init=False, - factory=stdlib_queue.SimpleQueue, + init=False, factory=stdlib_queue.SimpleQueue ) @disable_ki_protection @@ -228,7 +222,7 @@ def unprotected_fn(self) -> RetT: ret.close() raise TypeError( "Trio expected a synchronous function, but {!r} appears to be " - "asynchronous".format(getattr(self.fn, "__qualname__", self.fn)), + "asynchronous".format(getattr(self.fn, "__qualname__", self.fn)) ) return ret @@ -394,7 +388,7 @@ def worker_fn() -> RetT: ret.close() raise TypeError( "Trio expected a sync function, but {!r} appears to be " - "asynchronous".format(getattr(sync_fn, "__qualname__", sync_fn)), + "asynchronous".format(getattr(sync_fn, "__qualname__", sync_fn)) ) return ret @@ -449,7 +443,7 @@ def abort(raise_cancel: RaiseCancelT) -> trio.lowlevel.Abort: msg_from_thread.run_sync() else: # pragma: no cover, internal debugging guard TODO: use assert_never raise TypeError( - f"trio.to_thread.run_sync received unrecognized thread message {msg_from_thread!r}.", + f"trio.to_thread.run_sync received unrecognized thread message {msg_from_thread!r}." ) del msg_from_thread @@ -485,15 +479,14 @@ def from_thread_check_cancelled() -> None: raise_cancel = PARENT_TASK_DATA.cancel_register[0] except AttributeError: raise RuntimeError( - "this thread wasn't created by Trio, can't check for cancellation", + "this thread wasn't created by Trio, can't check for cancellation" ) from None if raise_cancel is not None: raise_cancel() def _send_message_to_trio( - trio_token: TrioToken | None, - message_to_trio: Run[RetT] | RunSync[RetT], + trio_token: TrioToken | None, message_to_trio: Run[RetT] | RunSync[RetT] ) -> RetT: """Shared logic of from_thread functions""" token_provided = trio_token is not None @@ -503,7 +496,7 @@ def _send_message_to_trio( trio_token = PARENT_TASK_DATA.token except AttributeError: raise RuntimeError( - "this thread wasn't created by Trio, pass kwarg trio_token=...", + "this thread wasn't created by Trio, pass kwarg trio_token=..." ) from None elif not isinstance(trio_token, TrioToken): raise RuntimeError("Passed kwarg trio_token is not of type TrioToken") @@ -571,9 +564,7 @@ def from_thread_run( # type: ignore[misc] # Explicit "Any" is not allowed def from_thread_run_sync( # type: ignore[misc] - fn: Callable[..., RetT], - *args: object, - trio_token: TrioToken | None = None, + fn: Callable[..., RetT], *args: object, trio_token: TrioToken | None = None ) -> RetT: """Run the given sync function in the parent Trio thread, blocking until it is complete. diff --git a/src/trio/_timeouts.py b/src/trio/_timeouts.py index 7ce123c7c..b35ba5bc4 100644 --- a/src/trio/_timeouts.py +++ b/src/trio/_timeouts.py @@ -28,11 +28,7 @@ def move_on_at(deadline: float, *, shield: bool = False) -> trio.CancelScope: return trio.CancelScope(deadline=deadline, shield=shield) -def move_on_after( - seconds: float, - *, - shield: bool = False, -) -> trio.CancelScope: +def move_on_after(seconds: float, *, shield: bool = False) -> trio.CancelScope: """Use as a context manager to create a cancel scope whose deadline is set to now + *seconds*. @@ -52,10 +48,7 @@ def move_on_after( raise ValueError("`seconds` must be non-negative") if math.isnan(seconds): raise ValueError("`seconds` must not be NaN") - return trio.CancelScope( - shield=shield, - relative_deadline=seconds, - ) + return trio.CancelScope(shield=shield, relative_deadline=seconds) async def sleep_forever() -> NoReturn: @@ -120,9 +113,7 @@ class TooSlowError(Exception): @contextmanager def fail_at( - deadline: float, - *, - shield: bool = False, + deadline: float, *, shield: bool = False ) -> Generator[trio.CancelScope, None, None]: """Creates a cancel scope with the given deadline, and raises an error if it is actually cancelled. @@ -154,9 +145,7 @@ def fail_at( @contextmanager def fail_after( - seconds: float, - *, - shield: bool = False, + seconds: float, *, shield: bool = False ) -> Generator[trio.CancelScope, None, None]: """Creates a cancel scope with the given timeout, and raises an error if it is actually cancelled. diff --git a/src/trio/_tools/gen_exports.py b/src/trio/_tools/gen_exports.py index b4db597b6..784af53cc 100755 --- a/src/trio/_tools/gen_exports.py +++ b/src/trio/_tools/gen_exports.py @@ -215,7 +215,7 @@ def gen_public_wrappers_source(file: File) -> str: if "import sys" not in file.imports: # pragma: no cover header.append("import sys\n") header.append( - f'\nassert not TYPE_CHECKING or sys.platform=="{file.platform}"\n', + f'\nassert not TYPE_CHECKING or sys.platform=="{file.platform}"\n' ) generated = ["".join(header)] @@ -313,13 +313,10 @@ def process(files: Iterable[File], *, do_test: bool) -> None: # doesn't collect coverage. def main() -> None: # pragma: no cover parser = argparse.ArgumentParser( - description="Generate python code for public api wrappers", + description="Generate python code for public api wrappers" ) parser.add_argument( - "--test", - "-t", - action="store_true", - help="test if code is still up to date", + "--test", "-t", action="store_true", help="test if code is still up to date" ) parsed_args = parser.parse_args() diff --git a/src/trio/_tools/mypy_annotate.py b/src/trio/_tools/mypy_annotate.py index 5acb9b993..86047b273 100644 --- a/src/trio/_tools/mypy_annotate.py +++ b/src/trio/_tools/mypy_annotate.py @@ -30,11 +30,7 @@ re.VERBOSE, ) -mypy_to_github = { - "error": "error", - "warn": "warning", - "note": "notice", -} +mypy_to_github = {"error": "error", "warn": "warning", "note": "notice"} @attrs.frozen(kw_only=True) @@ -86,9 +82,7 @@ def main(argv: list[str]) -> None: """Look for error messages, and convert the format.""" parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( - "--dumpfile", - help="File to write pickled messages to.", - required=True, + "--dumpfile", help="File to write pickled messages to.", required=True ) parser.add_argument( "--platform", diff --git a/src/trio/_unix_pipes.py b/src/trio/_unix_pipes.py index a95f761bc..34340d2b3 100644 --- a/src/trio/_unix_pipes.py +++ b/src/trio/_unix_pipes.py @@ -121,10 +121,10 @@ class FdStream(Stream): def __init__(self, fd: int) -> None: self._fd_holder = _FdHolder(fd) self._send_conflict_detector = ConflictDetector( - "another task is using this stream for send", + "another task is using this stream for send" ) self._receive_conflict_detector = ConflictDetector( - "another task is using this stream for receive", + "another task is using this stream for receive" ) async def send_all(self, data: bytes) -> None: @@ -147,7 +147,7 @@ async def send_all(self, data: bytes) -> None: except OSError as e: if e.errno == errno.EBADF: raise trio.ClosedResourceError( - "file was already closed", + "file was already closed" ) from None else: raise trio.BrokenResourceError from e @@ -182,7 +182,7 @@ async def receive_some(self, max_bytes: int | None = None) -> bytes: except OSError as exc: if exc.errno == errno.EBADF: raise trio.ClosedResourceError( - "file was already closed", + "file was already closed" ) from None else: raise trio.BrokenResourceError from exc diff --git a/src/trio/_util.py b/src/trio/_util.py index 994a4655b..9fba3d85b 100644 --- a/src/trio/_util.py +++ b/src/trio/_util.py @@ -7,14 +7,7 @@ from abc import ABCMeta from collections.abc import Awaitable, Callable, Sequence from functools import update_wrapper -from typing import ( - TYPE_CHECKING, - Any, - Generic, - NoReturn, - TypeVar, - final as std_final, -) +from typing import TYPE_CHECKING, Any, Generic, NoReturn, TypeVar, final as std_final from sniffio import thread_local as sniffio_loop @@ -56,8 +49,7 @@ 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], + async_fn: Callable[[Unpack[PosArgsT]], Awaitable[RetT]], *args: Unpack[PosArgsT] ) -> collections.abc.Coroutine[object, NoReturn, RetT]: def _return_value_looks_like_wrong_library(value: object) -> bool: # Returned by legacy @asyncio.coroutine functions, which includes @@ -97,7 +89,7 @@ def _return_value_looks_like_wrong_library(value: object) -> bool: "Instead, you want (notice the parentheses!):\n" "\n" f" trio.run({async_fn.__name__}, ...) # correct!\n" - f" nursery.start_soon({async_fn.__name__}, ...) # correct!", + f" nursery.start_soon({async_fn.__name__}, ...) # correct!" ) from None # Give good error for: nursery.start_soon(future) @@ -106,7 +98,7 @@ def _return_value_looks_like_wrong_library(value: object) -> bool: "Trio was expecting an async function, but instead it got " f"{async_fn!r} – are you trying to use a library written for " "asyncio/twisted/tornado or similar? That won't work " - "without some sort of compatibility shim.", + "without some sort of compatibility shim." ) from None raise @@ -126,19 +118,19 @@ def _return_value_looks_like_wrong_library(value: object) -> bool: raise TypeError( f"Trio got unexpected {coro!r} – are you trying to use a " "library written for asyncio/twisted/tornado or similar? " - "That won't work without some sort of compatibility shim.", + "That won't work without some sort of compatibility shim." ) if inspect.isasyncgen(coro): raise TypeError( "start_soon expected an async function but got an async " - f"generator {coro!r}", + f"generator {coro!r}" ) # Give good error for: nursery.start_soon(some_sync_fn) raise TypeError( "Trio expected an async function, but {!r} appears to be " - "synchronous".format(getattr(async_fn, "__qualname__", async_fn)), + "synchronous".format(getattr(async_fn, "__qualname__", async_fn)) ) return coro @@ -179,9 +171,7 @@ def __exit__( # Explicit "Any" is not allowed def async_wraps( # type: ignore[misc] - cls: type[object], - wrapped_cls: type[object], - attr_name: str, + cls: type[object], wrapped_cls: type[object], attr_name: str ) -> Callable[[CallT], CallT]: """Similar to wraps, but for async wrappers of non-async functions.""" @@ -198,8 +188,7 @@ def decorator(func: CallT) -> CallT: # type: ignore[misc] def fixup_module_metadata( - module_name: str, - namespace: collections.abc.Mapping[str, object], + module_name: str, namespace: collections.abc.Mapping[str, object] ) -> None: seen_ids: set[int] = set() @@ -250,10 +239,7 @@ def open_memory_channel(max_buffer_size: int) -> Tuple[ """ # Explicit .../"Any" is not allowed - def __init__( # type: ignore[misc] - self, - fn: Callable[..., RetT], - ) -> None: + def __init__(self, fn: Callable[..., RetT]) -> None: # type: ignore[misc] update_wrapper(self, fn) self._fn = fn @@ -320,7 +306,7 @@ class SomeClass(metaclass=NoPublicConstructor): def __call__(cls, *args: object, **kwargs: object) -> None: raise TypeError( - f"{cls.__module__}.{cls.__qualname__} has no public constructor", + f"{cls.__module__}.{cls.__qualname__} has no public constructor" ) def _create(cls: type[T], *args: object, **kwargs: object) -> T: diff --git a/src/trio/_windows_pipes.py b/src/trio/_windows_pipes.py index e1eea1e72..43592807b 100644 --- a/src/trio/_windows_pipes.py +++ b/src/trio/_windows_pipes.py @@ -49,7 +49,7 @@ class PipeSendStream(SendStream): def __init__(self, handle: int) -> None: self._handle_holder = _HandleHolder(handle) self._conflict_detector = ConflictDetector( - "another task is currently using this pipe", + "another task is currently using this pipe" ) async def send_all(self, data: bytes) -> None: @@ -93,7 +93,7 @@ class PipeReceiveStream(ReceiveStream): def __init__(self, handle: int) -> None: self._handle_holder = _HandleHolder(handle) self._conflict_detector = ConflictDetector( - "another task is currently using this pipe", + "another task is currently using this pipe" ) async def receive_some(self, max_bytes: int | None = None) -> bytes: @@ -112,13 +112,12 @@ async def receive_some(self, max_bytes: int | None = None) -> bytes: buffer = bytearray(max_bytes) try: size = await _core.readinto_overlapped( - self._handle_holder.handle, - buffer, + self._handle_holder.handle, buffer ) except BrokenPipeError: if self._handle_holder.closed: raise _core.ClosedResourceError( - "another task closed this pipe", + "another task closed this pipe" ) from None # Windows raises BrokenPipeError on one end of a pipe diff --git a/src/trio/socket.py b/src/trio/socket.py index 617f0382c..949601821 100644 --- a/src/trio/socket.py +++ b/src/trio/socket.py @@ -29,7 +29,7 @@ _name: getattr(_stdlib_socket, _name) for _name in _stdlib_socket.__all__ # type: ignore if _name.isupper() and _name not in _bad_symbols - }, + } ) # import the overwrites @@ -77,17 +77,13 @@ # For android devices, if_nameindex support was introduced in API 24, # so it doesn't exist for any version prior. with _suppress(ImportError): - from socket import ( - if_nameindex as if_nameindex, - ) + from socket import if_nameindex as if_nameindex # not always available so expose only if if sys.platform != "win32" or not _t.TYPE_CHECKING: with _suppress(ImportError): - from socket import ( - sethostname as sethostname, - ) + from socket import sethostname as sethostname if _t.TYPE_CHECKING: IP_BIND_ADDRESS_NO_PORT: int diff --git a/src/trio/testing/_check_streams.py b/src/trio/testing/_check_streams.py index e58e2ddfe..74d7f2349 100644 --- a/src/trio/testing/_check_streams.py +++ b/src/trio/testing/_check_streams.py @@ -5,11 +5,7 @@ import sys from collections.abc import Awaitable, Callable, Generator from contextlib import contextmanager, suppress -from typing import ( - TYPE_CHECKING, - Generic, - TypeVar, -) +from typing import TYPE_CHECKING, Generic, TypeVar from .. import CancelScope, _core from .._abc import AsyncResource, HalfCloseableStream, ReceiveStream, SendStream, Stream @@ -54,8 +50,7 @@ async def __aexit__( # on pytest, as the check_* functions are publicly exported. @contextmanager def _assert_raises( - expected_exc: type[BaseException], - wrapped: bool = False, + expected_exc: type[BaseException], wrapped: bool = False ) -> Generator[None, None, None]: __tracebackhide__ = True try: @@ -172,8 +167,7 @@ async def simple_check_wait_send_all_might_not_block( async with _core.open_nursery() as nursery: nursery.start_soon( - simple_check_wait_send_all_might_not_block, - nursery.cancel_scope, + simple_check_wait_send_all_might_not_block, nursery.cancel_scope ) nursery.start_soon(do_receive_some, 1) @@ -344,11 +338,7 @@ async def receiver() -> None: await _core.wait_all_tasks_blocked() nursery.start_soon(receiver) - assert record == [ - "waiter sleeping", - "receiver starting", - "waiter wokeup", - ] + assert record == ["waiter sleeping", "receiver starting", "waiter wokeup"] async with _ForceCloseBoth(await clogged_stream_maker()) as (s, r): # simultaneous wait_send_all_might_not_block fails @@ -466,9 +456,7 @@ async def flipped_clogged_stream_maker() -> tuple[Stream, Stream]: test_data = i.to_bytes(DUPLEX_TEST_SIZE, "little") async def sender( - s: Stream, - data: bytes | bytearray | memoryview, - seed: int, + s: Stream, data: bytes | bytearray | memoryview, seed: int ) -> None: r = random.Random(seed) m = memoryview(data) diff --git a/src/trio/testing/_fake_net.py b/src/trio/testing/_fake_net.py index 2f5bd624a..dfb905e2d 100644 --- a/src/trio/testing/_fake_net.py +++ b/src/trio/testing/_fake_net.py @@ -14,14 +14,7 @@ import os import socket import sys -from typing import ( - TYPE_CHECKING, - Any, - NoReturn, - TypeVar, - Union, - overload, -) +from typing import TYPE_CHECKING, Any, NoReturn, TypeVar, Union, overload import attrs @@ -101,8 +94,7 @@ def as_python_sockaddr(self) -> tuple[str, int] | tuple[str, int, int, int]: @classmethod def from_python_sockaddr( - cls: type[T_UDPEndpoint], - sockaddr: tuple[str, int] | tuple[str, int, int, int], + cls: type[T_UDPEndpoint], sockaddr: tuple[str, int] | tuple[str, int, int, int] ) -> T_UDPEndpoint: ip, port = sockaddr[:2] return cls(ip=ipaddress.ip_address(ip), port=port) @@ -123,9 +115,7 @@ class UDPPacket: # not used/tested anywhere def reply(self, payload: bytes) -> UDPPacket: # pragma: no cover return UDPPacket( - source=self.destination, - destination=self.source, - payload=payload, + source=self.destination, destination=self.source, payload=payload ) @@ -161,9 +151,7 @@ async def getaddrinfo( raise NotImplementedError("FakeNet doesn't do fake DNS yet") async def getnameinfo( - self, - sockaddr: tuple[str, int] | tuple[str, int, int, int], - flags: int, + self, sockaddr: tuple[str, int] | tuple[str, int, int, int], flags: int ) -> tuple[str, str]: raise NotImplementedError("FakeNet doesn't do fake DNS yet") @@ -207,11 +195,7 @@ def deliver_packet(self, packet: UDPPacket) -> None: @final class FakeSocket(trio.socket.SocketType, metaclass=NoPublicConstructor): def __init__( - self, - fake_net: FakeNet, - family: AddressFamily, - type: SocketKind, - proto: int, + self, fake_net: FakeNet, family: AddressFamily, type: SocketKind, proto: int ) -> None: self._fake_net = fake_net @@ -263,10 +247,7 @@ def close(self) -> None: self._packet_receiver.close() async def _resolve_address_nocp( - self, - address: object, - *, - local: bool, + self, address: object, *, local: bool ) -> tuple[str, int]: return await trio._socket._resolve_address_nocp( # type: ignore[no-any-return] self.type, @@ -340,9 +321,7 @@ async def _sendmsg( assert self._binding is not None packet = UDPPacket( - source=self._binding.local, - destination=destination, - payload=payload, + source=self._binding.local, destination=destination, payload=payload ) self._fake_net.send_packet(packet) @@ -355,10 +334,7 @@ async def _sendmsg( sendmsg = _sendmsg async def _recvmsg_into( - self, - buffers: Iterable[Buffer], - ancbufsize: int = 0, - flags: int = 0, + self, buffers: Iterable[Buffer], ancbufsize: int = 0, flags: int = 0 ) -> tuple[ int, list[tuple[int, int, bytes]], @@ -375,7 +351,7 @@ async def _recvmsg_into( raise NotImplementedError( "The code will most likely hang if you try to receive on a fakesocket " "without a binding. If that is not the case, or you explicitly want to " - "test that, remove this warning.", + "test that, remove this warning." ) self._check_closed() @@ -414,13 +390,11 @@ def getpeername(self) -> tuple[str, int] | tuple[str, int, int, int]: self._check_closed() if self._binding is not None: assert hasattr( - self._binding, - "remote", + self._binding, "remote" ), "This method seems to assume that self._binding has a remote UDPEndpoint" if self._binding.remote is not None: # pragma: no cover assert isinstance( - self._binding.remote, - UDPEndpoint, + self._binding.remote, UDPEndpoint ), "Self._binding.remote should be a UDPEndpoint" return self._binding.remote.as_python_sockaddr() _fake_err(errno.ENOTCONN) @@ -432,11 +406,7 @@ def getsockopt(self, /, level: int, optname: int) -> int: ... def getsockopt(self, /, level: int, optname: int, buflen: int) -> bytes: ... def getsockopt( - self, - /, - level: int, - optname: int, - buflen: int | None = None, + self, /, level: int, optname: int, buflen: int | None = None ) -> int | bytes: self._check_closed() raise OSError(f"FakeNet doesn't implement getsockopt({level}, {optname})") @@ -446,12 +416,7 @@ def setsockopt(self, /, level: int, optname: int, value: int | Buffer) -> None: @overload def setsockopt( - self, - /, - level: int, - optname: int, - value: None, - optlen: int, + self, /, level: int, optname: int, value: None, optlen: int ) -> None: ... def setsockopt( @@ -508,10 +473,7 @@ async def sendto( ) -> int: ... # Explicit "Any" is not allowed - async def sendto( # type: ignore[misc] - self, - *args: Any, - ) -> int: + async def sendto(self, *args: Any) -> int: # type: ignore[misc] data: Buffer flags: int address: tuple[object, ...] | str | Buffer @@ -533,39 +495,27 @@ async def recv_into(self, buf: Buffer, nbytes: int = 0, flags: int = 0) -> int: return got_bytes async def recvfrom( - self, - bufsize: int, - flags: int = 0, + self, bufsize: int, flags: int = 0 ) -> tuple[bytes, AddressFormat]: data, _ancdata, _msg_flags, address = await self._recvmsg(bufsize, flags) return data, address async def recvfrom_into( - self, - buf: Buffer, - nbytes: int = 0, - flags: int = 0, + self, buf: Buffer, nbytes: int = 0, flags: int = 0 ) -> tuple[int, AddressFormat]: if nbytes != 0 and nbytes != memoryview(buf).nbytes: raise NotImplementedError("partial recvfrom_into") got_nbytes, _ancdata, _msg_flags, address = await self._recvmsg_into( - [buf], - 0, - flags, + [buf], 0, flags ) return got_nbytes, address async def _recvmsg( - self, - bufsize: int, - ancbufsize: int = 0, - flags: int = 0, + self, bufsize: int, ancbufsize: int = 0, flags: int = 0 ) -> tuple[bytes, list[tuple[int, int, bytes]], int, AddressFormat]: buf = bytearray(bufsize) got_nbytes, ancdata, msg_flags, address = await self._recvmsg_into( - [buf], - ancbufsize, - flags, + [buf], ancbufsize, flags ) return (bytes(buf[:got_nbytes]), ancdata, msg_flags, address) diff --git a/src/trio/testing/_memory_streams.py b/src/trio/testing/_memory_streams.py index 6dd48ebf3..3edce1b0b 100644 --- a/src/trio/testing/_memory_streams.py +++ b/src/trio/testing/_memory_streams.py @@ -30,7 +30,7 @@ def __init__(self) -> None: self._closed = False self._lot = _core.ParkingLot() self._fetch_lock = _util.ConflictDetector( - "another task is already fetching data", + "another task is already fetching data" ) # This object treats "close" as being like closing the send side of a @@ -116,7 +116,7 @@ def __init__( close_hook: SyncHook | None = None, ) -> None: self._conflict_detector = _util.ConflictDetector( - "another task is using this stream", + "another task is using this stream" ) self._outgoing = _UnboundedByteQueue() self.send_all_hook = send_all_hook @@ -226,7 +226,7 @@ def __init__( close_hook: SyncHook | None = None, ) -> None: self._conflict_detector = _util.ConflictDetector( - "another task is using this stream", + "another task is using this stream" ) self._incoming = _UnboundedByteQueue() self._closed = False @@ -358,7 +358,7 @@ async def async_pump_from_send_stream_to_recv_stream() -> None: # noqa: RUF029 def _make_stapled_pair( - one_way_pair: Callable[[], tuple[SendStreamT, ReceiveStreamT]], + one_way_pair: Callable[[], tuple[SendStreamT, ReceiveStreamT]] ) -> tuple[ StapledStream[SendStreamT, ReceiveStreamT], StapledStream[SendStreamT, ReceiveStreamT], @@ -370,10 +370,12 @@ def _make_stapled_pair( return stream1, stream2 -def memory_stream_pair() -> tuple[ - StapledStream[MemorySendStream, MemoryReceiveStream], - StapledStream[MemorySendStream, MemoryReceiveStream], -]: +def memory_stream_pair() -> ( + tuple[ + StapledStream[MemorySendStream, MemoryReceiveStream], + StapledStream[MemorySendStream, MemoryReceiveStream], + ] +): """Create a connected, pure-Python, bidirectional stream with infinite buffering and flexible configuration options. @@ -463,10 +465,10 @@ def __init__(self) -> None: self._receiver_waiting = False self._waiters = _core.ParkingLot() self._send_conflict_detector = _util.ConflictDetector( - "another task is already sending", + "another task is already sending" ) self._receive_conflict_detector = _util.ConflictDetector( - "another task is already receiving", + "another task is already receiving" ) def _something_happened(self) -> None: @@ -609,10 +611,12 @@ def lockstep_stream_one_way_pair() -> tuple[SendStream, ReceiveStream]: return _LockstepSendStream(lbq), _LockstepReceiveStream(lbq) -def lockstep_stream_pair() -> tuple[ - StapledStream[SendStream, ReceiveStream], - StapledStream[SendStream, ReceiveStream], -]: +def lockstep_stream_pair() -> ( + tuple[ + StapledStream[SendStream, ReceiveStream], + StapledStream[SendStream, ReceiveStream], + ] +): """Create a connected, pure-Python, bidirectional stream where data flows in lockstep. diff --git a/src/trio/testing/_raises_group.py b/src/trio/testing/_raises_group.py index 3bb52b4e8..ed71bd6b8 100644 --- a/src/trio/testing/_raises_group.py +++ b/src/trio/testing/_raises_group.py @@ -4,13 +4,7 @@ import sys from contextlib import AbstractContextManager from re import Pattern -from typing import ( - TYPE_CHECKING, - Generic, - Literal, - cast, - overload, -) +from typing import TYPE_CHECKING, Generic, Literal, cast, overload from trio._util import final @@ -26,10 +20,7 @@ from typing_extensions import TypeGuard, TypeVar MatchE = TypeVar( - "MatchE", - bound=BaseException, - default=BaseException, - covariant=True, + "MatchE", bound=BaseException, default=BaseException, covariant=True ) else: from typing import TypeVar @@ -50,14 +41,12 @@ class _ExceptionInfo(Generic[MatchE]): _excinfo: tuple[type[MatchE], MatchE, types.TracebackType] | None def __init__( - self, - excinfo: tuple[type[MatchE], MatchE, types.TracebackType] | None, + self, excinfo: tuple[type[MatchE], MatchE, types.TracebackType] | None ) -> None: self._excinfo = excinfo def fill_unfilled( - self, - exc_info: tuple[type[MatchE], MatchE, types.TracebackType], + self, exc_info: tuple[type[MatchE], MatchE, types.TracebackType] ) -> None: """Fill an unfilled ExceptionInfo created with ``for_later()``.""" assert self._excinfo is None, "ExceptionInfo was already filled" @@ -95,7 +84,7 @@ def tb(self) -> types.TracebackType: def exconly(self, tryshort: bool = False) -> str: raise NotImplementedError( - "This is a helper method only available if you use RaisesGroup with the pytest package installed", + "This is a helper method only available if you use RaisesGroup with the pytest package installed" ) def errisinstance( @@ -103,7 +92,7 @@ def errisinstance( exc: builtins.type[BaseException] | tuple[builtins.type[BaseException], ...], ) -> bool: raise NotImplementedError( - "This is a helper method only available if you use RaisesGroup with the pytest package installed", + "This is a helper method only available if you use RaisesGroup with the pytest package installed" ) def getrepr( @@ -117,7 +106,7 @@ def getrepr( chain: bool = True, ) -> ReprExceptionInfo | ExceptionChainRepr: raise NotImplementedError( - "This is a helper method only available if you use RaisesGroup with the pytest package installed", + "This is a helper method only available if you use RaisesGroup with the pytest package installed" ) @@ -139,10 +128,7 @@ def getrepr( # copied from pytest.ExceptionInfo def _stringify_exception(exc: BaseException) -> str: return "\n".join( - [ - getattr(exc, "message", str(exc)), - *getattr(exc, "__notes__", []), - ], + [getattr(exc, "message", str(exc)), *getattr(exc, "__notes__", [])] ) @@ -198,7 +184,7 @@ def __init__( raise ValueError("You must specify at least one parameter to match on.") if exception_type is not None and not issubclass(exception_type, BaseException): raise ValueError( - f"exception_type {exception_type} must be a subclass of BaseException", + f"exception_type {exception_type} must be a subclass of BaseException" ) self.exception_type = exception_type self.match: Pattern[str] | None @@ -227,13 +213,11 @@ def matches(self, exception: BaseException) -> TypeGuard[MatchE]: """ if self.exception_type is not None and not isinstance( - exception, - self.exception_type, + exception, self.exception_type ): return False if self.match is not None and not re.search( - self.match, - _stringify_exception(exception), + self.match, _stringify_exception(exception) ): return False # If exception_type is None check() accepts BaseException. @@ -247,7 +231,7 @@ def __str__(self) -> str: if (match := self.match) is not None: # If no flags were specified, discard the redundant re.compile() here. reqs.append( - f"match={match.pattern if match.flags == _regex_no_flags else match!r}", + f"match={match.pattern if match.flags == _regex_no_flags else match!r}" ) if self.check is not None: reqs.append(f"check={self.check!r}") @@ -277,8 +261,7 @@ def __str__(self) -> str: @final class RaisesGroup( - AbstractContextManager[ExceptionInfo[BaseExceptionGroup[E]]], - SuperClass[E], + AbstractContextManager[ExceptionInfo[BaseExceptionGroup[E]]], SuperClass[E] ): """Contextmanager for checking for an expected `ExceptionGroup`. This works similar to ``pytest.raises``, and a version of it will hopefully be added upstream, after which this can be deprecated and removed. See https://github.com/pytest-dev/pytest/issues/11538 @@ -401,13 +384,13 @@ def __init__( "You cannot specify multiple exceptions with `allow_unwrapped=True.`" " If you want to match one of multiple possible exceptions you should" " use a `Matcher`." - " E.g. `Matcher(check=lambda e: isinstance(e, (...)))`", + " E.g. `Matcher(check=lambda e: isinstance(e, (...)))`" ) if allow_unwrapped and isinstance(exception, RaisesGroup): raise ValueError( "`allow_unwrapped=True` has no effect when expecting a `RaisesGroup`." " You might want it in the expected `RaisesGroup`, or" - " `flatten_subgroups=True` if you don't care about the structure.", + " `flatten_subgroups=True` if you don't care about the structure." ) if allow_unwrapped and (match is not None or check is not None): raise ValueError( @@ -416,7 +399,7 @@ def __init__( " exception you should use a `Matcher` object. If you want to match/check" " the exceptiongroup when the exception *is* wrapped you need to" " do e.g. `if isinstance(exc.value, ExceptionGroup):" - " assert RaisesGroup(...).matches(exc.value)` afterwards.", + " assert RaisesGroup(...).matches(exc.value)` afterwards." ) # verify `expected_exceptions` and set `self.is_baseexceptiongroup` @@ -427,7 +410,7 @@ def __init__( "You cannot specify a nested structure inside a RaisesGroup with" " `flatten_subgroups=True`. The parameter will flatten subgroups" " in the raised exceptiongroup before matching, which would never" - " match a nested structure.", + " match a nested structure." ) self.is_baseexceptiongroup |= exc.is_baseexceptiongroup elif isinstance(exc, Matcher): @@ -437,15 +420,14 @@ def __init__( continue # Matcher __init__ assures it's a subclass of BaseException self.is_baseexceptiongroup |= not issubclass( - exc.exception_type, - Exception, + exc.exception_type, Exception ) elif isinstance(exc, type) and issubclass(exc, BaseException): self.is_baseexceptiongroup |= not issubclass(exc, Exception) else: raise ValueError( f'Invalid argument "{exc!r}" must be exception type, Matcher, or' - " RaisesGroup.", + " RaisesGroup." ) def __enter__(self) -> ExceptionInfo[BaseExceptionGroup[E]]: @@ -453,8 +435,7 @@ def __enter__(self) -> ExceptionInfo[BaseExceptionGroup[E]]: return self.excinfo def _unroll_exceptions( - self, - exceptions: Sequence[BaseException], + self, exceptions: Sequence[BaseException] ) -> Sequence[BaseException]: """Used if `flatten_subgroups=True`.""" res: list[BaseException] = [] @@ -467,8 +448,7 @@ def _unroll_exceptions( return res def matches( - self, - exc_val: BaseException | None, + self, exc_val: BaseException | None ) -> TypeGuard[BaseExceptionGroup[E]]: """Check if an exception matches the requirements of this RaisesGroup. @@ -498,8 +478,7 @@ def matches( return False if self.match_expr is not None and not re.search( - self.match_expr, - _stringify_exception(exc_val), + self.match_expr, _stringify_exception(exc_val) ): return False if self.check is not None and not self.check(exc_val): diff --git a/src/trio/testing/_sequencer.py b/src/trio/testing/_sequencer.py index 32171cb2a..9c01e902f 100644 --- a/src/trio/testing/_sequencer.py +++ b/src/trio/testing/_sequencer.py @@ -55,8 +55,7 @@ async def main(): """ _sequence_points: defaultdict[int, Event] = attrs.field( - factory=lambda: defaultdict(Event), - init=False, + factory=lambda: defaultdict(Event), init=False ) _claimed: set[int] = attrs.field(factory=set, init=False) _broken: bool = attrs.field(default=False, init=False) @@ -76,7 +75,7 @@ async def __call__(self, position: int) -> AsyncIterator[None]: for event in self._sequence_points.values(): event.set() raise RuntimeError( - "Sequencer wait cancelled -- sequence broken", + "Sequencer wait cancelled -- sequence broken" ) from None else: if self._broken: diff --git a/src/trio/testing/_trio_test.py b/src/trio/testing/_trio_test.py index 226e55919..a57c0ee4c 100644 --- a/src/trio/testing/_trio_test.py +++ b/src/trio/testing/_trio_test.py @@ -42,9 +42,7 @@ def wrapper(*args: ArgsT.args, **kwargs: ArgsT.kwargs) -> RetT: raise ValueError("too many clocks spoil the broth!") instruments = [i for i in kwargs.values() if isinstance(i, Instrument)] return _core.run( - partial(fn, *args, **kwargs), - clock=clock, - instruments=instruments, + partial(fn, *args, **kwargs), clock=clock, instruments=instruments ) return wrapper