python / python/mypy

Analysis time binding of restricted `Generic`s

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

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

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

説明

Feature

A generic type defined with reference to a restricted type variable only makes sense when containing a value of type within the restrictions of the type variable.

It would then make sense to assume that when the user does not bind the generic type (that is, they do not provide a type argument), the implied type is the Union of the possible bound types.

To Reproduce

from typing import Any
from typing import AnyStr
from typing import Generic


class Message(Generic[AnyStr]):
    header: AnyStr
    content: AnyStr

    def __init__(self, header: AnyStr, content: AnyStr) -> None:
        self.header = header
        self.content = content

# This feels wrong to me, and I'd rather see this as Union[Message[str], Message[bytes]]
m1: Message = Message(header="foo", content="bar")
reveal_type(m1)  # Message[Any]...

# This is perhaps ok, since the user explicitly passed the `Any` parameter. But if this behavior is kept, 
# one shouldn't be forced to provide a type arg to restricted generics in strict mode, since that 
# would imply having to enumerate the restriction to get the same behavior as above.
m2: Message[Any] = Message(header="foo", content="bar")
reveal_type(m2)  # Message[Any]...

Pitch

Say I have a function that accepts any valid Message as an arg:

def read(msg: Message) -> None:
    msg.content.method_in_neither_str_nor_bytes()

If I annotate it like I just did, I get no hand-holding from the type checker. msg.content is understood as Any, so everything goes. We know, however, that this has to be one of AnyStr. If I want type checker assistance, I now have to manually list the possible Message types, like so:

def read(msg: Union[Message[str], Message[bytes]]) -> None:
    msg.content.method_in_neither_str_nor_bytes()

This is fine when the restriction consists of two types, but it should be easy to imagine examples with a more verbose restriction.

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

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

はじめの一歩

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

調査の方向性

この issue では、実装ファイル、テスト、エントリポイントが指定されていません。まず再現手順と、既存の未束縛の制限付きジェネリクスの処理を確認してください。許可される bound 型の union を Any ではなく推論し、明示的に指定された Any の動作を維持し、示されているケースのカバレッジを追加できれば完了です。

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

評価

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

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

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