Skip to content

TypeVarTuple and generic ParamSpec #1135

@cdce8p

Description

@cdce8p
Contributor

I've recently been trying to add better type hints to call_job below. The Job class is basically a wrapper for a callable with some small additions.

from typing import Callable, Generic, Any
from typing_extensions import ParamSpec

_P = ParamSpec("_P")

class Job(Generic[_P]):
    def __init__(self, target: Callable[_P, None]) -> None:
        self.target = target

def call_job(
    job: Job[...],
    *args: Any
) -> None:
    job.target(*args)

My first Idea was to use only _P.args for *args, but that isn't supported (yet).

In the discussion, Eric suggested TypeVarTuple for a basic callable example.

Ts = TypeVarTuple("Ts")

def call_soon(self, callback: Callable[[*Ts], Any], *args: *Ts) -> Handle:
    ...

--
I was wondering if that extends to generic ParamSpec as well. AFAICT the PEP doesn't mention it directly. Logically it would make sense IMO.

_Ts = TypeVarTuple("_Ts")

def call_job(
    job: Job[[*_Ts]],
    *args: *_Ts
) -> None:
    job.target(*args)


def f(x: int) -> None: ...

call_job(Job(f), 42)
call_job(Job(f), "Hello")  # this should be an error

A related discussion in pyright: microsoft/pyright#3310

Activity

cdce8p

cdce8p commented on May 24, 2022

@cdce8p
ContributorAuthor

Discussions might be a better place for it. I've created a new topic with a better issue description. Maybe that will help in getting some feedback. #1194

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    topic: otherOther topics not covered

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @cdce8p

        Issue actions

          TypeVarTuple and generic ParamSpec · Issue #1135 · python/typing