![](/img/trans.png)
[英]How to register typing.Callable with Python @singledispatch?
[英]Python typing.get_args and typing.Union
使用typing.Union
時,我無法獲得有關參數的任何信息:
import typing
x = typing.Union[str,int]
print(typing.get_args(x))
Output: (<class 'str'>, <class 'int'>)
def f(y: typing.Union[str,int]):
print(typing.get_args(y))
f(1)
Output: ()
x
是類型的聯合。 y
是聯合類型(即int
類型或str
類型)。
試試print(type(x))
和print(type(y))
。
在您的 function 簽名中,您只是注釋了y
應該是str
類型或int
類型。 因此,當您將1
傳遞給 function 時,您將在int
上調用get_args
。
您代碼中的x
只是該類型聯合 object 的別名。
事實上,你可以這樣做:
from typing import Union
x = Union[str, int]
def f(y: x):
...
這是等價的:
from typing import Union
def f(y: Union[str, int]):
...
您可以使用typing.get_type_hints()
獲取f
的類型注釋:
def f(y: typing.Union[str,int]):
print(typing.get_type_hints(f))
f(1)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.