95

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
  • 4
    Is this really a duplicate? I mean, the syntax is the same, but the semantics aren't, are they? I seem to remember something like, "functions should be contravariant on their inputs and covariant on their outputs", which means a function that can accept multiple types makes much more sense than a function that can return multiple types. Commented Jan 27, 2023 at 16:13

1 Answer 1

164

You want a type union. For Python 3.10+:

def post_xml(data: str | ET.Element):

For earlier versions:

from typing import Union

def post_xml(data: Union[str, ET.Element]):
    ...
Sign up to request clarification or add additional context in comments.

2 Comments

Pycharm's parameter info interprets Union[str, ET.Element] as Union[str, Element, Element].
So this is not even supported in python <= 9

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.