Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set default value with type Union

I want to use type checking using mypy. One input argument to a function accepts either a single int or a List[int].

I could use x: Union[int, List[int]], however, what is the correct syntax to set a default value of 10, if the input argument is a single int?

x: Union[int = 10, List[int]] is not working.

like image 820
Andi Avatar asked Aug 07 '26 00:08

Andi


1 Answers

The default value is not part of the type hint. It goes after the type hint, same as for a non-union type:

x: Union[int, List[int]] = 10

Note the divergence in formatting from PEP-8 convention: whereas default values are usually given without spaces surrounding the = (i.e. as x=10), this is no longer true when they go after type hints according to PEP-484.

like image 121
Konrad Rudolph Avatar answered Aug 09 '26 13:08

Konrad Rudolph