python / python/mypy

Support type narrowing on __eq__ with TypeGuard/TypeIs

オープン
#20,779 コメント 1 件 リアクション 1 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

feature topic-type-narrowing topic-typeguard-typeis
主要言語
Python
スター
20.6k
フォーク
3.3k
PR マージ指標
PR 指標を取得中

説明

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.

コントリビューションガイド

コントリビューションガイドを開く

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

調査の方向性

比較に対する型の絞り込みロジックと、TypeGuard および TypeIs の戻り値アノテーションの処理をまず特定します。issue の IsInstance の例を使って動作を確認します。assert v == IsInstance(int) の後で、reveal_type(v) は明示的な eq の呼び出しと一致して int を報告するはずです。

索引モデルが issue の本文から書いたものです。

評価

技術スタック
python
領域
compilers
issue の種類
機能追加
難易度
4/5
見積もり時間
3〜5日
活発さ
停滞
明瞭さ
おおむね明確
初心者へのやさしさ
45/100

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。