具有任意数量的 int 参数键入提示的函数
Function with any number of int params typing hint
def f() -> Callable[[ # how to show there can be any number of int?
], float]:
def g(*args):
assert all(type(x) == int for x in args)
return 0.1
return g
我阅读了打字文档,Callable(即 Callable[…, ReturnType]
)不是我需要的。
我知道Tuple[int, …]
,但是Callable[[int, …], float]
return错误"…" not allowed in this context Pylance
。
您可以通过定义一个 Protocol
和一个 __call__
来做到这一点,其函数签名具有所需的类型:
from typing import Protocol
class IntCallable(Protocol):
def __call__(self, *args: int) -> float: ...
def f() -> IntCallable:
def g(*args: int) -> float:
assert all(type(x) == int for x in args)
return 0.1
return g
正在使用 mypy 进行测试:
f()(1, 2, 3) # fine
f()("foo") # error: Argument 1 to "__call__" of "IntCallable" has incompatible type "str"; expected "int"
另一种选择是让您的函数采用单个 Iterable[int]
参数而不是任意数量的 int
参数,这样您就可以使用简单的 Callable
键入而不是走更复杂的 Protocol
路线。
def f() -> Callable[[ # how to show there can be any number of int?
], float]:
def g(*args):
assert all(type(x) == int for x in args)
return 0.1
return g
我阅读了打字文档,Callable(即 Callable[…, ReturnType]
)不是我需要的。
我知道Tuple[int, …]
,但是Callable[[int, …], float]
return错误"…" not allowed in this context Pylance
。
您可以通过定义一个 Protocol
和一个 __call__
来做到这一点,其函数签名具有所需的类型:
from typing import Protocol
class IntCallable(Protocol):
def __call__(self, *args: int) -> float: ...
def f() -> IntCallable:
def g(*args: int) -> float:
assert all(type(x) == int for x in args)
return 0.1
return g
正在使用 mypy 进行测试:
f()(1, 2, 3) # fine
f()("foo") # error: Argument 1 to "__call__" of "IntCallable" has incompatible type "str"; expected "int"
另一种选择是让您的函数采用单个 Iterable[int]
参数而不是任意数量的 int
参数,这样您就可以使用简单的 Callable
键入而不是走更复杂的 Protocol
路线。