如何使用类型提示为参数指定多种类型? [英] How do I specify multiple types for a parameter using type-hints?
本文介绍了如何使用类型提示为参数指定多种类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个Python函数,该函数接受XML数据作为 str
.
I have a Python function which accepts XML data as an str
.
为方便起见,该函数还会检查 xml.etree.ElementTree.Element
,并在必要时自动将其转换为 str
.
For convenience, the function also checks for xml.etree.ElementTree.Element
and will automatically convert to str
if necessary.
import xml.etree.ElementTree as ET
def post_xml(data: str):
if type(data) is ET.Element:
data = ET.tostring(data).decode()
# ...
是否可以通过类型提示指定可以将参数指定为两种类型之一?
Is it possible to specify with type-hints that a parameter can be given as one of two types?
def post_xml(data: str or ET.Element):
# ...
推荐答案
您需要输入联盟:
from typing import Union
def post_xml(data: Union[str, ET.Element]):
...
这篇关于如何使用类型提示为参数指定多种类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文