Search code examples
pythonpython-3.xtype-hinting

Python: TypeVar for multiple arguments at once


Is there a way to have a TypeVar (or some other format) capture all the arguments of a function? For example, say I want to wrap a general function, such that all its arguments are given within a tuple:

def invoke(f: Callable[..., T], args: Tuple[...]) -> T:
    return f(*args)

Only that instead of the ellipsis (...), I'll have the static-type inspection enforce the contents of the Tuple to be have the same types as the function's arguments.

Thanks.


Solution

  • The answer is Yes, just not with TypeVar. One should use ParamSpec:

    from typing import ParamSpec, TypeVar, Callable
    P = ParamSpec('P')
    RT = TypeVar('RT')
    
    def invoke(f: Callable[P, RT], args: P.args) -> RT:
        return f(*args)
    
    # Or, makes more sense:
    
    def invoke(f: Callable[P, RT], args: P.args, **kwargs: P.kwargs) -> RT:
        return f(*args, **kwargs)
    
    

    Note that for python < 3.10, one should import it from typing_extensions rather than typing.