【问题标题】:Better typing hints in python? [duplicate]在 python 中更好的输入提示? [复制]
【发布时间】:2021-11-28 20:29:25
【问题描述】:

当我使用 Union of types 时如何具体说明,假设我编写了一个函数,它接受 strlist 并输出传入的任何类型,请考虑以下示例

from typing import Union

def concat(x1: Union[str, list], x2: Union[str, list]) -> Union[str, list]:
    return x1 + x2

我希望上面的示例更具体,例如 x1x2,并且函数的返回值都必须匹配相同的类型,但这些类型必须是 strlist

【问题讨论】:

    标签: python type-hinting python-typing


    【解决方案1】:
    from typing import TypeVar
    
    T = TypeVar("T")
    
    def concat(x1: T, x2: T) -> T:
        return x1 + x2
    

    【讨论】:

    • 这个例子中的union在哪里,我只看到一个类型T
    • @AbhijitSarkar:T 采用任何类型并表示输出是相同的类型。如果您需要 T 仅用于您可以说的类型子集,例如 TypeVar("T", int, str)
    • 感谢@richard,这很有意义,我不知道 TypeVar 也需要额外的参数,上面的例子在 python 文档中明确提到,我应该在之前检查过!!!
    【解决方案2】:

    类型库有一个@overload 注释,可以满足您的需求。请注意,它与其他语言(如 java)中的重载并不完全相同。您不能使用不同数量的参数创建重载。

    来自文档:

    @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>
    

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

    【讨论】:

    • 谢谢@andrew-harelson,但它太冗长了,每个进程里面都有相同的东西。
    猜你喜欢
    • 2018-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-19
    • 1970-01-01
    • 1970-01-01
    • 2020-12-23
    相关资源
    最近更新 更多