Skip to content

ParamSpec: use P.args and P.kwargs in other scopes, such as return types #1252

@chadrik

Description

@chadrik

I have a number of cases where it would be very useful to use P.args and P.kwargs of a ParamSpec to annotate tuple and dict objects, for example, when extracting arguments to pass to a function in another context.

Here's an example:

from typing import Callable, TypeVar, Tuple, Any
from typing_extensions import ParamSpec

P = ParamSpec('P')
T = TypeVar('T')


def complex(value: str, reverse: bool =False, capitalize: bool =False) -> str:
    if reverse:
        value = str(reversed(value))
    if capitalize:
        value = value.capitalize()
    return value


def call_it(func: Callable[P, T], args: P.args, kwargs: P.kwargs) -> T:
    print("calling", func)
    return func(*args, **kwargs)


def get_callable_and_args() -> Tuple[Callable[P, Any], P.args, P.kwargs]:
    return complex, ('foo',), {'reverse': True}


call_it(*get_callable_and_args())

In this scenario P.args and P.kwargs represent a kind of ad-hoc NamedTuple and TypedDict, respectively.

Does this seem like a reasonable extension for ParamSpecs?

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