Lets say I want a function that execute a function with its parameters (yes, this is useless, but also the simplest case I could think of) :
from typing import Callable, TypeVar, List, Any
Params = TypeVar("Params", bound=List[Any])
def do_something(fn: Callable[Params , bool], params: Params)
return fn(params)
def add(a: int, b: int) -> int:
return a + b
result = do_something(add, (1, 2))
print(result)
Right now, python typing is showing an error, as Params is neither a List or “…”. Is there a way to use TypeVar so that my IDE understands that the function should take as arguments the same types as the ones passed as params ?
3
You are trying to reinvent ParamSpec
, a kind of type variable designed precisely for this purpose.
from typing import ParamSpec, TypeVar
P = ParamSpec('P')
RV = TypeVar('RV')
def do_something(fn: Callable[P, RV], *args: P.args, **kwargs: P.kwargs): -> RV
return fn(*args, **kwargs)
def add(a: int, b: int) -> int:
return a + b
result = do_something(add, 1, 2)
2