Search code examples
pythonpython-typingmypy

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.


Solution

  • 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.