Structural Pattern Matching for Types
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 1.8k
- Forks
- 302
- Avg merge
- 23h
- Merged PRs (30d)
- 8
Description
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
Contributor guide
No contributing guide indexed for this repository
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
No repository files or tests are named. Start by reviewing the proposed ParamSpec and structural-pattern examples alongside the linked TypeScript conditional-type approach. Done means an agreed specification for syntax, semantics, and interaction with existing typing features before implementation.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python, typescript
- Domain
- developer-experience
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 25/100