微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

具有任意数量的 int 参数键入提示的函数

如何解决具有任意数量的 int 参数键入提示的函数

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] 返回错误 "…" 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 路线。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。