Ste*_*ica 12 python arguments type-hinting python-3.x
我有一个Python函数,它接受XML数据作为str.
为方便起见,该功能还会检查xml.etree.ElementTree.Element并str在必要时自动转换为.
import xml.etree.ElementTree as ET
def post_xml(data: str):
if type(data) is ET.Element:
data = ET.tostring(data).decode()
# ...
Run Code Online (Sandbox Code Playgroud)
是否可以使用类型提示指定参数可以作为两种类型之一给出?
def post_xml(data: str or ET.Element):
# ...
Run Code Online (Sandbox Code Playgroud)
dec*_*eze 18
你想要一个类型联盟:
from typing import Union
def post_xml(data: Union[str, ET.Element]):
...
Run Code Online (Sandbox Code Playgroud)