【问题标题】:How to define overloaded type signatures?如何定义重载类型签名?
【发布时间】:2021-10-03 17:04:39
【问题描述】:

我有一个带有重载签名的 Python 函数,例如 float → float、str → int。我希望它正确输入,使用注释等,以便 mypy 可以正确检查它,并且像自动完成这样的工具可以工作。这可能吗?我很欣赏不同的工具会有不同的支持,所以 mypy 可以成为这个问题的标准。我可以使用任何已发布的 Python 3 版本。

【问题讨论】:

    标签: python overloading type-hinting typechecking python-typing


    【解决方案1】:

    是的,您可以使用 @typing.overload 装饰器。

    来自https://docs.python.org/3/library/typing.html#typing.overload

    @overload
    def process(response: None) -> None:
        ...
    @overload
    def process(response: int) -> tuple[int, str]:
        ...
    @overload
    def process(response: bytes) -> str:
        ...
    def process(response):
        <actual implementation>
    

    那些省略号 (...) 是文字。实际上,您将为每个重载函数签名键入三个点。实际代码将在最终定义中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-28
      • 2020-08-05
      • 2020-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多