-
-
Notifications
You must be signed in to change notification settings - Fork 3.1k
Open
Labels
featuretopic-type-narrowingConditional type narrowing / binderConditional type narrowing / bindertopic-typeguard-typeisTypeGuard / TypeIs / PEP 647 / PEP 742TypeGuard / TypeIs / PEP 647 / PEP 742
Description
Feature
Handle type narrowing when overridden __eq__ method has a return type annotated with TypeIs or TypeGuard.
Pitch
When defining custom __eq__ methods, it might be useful in some contexts to leverage type narrowing. For example, consider an assertion helper1 like the following:
import typing
T = typing.TypeVar("T")
class IsInstance(typing.Generic[T]):
def __init__(self, t: type[T]) -> None:
self.t = t
def __eq__(self, other: typing.Any) -> typing.TypeGuard[T]:
return isinstance(other, self.t)
v: typing.Any = 1
assert v == IsInstance(int)
typing.reveal_type(v) # Should ideally be "int"Currently, mypy doesn't narrow the type. If we explicitly call __eq__, it works as intended:
v: typing.Any = 1
assert IsInstance(int).__eq__(v)
typing.reveal_type(v) # intFootnotes
-
It's admittedly a bit naive for the sake of the example, but we could imagine more complex stuff. ↩
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
featuretopic-type-narrowingConditional type narrowing / binderConditional type narrowing / bindertopic-typeguard-typeisTypeGuard / TypeIs / PEP 647 / PEP 742TypeGuard / TypeIs / PEP 647 / PEP 742