python / python/mypy

Support type narrowing on __eq__ with TypeGuard/TypeIs

Open
#20,779 1 comment 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

feature topic-type-narrowing topic-typeguard-typeis
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

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. 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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.