python / python/mypy

Subclass attribute type narrowing on assignment

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

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

documentation
主要言語
Python
スター
20.6k
フォーク
3.3k
平均マージ
1日 18時間
マージ済み PR(30日)
54

説明

Documentation

Consider this code snippet:

from typing import Iterable


class A:
    attr1: Iterable[str]  # narrows to different type, specific number of elements.
    attr2: tuple[str, ...]  # narrows to specific number of elements



class B(A):
    attr1 = "a", "b"
    attr2 = "a", "b", "c"


reveal_type(B.attr1)
reveal_type(B.attr2)

With this, mypy will tell us that Revealed type is "Tuple[builtins.str, builtins.str]" and Revealed type is "Tuple[builtins.str, builtins.str, builtins.str]" for attr1 and attr2 respectively. I can't find this behaviour documented, neither in PEP484, nor the Python typing docs, nor mypy docs. I don't even know where this should be documented best. But for what it's worth, I asked pylance, which says Type of "B.attr1" is "tuple[str, ...]" and Type of "B.attr2" is "tuple[str, ...]". Which tells me that the intended behaviour isn't clear for other people, too.

Note: I'm aware that this may be a bug report instead. But I rather err on the side of this not being clearly specified yet than being incorrectly implemented.

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

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

はじめの一歩

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

調査の方向性

まず、示されているサブクラスの代入について、PEP 484、Python の typing ドキュメント、mypy のドキュメントを読んでください。mypy が明らかにした型と Pylance のレポートを比較し、そのうえで意図された動作を文書化するか、その相違をバグとして扱うべきかどうかを明確にしてください。

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

評価

技術スタック
python
領域
documentation
issue の種類
ドキュメント
難易度
4/5
見積もり時間
3〜5日
活発さ
停滞
明瞭さ
説明が足りない
初心者へのやさしさ
35/100

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

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