Skip to content

Support type narrowing on __eq__ with TypeGuard/TypeIs #20779

@frankie567

Description

@frankie567

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)  # int

Footnotes

  1. It's admittedly a bit naive for the sake of the example, but we could imagine more complex stuff.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions