How do I specify multiple types for a parameter using type-hints? [duplicate]

北城余情 提交于 2020-06-09 11:58:47

问题


I have a Python function which accepts XML data as an 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):
    # ...

回答1:


You want a type union:

from typing import Union

def post_xml(data: Union[str, ET.Element]):
    ...


来源:https://stackoverflow.com/questions/48709104/how-do-i-specify-multiple-types-for-a-parameter-using-type-hints

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!