python / python/typing

Structural Pattern Matching for Types

未关闭
#1,966 1 条评论 4 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

topic: feature
主要语言
Python
星标
1.8k
派生
302
平均合并
23 小时
30 天内合并 PR
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

贡献指南

这个仓库没有索引到贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

未指定任何仓库文件或测试。首先,结合链接的 TypeScript conditional-type 方法,审查提议的 ParamSpec 和 structural-pattern 示例。只有在就语法、语义以及与现有类型功能的交互达成一致的规范后,才算完成。

由索引模型根据 Issue 内容生成。

评估

技术栈
python, typescript
领域
developer-experience
Issue 类型
功能
难度
5/5
预计耗时
一周以上
活跃度
停滞
描述清晰度
需要澄清
新手友好度
25/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。