Support type narrowing on __eq__ with TypeGuard/TypeIs
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
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 helper[^1] 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) # int
[^1]: It's admittedly a bit naive for the sake of the example, but we could imagine more complex stuff.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by locating the type-narrowing logic for comparisons and its handling of TypeGuard and TypeIs return annotations. Verify the behavior using the issue's IsInstance example: after assert v == IsInstance(int), reveal_type(v) should report int, matching the explicit eq call.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- compilers
- Issue type
- Feature
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 45/100