python / python/typing

Suggestion: Allow free type variables in type variable bounds that permeate beyond

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

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

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

説明

Suppose we have the following code:

T_co = TypeVar("T_co", covariant=True)

class CanProduce(Protocol[T_co]):
    def produce(self) -> T_co:
        ...

T_in = TypeVar("T_in")
U = TypeVar("U")

@dataclass
class Container(Generic[T_in]):
    value: T_in

    def produce_from_value(self: Container[CanProduce[U]]) -> U:
        return self.value.produce()

This code has an undesirable property: Since T_in is invariant, produce_from_value can only be called on instances of Container whose type parameter is exactly CanProduce[U], for some U:

class IntProducer(CanProduce[int]):
    def produce(self) -> int:
        return 42

c: Container[IntProducer] = Container(IntProducer())
c.produce_from_value()  # this produces a type error

It would be ideal if we could communicate that in this method (which need not be an instance method, it could be a discrete function also), the type parameter behaves as though it were covariant, where any subtype of CanProduce[U] is valid.

In fact, there exists a mechanism for doing this in other situations. Consider if we have the following non-generic protocol:

class SupportsIndex(Protocol):
    def __index__(self) -> int:
        ...

We can then make a method index_from_value that works with all subtypes of SupportsIndex:

SI = TypeVar("SI", bound=SupportsIndex)

@dataclass
class Container(Generic[T_in]):
    value: T_in
    
    def index_from_value(self: Container[SI]):
        return self.value.__index__

Now, the following is valid:

c: Container[int] = Container(27)
c.index_from_value()

Unfortunately, this method cannot be used with generic protocols, because the following is invalid:

U = TypeVar("U")
CPU = TypeVar("CPU", bound=CanProduce[U])  # this produces a type error

I suggest altering the restriction to allow this trick to work.

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

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

はじめの一歩

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

調査の方向性

まず issue にある protocol、Container、TypeVar のジェネリックな例から始め、次に非ジェネリックな SupportsIndex のケースと比較してください。提案されている制約の変更と、サブタイプに対するその挙動が評価できる程度に明確に仕様化されて初めて、issue は対応可能になります。

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

評価

技術スタック
python
領域
devtools
issue の種類
機能追加
難易度
5/5
見積もり時間
1週間以上
活発さ
停滞
明瞭さ
おおむね明確
初心者へのやさしさ
25/100

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

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