Search code examples
pythonpython-3.xtype-hinting

python3 typing: extract argument list from Callable


Consider a function which wraps another function and puts the output into a singleton list:

def listify(func):
    return lambda *kargs, **kwargs: [func(*kargs, **kwargs)]

How would you type-hint this function in python3? This is my best attempt:

from typing import Callable, TypeVar
T = TypeVar('T')

def listify(func: Callable[..., T]) -> Callable[..., List[T]]:
    return lambda *kargs, **kwargs: [func(*kargs, **kwargs)]

But I'm not happy that the returned Callable does not inherit the signature of the argument types of the input Callable. Is there any way to make that happen without making assumptions on the number of arguments of func?


Solution

  • PEP 612 adds ParamSpec to python-3.10, which allows for:

    from typing import Callable, ParamSpec, TypeVar
    P = ParamSpec('P')
    T = TypeVar('T')
    
    def listify(func: Callable[P, T]) -> Callable[P, List[T]]:
        return lambda *kargs, **kwargs: [func(*kargs, **kwargs)]