How to require the first parameter of a Paramspec is a specific type #9678
-
Hi, I'm writing a decorator what has an implicit contract I'd like to enforce but I'm having an issue making the type system do what I would like. Here is what I have working:
Essentially, I'd love for the return type of the model decorator to enforce that the first positional parameter of a decorated method is of type TIndex. In the example above that would be str. Is there any way to do this? Thanks for your help! Mike |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
The type system includes a special form called Here's an updated sample using Concatenate. from typing import Any, Callable, Concatenate, ParamSpec, TypeVar
TIndex = TypeVar("TIndex")
TReturn = TypeVar("TReturn")
P = ParamSpec("P")
def model(
reindex_function: Callable[[TIndex], TIndex],
) -> Callable[[Callable[Concatenate[TIndex, P], TReturn]], Callable[Concatenate[TIndex, P], TReturn]]: ...
def sample_reindex_function(index: str) -> str: ...
@model(reindex_function=sample_reindex_function)
def decorated_method(index: str, pos_arg2: int, *, kwarg1: int) -> Any: ... Or using the more modern Python 3.12 syntax: from typing import Any, Callable, Concatenate
def model[T, R, **P](
reindex_function: Callable[[T], T],
) -> Callable[[Callable[Concatenate[T, P], R]], Callable[Concatenate[T, P], R]]: ...
def sample_reindex_function(index: str) -> str: ...
@model(reindex_function=sample_reindex_function)
def decorated_method(index: str, pos_arg2: int, *, kwarg1: int) -> Any: ... If you have other general questions about the Python type system, the Python typing forum is a good place to get answers. |
Beta Was this translation helpful? Give feedback.
The type system includes a special form called
Concatenate
. You can use it to prepend positional parameters for aCallable
. For documentation, refer to this section of the typing spec.Here's an updated sample using Concatenate.