Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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):     # ... 
like image 753
Stevoisiak Avatar asked Feb 09 '18 15:02

Stevoisiak


People also ask

Can a Python function return multiple types?

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.

How do you use type hints in Python?

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.

What does type () do in Python?

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.

What is TypeVar?

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.


1 Answers

You want a type union:

from typing import Union  def post_xml(data: Union[str, ET.Element]):     ... 
like image 126
deceze Avatar answered Sep 20 '22 17:09

deceze