python / python/mypy

Generic method in generic class impacting type signature of unrelated method

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

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

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

説明

Bug Report

MyPy's type resolution appears to get impacted by an unrelated generic method when evaluating a method.

To Reproduce

"""Mypy bug: method-level type parameter breaks unrelated method's self type.

mypy --strict mypy-bug-repro.py
mypy 1.19.1, Python 3.13.9
"""

from typing import Protocol, Self


class Read(Protocol):
    def read(self: Self) -> None: ...


class Write(Protocol):
    def write(self: Self) -> None: ...


class CopyFrom(Protocol):
    def copy_from(self: CopyFrom, src: CopyFrom) -> None: ...


class ReadWrite(Read, Write, Protocol):
    pass


class Store[B: Read | Write | CopyFrom]:
    def read(self: Store[Read]) -> None: ...
    def copy_from[T: CopyFrom](self: Store[T], src: Store[T]) -> None: ...


def test(store: Store[ReadWrite]) -> None:
    store.read()  # Error: Invalid self argument

Expected Behavior

Expected mypy to be happy

Actual Behavior

mypy --strict --warn-unreachable --extra-checks returns;

error: Invalid self argument "Store[ReadWrite]" to attribute function "read" with type "Callable[[Store[Read]], None]"  [misc]

Removing Store.copy_from fixes this.
Replacing test def with def test(store: Store[Read]) -> None: fixes this
Replacing Store.copy_from with the following fixes it as well;

type T = CopyFrom
class Store[B: Read | Write | CopyFrom]:
    def read(self: Store[Read]) -> None: ...
    def copy_from(self: Store[T], src: Store[T]) -> None: ...

Your Environment

  • Mypy version used: mypy 1.19.1 (compiled: yes)
  • Mypy command-line flags: --strict --warn-unreachable --extra-checks
  • Mypy configuration options from mypy.ini (and other config files):
[tool.mypy]
plugins = ["pydantic.mypy"]
exclude = ["build-resources"]
  • Python version used: Python 3.13.9

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

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

はじめの一歩

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

調査の方向性

まず、記載された strictness フラグを付けて mypy 1.19.1 で提供された Store[ReadWrite] の再現コードを実行し、次にジェネリックメソッド Store.copy_from が Store.read の self 型にどのような影響を与えるかを追跡します。再現コードで invalid self argument が報告されなくなり、ジェネリックな動作が正しく保たれ、このケースのリグレッションテストが追加されていれば完了です。

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

評価

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

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

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