Skip to content

Enable mypy's disallow_any_explicit flag. #3121

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 33 commits into from
Nov 3, 2024
Merged
Show file tree
Hide file tree
Changes from 15 commits
Commits
Show all changes
33 commits
Select commit Hold shift + click to select a range
6e91b75
Enable mypy's `disallow_any_explicit` flag.
CoolCat467 Oct 27, 2024
feeccf1
Fix various things after reviewing all changes
CoolCat467 Oct 27, 2024
569bc37
Do not use faster mypy cache on pypy
CoolCat467 Oct 27, 2024
deb1c13
Merge remote-tracking branch 'origin/main' into enable-disallow_any_e…
CoolCat467 Oct 27, 2024
521c1b7
Try to get rid of more `Any`s
CoolCat467 Oct 27, 2024
55964ad
Get rid of a bunch more `Any`s and resolve mypy issues
CoolCat467 Oct 28, 2024
e888514
Match other TypeVarTuple usage
CoolCat467 Oct 28, 2024
30db0d8
Mark variable as nonlocal
CoolCat467 Oct 28, 2024
7707361
Cast asyncio run in loop to be InHost
CoolCat467 Oct 28, 2024
e99b69f
Handle case where `names` does not exist in node for some reason
CoolCat467 Oct 28, 2024
aee4a77
Hopefully fix jedi issue
CoolCat467 Oct 28, 2024
e157589
Check the hashes are the same
A5rocks Oct 28, 2024
62f89fa
Get the hash glob makes
A5rocks Oct 28, 2024
ca48ef6
Fix inputs to glob.hashFiles
A5rocks Oct 28, 2024
28b4abc
Remove testing hashes
A5rocks Oct 28, 2024
a1e4916
Apply requested changes from code review
CoolCat467 Oct 28, 2024
c3c0a28
Code review suggestions
CoolCat467 Oct 28, 2024
63353f4
Fix type issue
CoolCat467 Oct 28, 2024
69e60a5
Fix cffi type issues again
CoolCat467 Oct 28, 2024
25ecf1e
Merge branch 'main' into enable-disallow_any_explicit
CoolCat467 Oct 28, 2024
2bc0da3
Use correct `CData`
CoolCat467 Oct 28, 2024
0f999b8
Fix cast again
CoolCat467 Oct 28, 2024
50adccb
Clarify comments and get rid of more `Any`s
CoolCat467 Oct 30, 2024
3a320c3
Update src/trio/_tests/test_socket.py
CoolCat467 Oct 30, 2024
03f1c4e
Apply suggestions from code review
CoolCat467 Oct 30, 2024
33f1caa
Apply suggestions from code review
CoolCat467 Oct 30, 2024
854c5cd
Update src/trio/_threads.py
CoolCat467 Oct 30, 2024
bcd3f54
Improve type annotations
CoolCat467 Oct 30, 2024
7e719a8
Merge branch 'main' into enable-disallow_any_explicit
CoolCat467 Oct 30, 2024
ee0322a
Forgot `type` and fix more type issues
CoolCat467 Oct 30, 2024
9005f98
Add typing to `orig_getaddrinfo`
CoolCat467 Oct 30, 2024
c480449
Add full typing for `_responses` and `record`
CoolCat467 Oct 30, 2024
ba24f74
Fix type issues
CoolCat467 Oct 30, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,7 @@ warn_return_any = true

# Avoid subtle backsliding
disallow_any_decorated = true
disallow_any_explicit = true
disallow_any_generics = true
disallow_any_unimported = true
disallow_incomplete_defs = true
Expand Down
10 changes: 7 additions & 3 deletions src/trio/_core/_concat_tb.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from __future__ import annotations

from types import TracebackType
from typing import Any, ClassVar, cast
from typing import TYPE_CHECKING, ClassVar, cast

################################################################
# concat_tb
Expand Down Expand Up @@ -86,7 +86,9 @@
def copy_tb(base_tb: TracebackType, tb_next: TracebackType | None) -> TracebackType:
# tputil.ProxyOperation is PyPy-only, and there's no way to specify
# cpython/pypy in current type checkers.
def controller(operation: tputil.ProxyOperation) -> Any | None: # type: ignore[no-any-unimported]
def controller( # type: ignore[no-any-unimported]

Check warning on line 89 in src/trio/_core/_concat_tb.py

View check run for this annotation

Codecov / codecov/patch

src/trio/_core/_concat_tb.py#L89

Added line #L89 was not covered by tests
operation: tputil.ProxyOperation,
) -> TracebackType | None:
# Rationale for pragma: I looked fairly carefully and tried a few
# things, and AFAICT it's not actually possible to get any
# 'opname' that isn't __getattr__ or __getattribute__. So there's
Expand All @@ -99,8 +101,10 @@
"__getattr__",
}
and operation.args[0] == "tb_next"
): # pragma: no cover
) or TYPE_CHECKING: # pragma: no cover
return tb_next
if TYPE_CHECKING:
raise RuntimeError("Should not be possible")
return operation.delegate() # Delegate is reverting to original behaviour

return cast(
Expand Down
3 changes: 2 additions & 1 deletion src/trio/_core/_entry_queue.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@

PosArgsT = TypeVarTuple("PosArgsT")

Function = Callable[..., object]
# Explicit "Any" is not allowed
Function = Callable[..., object] # type: ignore[misc]
Job = tuple[Function, tuple[object, ...]]


Expand Down
14 changes: 10 additions & 4 deletions src/trio/_core/_instrumentation.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,22 @@
import logging
import types
from collections.abc import Callable, Sequence
from typing import Any, TypeVar
from typing import TypeVar

from .._abc import Instrument

# Used to log exceptions in instruments
INSTRUMENT_LOGGER = logging.getLogger("trio.abc.Instrument")


F = TypeVar("F", bound=Callable[..., Any])
# Explicit "Any" is not allowed
F = TypeVar("F", bound=Callable[..., object]) # type: ignore[misc]


# Decorator to mark methods public. This does nothing by itself, but
# trio/_tools/gen_exports.py looks for it.
def _public(fn: F) -> F:
# Explicit "Any" is not allowed
def _public(fn: F) -> F: # type: ignore[misc]
return fn


Expand Down Expand Up @@ -89,7 +91,11 @@ def remove_instrument(self, instrument: Instrument) -> None:
if not instruments:
del self[hookname]

def call(self, hookname: str, *args: Any) -> 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
Expand Down
8 changes: 5 additions & 3 deletions src/trio/_core/_io_windows.py
Original file line number Diff line number Diff line change
Expand Up @@ -253,9 +253,10 @@ class AFDWaiters:
# object, because we need to keep all these objects alive until the operation
# finishes, even if we're throwing it away.
@attrs.frozen(eq=False)
class AFDPollOp:
# Explicit "Any" is not allowed
class AFDPollOp: # type: ignore[misc]
lpOverlapped: CData
poll_info: Any
poll_info: Any # type: ignore[misc]
waiters: AFDWaiters
afd_group: AFDGroup

Expand Down Expand Up @@ -684,7 +685,8 @@ def _refresh_afd(self, base_handle: Handle) -> None:

lpOverlapped = ffi.new("LPOVERLAPPED")

poll_info: Any = ffi.new("AFD_POLL_INFO *")
# Explicit "Any" is not allowed
poll_info: Any = ffi.new("AFD_POLL_INFO *") # type: ignore[misc]
poll_info.Timeout = 2**63 - 1 # INT64_MAX
poll_info.NumberOfHandles = 1
poll_info.Exclusive = 0
Expand Down
8 changes: 7 additions & 1 deletion src/trio/_core/_ki.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,13 @@ class _IdRef(weakref.ref[_T]):
__slots__ = ("_hash",)
_hash: int

def __new__(cls, ob: _T, callback: Callable[[Self], Any] | None = None, /) -> Self:
# Explicit "Any" is not allowed
def __new__( # type: ignore[misc]
cls,
ob: _T,
callback: Callable[[Self], Any] | None = None,
/,
) -> Self:
self: Self = weakref.ref.__new__(cls, ob, callback)
self._hash = object.__hash__(ob)
return self
Expand Down
74 changes: 43 additions & 31 deletions src/trio/_core/_run.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,14 +82,13 @@
StatusT = TypeVar("StatusT")
StatusT_contra = TypeVar("StatusT_contra", contravariant=True)

FnT = TypeVar("FnT", bound="Callable[..., Any]")
RetT = TypeVar("RetT")


DEADLINE_HEAP_MIN_PRUNE_THRESHOLD: Final = 1000

# Passed as a sentinel
_NO_SEND: Final[Outcome[Any]] = cast("Outcome[Any]", object())
_NO_SEND: Final[Outcome[object]] = cast("Outcome[object]", object())

# Used to track if an exceptiongroup can be collapsed
NONSTRICT_EXCEPTIONGROUP_NOTE = 'This is a "loose" ExceptionGroup, and may be collapsed by Trio if it only contains one exception - typically after `Cancelled` has been stripped from it. Note this has consequences for exception handling, and strict_exception_groups=True is recommended.'
Expand All @@ -102,7 +101,7 @@ class _NoStatus(metaclass=NoPublicConstructor):

# Decorator to mark methods public. This does nothing by itself, but
# trio/_tools/gen_exports.py looks for it.
def _public(fn: FnT) -> FnT:
def _public(fn: RetT) -> RetT:
return fn


Expand Down Expand Up @@ -1172,7 +1171,11 @@ 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[Any]) -> None:
def _child_finished(
self,
task: Task,
outcome: Outcome[object],
) -> None:
self._children.remove(task)
if isinstance(outcome, Error):
self._add_exc(outcome.error)
Expand Down Expand Up @@ -1278,12 +1281,13 @@ def start_soon(
"""
GLOBAL_RUN_CONTEXT.runner.spawn_impl(async_fn, args, self, name)

async def start(
# Explicit "Any" is not allowed
async def start( # type: ignore[misc]
self,
async_fn: Callable[..., Awaitable[object]],
*args: object,
name: object = None,
) -> Any:
) -> Any | None:
r"""Creates and initializes a child task.

Like :meth:`start_soon`, but blocks until the new task has
Expand Down Expand Up @@ -1334,7 +1338,10 @@ async def async_fn(arg1, arg2, *, task_status=trio.TASK_STATUS_IGNORED):
# set strict_exception_groups = True to make sure we always unwrap
# *this* nursery's exceptiongroup
async with open_nursery(strict_exception_groups=True) as old_nursery:
task_status: _TaskStatus[Any] = _TaskStatus(old_nursery, self)
task_status: _TaskStatus[object | None] = _TaskStatus(
old_nursery,
self,
)
thunk = functools.partial(async_fn, task_status=task_status)
task = GLOBAL_RUN_CONTEXT.runner.spawn_impl(
thunk,
Expand Down Expand Up @@ -1375,9 +1382,10 @@ def __del__(self) -> None:

@final
@attrs.define(eq=False, repr=False)
class Task(metaclass=NoPublicConstructor):
class Task(metaclass=NoPublicConstructor): # type: ignore[misc]
_parent_nursery: Nursery | None
coro: Coroutine[Any, Outcome[object], Any]
# Explicit "Any" is not allowed
coro: Coroutine[Any, Outcome[object], Any] # type: ignore[misc]
_runner: Runner
name: str
context: contextvars.Context
Expand All @@ -1395,10 +1403,11 @@ class Task(metaclass=NoPublicConstructor):
# tracebacks with extraneous frames.
# - for scheduled tasks, custom_sleep_data is None
# Tasks start out unscheduled.
_next_send_fn: Callable[[Any], object] | None = None
_next_send: Outcome[Any] | None | BaseException = None
# Explicit "Any" is not allowed
_next_send_fn: Callable[[Any], object] | None = None # type: ignore[misc]
_next_send: Outcome[Any] | None | BaseException = None # type: ignore[misc]
_abort_func: Callable[[_core.RaiseCancelT], Abort] | None = None
custom_sleep_data: Any = None
custom_sleep_data: Any = None # type: ignore[misc]

# For introspection and nursery.start()
_child_nurseries: list[Nursery] = attrs.Factory(list)
Expand Down Expand Up @@ -1466,7 +1475,8 @@ def print_stack_for_task(task):

"""
# Ignore static typing as we're doing lots of dynamic introspection
coro: Any = self.coro
# Explicit "Any" is not allowed
coro: Any = self.coro # type: ignore[misc]
while coro is not None:
if hasattr(coro, "cr_frame"):
# A real coroutine
Expand Down Expand Up @@ -1611,13 +1621,16 @@ class RunStatistics:


@attrs.define(eq=False)
class GuestState:
# Explicit "Any" is not allowed
class GuestState: # type: ignore[misc]
runner: Runner
run_sync_soon_threadsafe: Callable[[Callable[[], object]], object]
run_sync_soon_not_threadsafe: Callable[[Callable[[], object]], object]
done_callback: Callable[[Outcome[Any]], object]
# Explicit "Any" is not allowed
done_callback: Callable[[Outcome[Any]], object] # type: ignore[misc]
unrolled_run_gen: Generator[float, EventResult, None]
unrolled_run_next_send: Outcome[Any] = attrs.Factory(lambda: Value(None))
# Explicit "Any" is not allowed
unrolled_run_next_send: Outcome[Any] = attrs.Factory(lambda: Value(None)) # type: ignore[misc]

def guest_tick(self) -> None:
prev_library, sniffio_library.name = sniffio_library.name, "trio"
Expand Down Expand Up @@ -1662,15 +1675,17 @@ def in_main_thread() -> None:


@attrs.define(eq=False)
class Runner:
# Explicit "Any" is not allowed
class Runner: # type: ignore[misc]
clock: Clock
instruments: Instruments
io_manager: TheIOManager
ki_manager: KIManager
strict_exception_groups: bool

# Run-local values, see _local.py
_locals: dict[_core.RunVar[Any], Any] = attrs.Factory(dict)
# Explicit "Any" is not allowed
_locals: dict[_core.RunVar[Any], object] = attrs.Factory(dict) # type: ignore[misc]

runq: deque[Task] = attrs.Factory(deque)
tasks: set[Task] = attrs.Factory(set)
Expand All @@ -1681,7 +1696,7 @@ class Runner:
system_nursery: Nursery | None = None
system_context: contextvars.Context = attrs.field(kw_only=True)
main_task: Task | None = None
main_task_outcome: Outcome[Any] | None = None
main_task_outcome: Outcome[object] | None = None

entry_queue: EntryQueue = attrs.Factory(EntryQueue)
trio_token: TrioToken | None = None
Expand Down Expand Up @@ -1774,11 +1789,7 @@ def current_root_task(self) -> Task | None:
################

@_public
def reschedule(
self,
task: Task,
next_send: Outcome[object] = _NO_SEND,
) -> None:
def reschedule(self, task: Task, next_send: Outcome[object] = _NO_SEND) -> None:
"""Reschedule the given task with the given
:class:`outcome.Outcome`.

Expand Down Expand Up @@ -1889,7 +1900,7 @@ async def python_wrapper(orig_coro: Awaitable[RetT]) -> RetT:
self.reschedule(task, None) # type: ignore[arg-type]
return task

def task_exited(self, task: Task, outcome: Outcome[Any]) -> None:
def task_exited(self, task: Task, outcome: Outcome[object]) -> None:
# break parking lots associated with the exiting task
if task in GLOBAL_PARKING_LOT_BREAKER:
for lot in GLOBAL_PARKING_LOT_BREAKER[task]:
Expand Down Expand Up @@ -2101,7 +2112,8 @@ def _deliver_ki_cb(self) -> None:

# sortedcontainers doesn't have types, and is reportedly very hard to type:
# https://github.com/grantjenks/python-sortedcontainers/issues/68
waiting_for_idle: Any = attrs.Factory(SortedDict)
# Explicit "Any" is not allowed
waiting_for_idle: Any = attrs.Factory(SortedDict) # type: ignore[misc]

@_public
async def wait_all_tasks_blocked(self, cushion: float = 0.0) -> None:
Expand Down Expand Up @@ -2402,7 +2414,7 @@ def run(
raise AssertionError(runner.main_task_outcome)


def start_guest_run(
def start_guest_run( # type: ignore[misc]
async_fn: Callable[..., Awaitable[RetT]],
*args: object,
run_sync_soon_threadsafe: Callable[[Callable[[], object]], object],
Expand Down Expand Up @@ -2706,7 +2718,7 @@ def unrolled_run(
next_send_fn = task._next_send_fn
next_send = task._next_send
task._next_send_fn = task._next_send = None
final_outcome: Outcome[Any] | None = None
final_outcome: Outcome[object] | None = None
try:
# We used to unwrap the Outcome object here and send/throw
# its contents in directly, but it turns out that .throw()
Expand Down Expand Up @@ -2815,15 +2827,15 @@ def unrolled_run(
################################################################


class _TaskStatusIgnored(TaskStatus[Any]):
class _TaskStatusIgnored(TaskStatus[object]):
def __repr__(self) -> str:
return "TASK_STATUS_IGNORED"

def started(self, value: Any = None) -> None:
def started(self, value: object = None) -> None:
pass


TASK_STATUS_IGNORED: Final[TaskStatus[Any]] = _TaskStatusIgnored()
TASK_STATUS_IGNORED: Final[TaskStatus[object]] = _TaskStatusIgnored()


def current_task() -> Task:
Expand Down
Loading
Loading