繁体   English   中英

如何输入提示 function 同时接受联合和该联合的任何类型?

[英]How to type hint function accepting both union and any type of that union?

$ cat foo.py

from typing import overload, Union, TypeVar

T = Union[int, str]
SubT = TypeVar("SubT", int, str)

@overload
def a(t: T) -> T:
    ...

@overload
def a(t: SubT) -> SubT:
    ...

def a(t: T) -> T:
    return t
$ mypy foo.py

foo.py:7: error: Overloaded function signatures 1 and 2 overlap with incompatible return types

为什么返回类型不兼容,我该如何进行类型检查? 我想要这些示例返回类型:

v_1: Union[int, str] = 1
v_2: int = 2
v_3: str = "3"

a(v_1)  # Want Union[int, str].
a(v_2)  # Want int.
a(v_3)  # Want str.

我想避免为intstr显式重载a ,因为SubT有超过 2 个约束。

如果我删除第一个重载, a(v_1)将不会进行类型检查。 如果我删除第二个重载, a(v_2)a(v_3)的返回值类型将分别提示为Union[int, str]而不是intstr

在我的实际问题中,我有一个Iterable ,它是SubTTypeVar )下的同类类型或TUnion )下的异构类型。 我想写一个a ,如果它出现在同类情况下,它将对两者的元素进行操作而不会丢失类型粒度。

TypeVar将允许您提供联合的类型和联合本身作为选项:

T = TypeVar("T", int, str, Union[int, str])

def a(t: T) -> T:
    return t

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM