Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Structural Pattern Matching for Types #1966

Open
Labels
topic: featureDiscussions about new features for Python's type annotations
@zach-waggoner

Description

@zach-waggoner

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:

classMyClass(BaseClass):defmy_method(self,*args,**kwargs):        ...returnsuper().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 useUnpack[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:

classMyClass(BaseClass):defmy_method(self,*args:Params[type[BaseClass.my_method]].args,**kwargs:Params[type[BaseClass.my_method]].kwargs,    ):        ...returnsuper().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 leveragingpattern matching within conditional types:

typeParameters<Textends(...args:any)=>any>=Textends(...args: inferP)=>any ?P :never;

This would be a very cool feature as it could be used for many other patterns, enabling things likeParams[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:

typeParams[C:Callable[...,Any]]=matchC:PifcaseCallable[P,Any]elseNever

or:

typeParams[C:Callable[...,Any]]matchC:caseCallable[P,Any]:Pcase _:Never

Metadata

Metadata

Assignees

No one assigned

    Labels

    topic: featureDiscussions about new features for Python's type annotations

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions


      [8]ページ先頭

      ©2009-2025 Movatter.jp