我有一个 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()
# ...
是否可以使用类型提示指定参数可以作为两种类型之一给出?
def post_xml(data: str or ET.Element):
# ...
您想要一个类型union。对于 Python 3.10+:
def post_xml(data: str | ET.Element):
对于早期版本:
from typing import Union
def post_xml(data: Union[str, ET.Element]):
...