python / python/typing

Support for alternative generic inference algorithms

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

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

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

説明

I believe there is a use case for generic inference that doesn't get as wide as possible.

Look at this example of an assertion function, you would never want to do an assertion between two different types, but there is currently no way to type this:

from typing import TypeVar

T = TypeVar("T")

def assert_something(expected: T, actual: T) -> None:
    ...

assert_something(1, "")  # no error, SUS alert!, T is inferred as `object`

Here are some behaviors from other languages

TypeScript

In Typescript generic inference is narrowed to type level types(not down to instance level types) and is never widened:

function assertSomething<T>(expected: T, actual: T): void { ... }

assertSomething(1, "")  // Argument of type 'string' is not assignable to parameter of type 'number'.
Kotlin

Kotlin by default acts the same as Python, but there are annotations for changing the behavior of inference.

NoInfer will exclude that usage from inferring the type.

fun <T> assertSomething(expected: T, actual: @NoInfer T) { }
assertSomething(1, "")  // Type mismatch: inferred type is String but Int was expected

Exact will require the type of the parameter is equal at a type level (Number != Int)

fun <T> foo(x: @Exact T) { }
foo<Number>(1) // Type mismatch. Required: Number, Found: Int

OnlyInputTypes will require a type annotation if there is any difference in types between the usages of the generic:

fun <@OnlyInputTypes T> doSomething(a: T, b: T)  { }

val a = doSomething("a", "b")
val b = doSomething("a", 1) // Type inference failed. The value of the type parameter T should be mentioned in input types (argument types, receiver type or expected type). Try to specify it explicitly.

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

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

はじめの一歩

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

調査の方向性

まず、issue で説明されている TypeScript と Kotlin の推論動作と Python の例を比較します。どの代替推論アルゴリズムまたはアノテーションをサポートすべきか、また混在した引数型、正確な型、除外された推論がどのように動作することが期待されるかを定義します。完了には、合意された設計と対応する型付け仕様が必要です。

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

評価

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

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

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