如何使用类型提示为参数指定多种类型? [英] How do I specify multiple types for a parameter using type-hints?

查看:44
本文介绍了如何使用类型提示为参数指定多种类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆