Using Callable[..., T]
is currently the best way to annotate this.
PEP 612 introduces ParamSpec
, which can be used similar to a TypeVar
and will solve your problem. It's currently planned for Python 3.10 and will be supported for older versions using typing_extensions
There you would write:
T = TypeVar('T')
P = ParamSpec('P')
def my_decorator(f: Callable[P, T]) -> Callable[P, Container[T]]:
def wrapper(*args: Any, **kwargs: Any) -> Container[T]:
return Container(f(*args, **kwargs))
return cast(Callable[P, Container[T]], wrapper)
mypy support for PEP 612 isn't finished yet: https://github.com/python/mypy/issues/8645. Same with pytype (Google's python typechecker).
pyright (Microsoft's python typechecker) and pyre (facebook's python typechecker) do already support PEP 612
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…