python / python/mypy

Type confusion with protocol attributes when explicitly subclassing protocol

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

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

bug topic-inheritance topic-protocols
主要言語
Python
スター
20.6k
フォーク
3.3k
PR マージ指標
PR 指標を取得中

説明

Bug Report

When type hinting an attribute on a protocol, and then explicitly subclassing the protocol in a class and performing assignment on the attribute, mypy appears to lose the type information on the attribute. In one case, mypy determines the type is whatever can be inferred from the assignment, and in another case, mypy cannot determine the type.

I've looked at Python's documentation for explicitly subclassing a Protocol (docs) as well as the documentation in mypy for Protocols (docs) and I believe this should work.

To Reproduce

Case 1: Incompatible types in assignment

from typing import Protocol


class InventoryItemProtocol(Protocol):
    val: int | None


class InventoryItemMixin(InventoryItemProtocol):
    def set(self) -> None:
        self.val = 1


class InventoryItem(InventoryItemMixin):
    def __init__(self) -> None:
        self.val: int | None = None

Case 2: Cannot determine type

from typing import Protocol


class ValProtocol(Protocol):
    val: int | None


class Runner(ValProtocol):
    def run(self) -> None:
        if not self.val:
            raise ValueError

        self.val = 1

Expected Behavior

Both programs pass type checks.

Actual Behavior

Case 1

sandbox_protocol1.py:15: error: Incompatible types in assignment (expression has type "int | None", base class "InventoryItemMixin" defined the type as "int")  [assignment]
Found 1 error in 1 file (checked 1 source file)

Case 2

sandbox_protocol2.py:10: error: Cannot determine type of "val"  [has-type]
Found 1 error in 1 file (checked 1 source file)

Your Environment

mypy --version
mypy 1.17.1 (compiled: yes)

python --version
Python 3.12.2

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

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

はじめの一歩

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

調査の方向性

まず、issue にある 2 つの Protocol の例を mypy 1.17.1 で実行し、エラーを期待される動作と比較します。明示的にサブクラス化された Protocol 属性がどのように推論され、検証されるかを追跡します。完了条件は、宣言された属性の型を失わずに、両方の例が型チェックを通過することです。

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

評価

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

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

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