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): # ...
Python functions can return multiple values. These values can be stored in variables directly. A function is not restricted to return a variable, it can return zero, one, two or more values.
Here's how you can add type hints to our function: Add a colon and a data type after each function parameter. Add an arrow ( -> ) and a data type after the function to specify the return data type.
Python has a lot of built-in functions. The type() function is used to get the type of an object. When a single argument is passed to the type() function, it returns the type of the object. Its value is the same as the object.
In short, a TypeVar is a variable you can use in type signatures so you can refer to the same unspecified type more than once, while a NewType is used to tell the type checker that some values should be treated as their own type.
You want a type union:
from typing import Union def post_xml(data: Union[str, ET.Element]): ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With