python / python/typing

[spec] Can staticmethod calls infer type parameters for the containing class?

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

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

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

説明

In this code:

from typing import TypeVar, Generic
T = TypeVar('T')

class Foo(Generic[T]):
    @staticmethod
    def create(arg: T) -> 'Foo[T]':
        ...

reveal_type(Foo.create(1234))

What should the type be? Should T be inferred based on the argument to the static method, resulting in Foo[int]? Or should it be Foo[Unknown] or similar?

mypy (python/mypy@fe15ee69b) picks Foo[int].

pyright used to choose Foo[int], but microsoft/pyright#7454 changed it to pick Foo[Unknown], on the grounds that this is required to comply with PEP 696's statement:

Type parameter defaults should be bound by attribute access (including call and subscript).

My example does not include any type parameter defaults, but I can see the logic of applying the same rule without one: you wouldn't want it to be a breaking change to add a default.

Still, why can't these kinds of static method calls be treated like constructor calls, where class type parameters can be inferred from arguments?

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

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

はじめの一歩

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

調査の方向性

まず、例、PEP 696 のバインディング規則、mypy のコミット fe15ee69b、および参照されている pyright の issue を確認します。ジェネリッククラスに対する staticmethod 呼び出しの合意された動作を判断し、結果として得られる仕様上の決定を記録します。これには、型チェッカーが Foo[int] を推論すべきか、未知の型を使用すべきかも含まれます。

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

評価

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

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

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