是的,您可以编写一个no-op修饰符来签名f
次拒绝try 传递您不想要的类型.下面的示例使f
拒绝任何传递与float
不兼容的值的try .
演示:mypy Playground,Pyright Playground
import typing_extensions as t
if t.TYPE_CHECKING:
import collections.abc as cx
F = t.TypeVar("F", bound=cx.Callable[..., t.Any])
Ts = t.TypeVarTuple("Ts")
class _FloatOnlyCallable(t.Protocol):
def __call__(self, /, *args: float) -> t.Any: ...
def asFloatOnlyCallable(f: F, /) -> F | _FloatOnlyCallable:
"""Decorate a function to make it only accept variadic positional float arguments"""
return f
@asFloatOnlyCallable
def f(*args: *Ts) -> tuple[*Ts]:
return args
>>> a, b = f(1.0, 2.0) # OK
>>> c, d = f("3.0", 4.0) # Error: Incompatible type "str", expected "float"
>>> e, g, h = f(5.0, 6.0) # Error: Need more values to unpack