Structural Pattern Matching for Types
まだ誰も着手していません。
- 主要言語
- Python
- スター
- 1.8k
- フォーク
- 302
- 平均マージ
- 23時間
- マージ済み PR(30日)
- 8
説明
I'm sure that there are other use cases for this, but the main one that comes to mind is inferring the type of function parameters. It is common that you want to override a superclass method, for example, which may accept many parameters that you don't need in the override:
class MyClass(BaseClass):
def my_method(self, *args, **kwargs):
...
return super().my_method(*args, **kwargs)
Unfortunately, most libraries, even if they provide type stubs, do not provide a TypedDict subclass that you can simply import in order to use Unpack[MyMethodKwargs], so the only way to not lose typing information is to redeclare all of the parameters.
If we could infer a ParamSpec type from the method type, and if we could infer the method type from the method object, then we could do something like:
class MyClass(BaseClass):
def my_method(
self,
*args: Params[type[BaseClass.my_method]].args,
**kwargs: Params[type[BaseClass.my_method]].kwargs,
):
...
return super().my_method(*args, **kwargs)
I think that Python badly needs this, as **kwargs is so ubiquitous and one of the most notable places where type information is lost in my experience.
The way that TypeScript implements this is by leveraging pattern matching within conditional types:
type Parameters<T extends (...args: any) => any> = T extends (...args: infer P) => any ? P : never;
This would be a very cool feature as it could be used for many other patterns, enabling things like Params[T], ReturnType[T], KeyOf[T], ValueOf[T], etc.
Unfortunately, since expressions were not implemented for structural pattern matching, we can't directly mirror the syntax, but it could maybe look something like:
type Params[C: Callable[..., Any]] = match C: P if case Callable[P, Any] else Never
or:
type Params[C: Callable[..., Any]] match C:
case Callable[P, Any]: P
case _: Never
コントリビューションガイド
このリポジトリのコントリビューションガイドは索引されていません
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- issue 番号を参照したプルリクエストを送ります。
調査の方向性
リポジトリのファイルやテストは指定されていません。まず、提案されている ParamSpec と structural-pattern の例を、リンクされた TypeScript conditional-type アプローチと併せて確認してください。構文、意味論、および既存の型付け機能との相互作用について合意された仕様ができた時点で完了です。
索引モデルが issue の本文から書いたものです。
評価
- 技術スタック
- python, typescript
- 領域
- developer-experience
- issue の種類
- 機能追加
- 難易度
- 5/5
- 見積もり時間
- 1週間以上
- 活発さ
- 停滞
- 明瞭さ
- 説明が足りない
- 初心者へのやさしさ
- 25/100