Is it possible to type hint tuple
and dict
equivalent to P.args
and P.kwargs
?
#1447
-
Is it possible to "unpack" Context: let's annotate a function that takes a def eval_func(func: Callable[P, R], /, *args: P.args, **kwargs: P.kwargs) -> R:
return func(*args, **kwargs) Is it possible to properly type-hint an equivalent function that takes as input a single triplet? def eval_triplet(triplet: tuple[Callable[..., R], tuple, dict], /) -> R:
func, args, kwargs = triplet
return func(*args, **kwargs) What I mean is if we replace Full example: (mypy-playground) from typing import Callable, ParamSpec, TypeVar
P = ParamSpec("P")
R = TypeVar("R")
def eval_func(func: Callable[P, R], /, *args: P.args, **kwargs: P.kwargs) -> R:
return func(*args, **kwargs)
def eval_triplet(triplet: tuple[Callable[..., R], tuple, dict], /) -> R:
func, args, kwargs = triplet
return func(*args, **kwargs)
def mandatory_positional(x: int, y: int, /) -> int:
return x+y
# calling with correct signature
eval_func(mandatory_positional, 1, 2) # ✔
eval_triplet((mandatory_positional, (1,2), {})) # ✔
# calling with completely wrong signature
eval_func(mandatory_positional) # ✔ correctly raises
eval_triplet((mandatory_positional, (), {})) # ✘ does not raise... |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
No, there is no mechanism currently in the type system that enables this. You can use unpack operators to make this work with the available mechanism, although some errors may go uncaught by current type checker implementations because this is not a typical usage pattern. eval_func(mandatory_positional, *(1, 2), **{}) # No error (correct)
eval_func(mandatory_positional, *("1", 2), **{}) # Error in both mypy and pyright (correct)
eval_func(mandatory_positional, *(1, 2, 3), **{}) # Error in mypy, false negative in pyright
eval_func(mandatory_positional, *(), **{"a": 1, "b": 2}) # False negative in both mypy and pyright |
Beta Was this translation helpful? Give feedback.
No, there is no mechanism currently in the type system that enables this.
You can use unpack operators to make this work with the available mechanism, although some errors may go uncaught by current type checker implementations because this is not a typical usage pattern.