python / python/mypy

Support generic upper bounds

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

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

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

説明

Feature

Allow generic upper bounds such as:

class ClassA[T, S: Sequence[T]]: ...

Pitch

PEP 695 has an example that currently doesn't work, and alludes to a future extension to the typesystem that eliminates the limitation:

# The following generates no compiler error, but a type checker
# should generate an error because an upper bound type must be concrete,
# and ``Sequence[S]`` is generic. Future extensions to the type system may
# eliminate this limitation.
class ClassA[S, T: Sequence[S]]: ...

I ran into a usecase for this that I have no way of expressing with the current generics limitations, and generic upper bounds would solve it. I will provide a simpler version of it here so it's easier to discuss.

from typing import Callable, Iterable, Sequence

type CostFunction[T] = Callable[[T], float]

# Sequence[T] gives an error, because T is not concrete
def get_lowest_cost_sequence[T, S: Sequence[T]](
    seqs: Iterable[S], item_cost: CostFunction[T]
) -> S:
    def seq_cost(seq: S) -> float:
        return sum(item_cost(t) for t in seq)

    return sorted(seqs, key=seq_cost)[0]

In the example, we are working with sequences, and a cost function for each item in the sequences. The crux is that the function must return the same type as the original sequences. In other words this is an incorrect type signature:

# Return type Sequence[T] is looser, because it does not mean whatever is
# returned will be _the same type_ as what is passed in. Any users of this
# function would have to cast the result for it to expose the same functionality
# as what was in `seqs`.
def get_lowest_cost_sequence[T](
    seqs: Iterable[Sequence[T]], item_cost: CostFunction[T]
) -> Sequence[T]:
    ...

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

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

はじめの一歩

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

調査の方向性

実装ファイル、テスト、またはエントリーポイントは指定されていません。まず PEP 695 の type-parameter-scopes セクションとこの Issue の例から始め、次に mypy によるジェネリックな上限の扱いを追跡してください。完了条件は、妥当なジェネリック境界が受け入れられ、無効な非具象境界が引き続き拒否され、リグレッションカバレッジがあることです。

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

評価

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

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

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