簡體   English   中英

Python typing.get_args 和 typing.Union

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM