I’m trying to include a type hint to indicate that a parameter can be a list or a single value.
In the code below, I do this using Union. However, is there a better practice?
from typing import Union, Dict, Optional, List
def my_method(self, ex_pararm: Union[List[Union[str, int, float]], str, int, float]):
pass
4
With current versions of Python (3.11+) you don’t need the typing
module to annotate unions or lists, and can do:
def my_method(self, ex_param: list[str | float] | str | float):
pass
Note that you can always pass an int
where a float
is expected, so int | float
is unnecessary.
In some situations you might want to define an alias for a pattern that you’ll repeat, in this case str | float
:
MyScalar = str | float
def my_method(self, ex_param: list[MyScalar] | MyScalar):
pass
The main benefit of using an alias like this is readability, i.e. being able to assign a meaningful/shorter name to that union type to make it easier to recognize visually than it would be if it were typed out each time, so I’d only do this if the context is such that you can actually come up with a meaningful name.
3