Generic specialization?
まだ誰も着手していません。
- 主要言語
- Python
- スター
- 1.8k
- フォーク
- 302
- 平均マージ
- 23時間
- マージ済み PR(30日)
- 8
説明
I was wondering if it was possible to redefine what a particular generic means for a particular type (and maybe its subclasses, superclasses depending on covariance/contravariance?).
My use case comes from the scikit-learn API. In this API each "estimator" class has two set of attributes: those that are passed to __init__ and those that are computed after calling .fit() to fit the model. The convention is that the latest ones end with an underscore.
Also the fit method returns self.
In addition to that, there are methods, like predict, that are only allowed after fitting.
Currently the code that uses this library is like this:
my_estimator = MyEstimator(param1, param2)
my_estimator.fit(X_train, y_train)
# Now is safe to access fit attributes and call predict, score, etc
print(my_estimator.fitted_attr1_)
print(my_estimator.predict(X_test))
The idea was to allow Mypy (or other analyzer) to check these invariants using additional types. Instead of typing fit as:
def fit(self, X: ..., y: ...) -> Self
we could type it as
def fit(self, X: ..., y: ...) -> Fitted[Self]
We then would need a way to:
- Define that
Fitted[T]is a subclass ofT. Similar to #802. - Define the particular fit attributes of
Fitted[T]for a particularT. - Define that some methods. such as
predictcan only be used with aFitted[T]object, and not with aTobject. - Define that
Fitted[Fitted[T]] == Fitted[T].
Then, only a small change would be needed in the previous code to allow type checkers to detect whether the invariants have been broken:
my_estimator = MyEstimator(param1, param2)
my_estimator = my_estimator.fit(X_train, y_train) # Line changed
# Now is safe to access fit attributes and call predict, score, etc
print(my_estimator.fitted_attr1_)
print(my_estimator.predict(X_test))
This is only a possibility. Alternatives include:
- Defining a subclass just for the type-checker in a
if TYPE_CHECKING:environment. This works for the basic usage illustrated here, but not in other generic cases, e.g.: typing a function that accepts a fitted estimator of any type. It also creates a parallel class structure, which should also be subclassed by subclasses, etc. - Just typing the whole class and don't let type-checkers to verify these invariants.
However I think that adding this flexibility to the type system could maybe help in other cases.
コントリビューションガイド
このリポジトリのコントリビューションガイドは索引されていません
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- issue 番号を参照したプルリクエストを送ります。
調査の方向性
この issue で提案されている Fitted[T] の例から始め、参照されている issue #802 を読んでください。要求されているサブクラス化、特殊化、メソッドの制限、冪等性の動作を、説明されている代替案と比較してください。完了には、合意された型システムの設計と、それに対応する仕様の詳細が必要です。
索引モデルが issue の本文から書いたものです。
評価
- 技術スタック
- python
- 領域
- developer-experience
- issue の種類
- 機能追加
- 難易度
- 5/5
- 見積もり時間
- 1週間以上
- 活発さ
- 停滞
- 明瞭さ
- おおむね明確
- 初心者へのやさしさ
- 25/100