python / python/mypy

Args with a generic type will use the mother type, rather than a literal

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

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

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

説明

Bug Report
Args with a generic type will use the mother type, rather than a literal

I noticed this issue while trying to chain together two lists with different types with itertools.chain.

To Reproduce

from typing import TypeVar

T = TypeVar('T')

class M:
    pass


class C1(M):
    def my_method(self) -> None:
        pass

class C2(M):
    def my_method(self) -> None:
        pass


def test(*args: T) -> T:
    return args[0]

result = test(C1(), C2())
result.my_method()

https://mypy-play.net/?mypy=latest&python=3.12&flags=strict&gist=d78c6875b87a3040126e1926b8f7ba0c

Expected Behavior
I expected to be able to run my_method, as all arguments have it defined. Instead the mother type is used. This issue can be mitigated by extracting the arguments, giving them a literal type, then unpack them into the function:

my_args: list[C1 | C2] = [C1(), C2()]
test(*my_args)

Actual Behavior

main.py:26: error: "M" has no attribute "my_method"  [attr-defined]

I believe this happens because untyped lists defined with items will use the mother type of all items. I don't think this is very intuitive for args.

Visual Studio Code's Pylance does not give an error in this situation, even with the strict flag.

Your Environment

  • Mypy version used: 1.9.0
  • Mypy command-line flags: no flags
  • Mypy configuration options from mypy.ini (and other config files): no config
  • Python version used: 3.9, 3.10, 3.11, 3.12

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

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

はじめの一歩

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

調査の方向性

まず、報告されている Python と mypy のバージョンで提供された mypy-play の再現コードを実行し、次に test(*args: T) -> T の例におけるジェネリック引数の推論を追跡します。C1C2 を混在させた呼び出しが、中間の型注釈付きリストを必要とせずに my_method を公開する型として推論され、この動作のリグレッションカバレッジが追加されれば完了です。

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

評価

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

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

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