python / python/typing

Spec: More precision on type parameter order

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

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

topic: documentation topic: typing spec
主要言語
Python
スター
1.8k
フォーク
302
平均マージ
23時間
マージ済み PR(30日)
8

説明

The spec currently isn't very precise on the order in which type parameters appear in a class. (Given a class C that is generic over type parameters T1 and T2, does C[int, str] mean that T1 is bound to int or that T2 is bound to int?)

I think the rule should be:

  • If PEP 695 syntax is used, the order is the order in which the type parameters appear in the type parameter list.
  • If the class has Generic[...] as a syntactic base, the order is the order of the type arguments to Generic.
  • If the class has Protocol[...] as a syntactic base, the order is the order of the type arguments to Protocol. This applies only if Protocol is subscripted, not if the class inherits from bare Protocol.
  • Otherwise, the order is the order in which the type parameters appear syntactically in the base class list.

As far as I know, this is how all type checkers currently behave, but we just found out it's not how the runtime behaves when Protocol is involved: https://github.com/python/cpython/issues/137191#issuecomment-3132748382.

In these examples, all classes are generic over two parameters T1 and T2, and in all cases the type parameter order is T1, T2:

from typing import Generic, Protocol, TypeVar

class C1[T1, T2]: ...  # order is T1, T2

T1 = TypeVar("T1")
T2 = TypeVar("T2")

class C2(C1[T2, T1], Generic[T1, T2]): ...  # order is T1, T2

class GenericProto[T1, T2](Protocol):  ...  # order is T1, T2

class Proto2(GenericProto[T2, T1], Protocol[T1, T2]): ...  # order is T1, T2

class Proto3(GenericProto[T1, T2], Protocol): ...  # order is T1, T2

class C3(C2[T1, T2]): ...  # order is T1, T2

We should change the spec to make this rule explicit. The only current rule appears to be in https://typing.python.org/en/latest/spec/generics.html#arbitrary-generic-types-as-base-classes "Type variables are applied to the defined class in the order in which they first appear in any generic base classes".

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

このリポジトリのコントリビューションガイドは索引されていません

はじめの一歩

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

調査の方向性

generics 仕様の「Arbitrary generic types as base classes」セクションから始め、特に現在の型変数の順序規則を確認してください。その文言を、issue で提案されている PEP 695、Generic、Protocol、基底クラスの各ケースと比較してください。仕様が各ケースの順序を明示的に定義し、示された例と一致すれば完了です。

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

評価

技術スタック
python
領域
documentation
issue の種類
ドキュメント
難易度
2/5
見積もり時間
1〜3時間
活発さ
停滞
明瞭さ
明確に書かれている
初心者へのやさしさ
55/100

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

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