[英]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.
我想避免為int
和str
顯式重載a
,因為SubT
有超過 2 個約束。
如果我刪除第一個重載, a(v_1)
將不會進行類型檢查。 如果我刪除第二個重載, a(v_2)
和a(v_3)
的返回值類型將分別提示為Union[int, str]
而不是int
和str
。
在我的實際問題中,我有一個Iterable
,它是SubT
( TypeVar
)下的同類類型或T
( Union
)下的異構類型。 我想寫一個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.