python / python/mypy

TypeForm: Recognize type variables in a consistent way

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

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

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

説明

Prerequisite: This issue applies after PR https://github.com/python/mypy/pull/19596 is merged.

Currently mypy sometimes allows a type variable to be assigned to a TypeForm variable and sometimes it does not. This is a problem because the behavior is inconsistent.

Specifically, mypy allows a type variable to be assigned to a TypeForm variable iff it is in a quoted type expression:

[case testTypeVarTypeFormsAreOnlyRecognizedInStringAnnotation]
...
E = TypeVar('E')
class Box(Generic[E]):
    def foo(self, e: E) -> None:
        list_of_typx: List[TypeForm] = [E]  # E: "E" is a type variable and only valid in type context
        typx1: TypeForm = E  # E: "E" is a type variable and only valid in type context
        typx2: TypeForm = 'E'

When a type variable is NOT quoted, mypy will not allow it to be assigned:

[case testEveryKindOfTypeExpressionIsAssignableToATypeFormVariable]
SomeTypeVar = TypeVar('SomeTypeVar')
typx: TypeForm
...
# NOTE: Unbound TypeVar isn't currently accepted as a TypeForm. Is that OK?
typx = SomeTypeVar  # E: Incompatible types in assignment (expression has type "TypeVar", variable has type "TypeForm[Any]")

I'd argue that TypeForm should always accept a type variable because it is a valid type expression and TypeForms are intended to accept all kinds of type expressions:

def cast[T](type_expr: TypeForm[T], value_expr: object) -> T: ...

cast(SomeTypeVar, some_expression)  # should not be an error

In summary:

  • mypy should allow a type variable to be assigned to a TypeForm variable, regardless of whether it is quoted or not. Update above-referenced tests to reflect this new behavior.

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

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

はじめの一歩

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

調査の方向性

まず前提となる PR #19596 を確認し、次に testTypeVarTypeFormsAreOnlyRecognizedInStringAnnotation と testEveryKindOfTypeExpressionIsAssignableToATypeFormVariable という名前のテストを見つけてください。TypeForm の代入で、引用符付きおよび引用符なしの型変数がどのように扱われるかを確認してください。両方のケースで一貫して型変数が許可され、テストが新しい動作を反映していれば完了です。

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

評価

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

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

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