How do I specify multiple types for a parameter using type-hints?
22,381
You want a type union:
from typing import Union
def post_xml(data: Union[str, ET.Element]):
...
Author by
Stevoisiak
Active programmer specializing in Python, SQL, C++, Java, and AutoHotkey. My goal is to make technology simpler to use by solving problems before users encounter them. That includes making easy-to-maintain code for anyone I collaborate with. (He/Him)
Updated on July 09, 2022Comments
-
Stevoisiak almost 2 years
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 tostr
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): # ...
-
Stevoisiak about 6 yearsPycharm's parameter info interprets
Union[str, ET.Element]
asUnion[str, Element, Element]
.