I have a list which can be like this:
a_list = ["apple"]
or
a_list = []
In this case, type-hint can be List[str]
or List[Optional[str]]
. Which is the appropriate type-hint for this variable and why?
Thanks!
CodePudding user response:
List[str]
includes all lists of strings, including the empty list. (From a typing perspective, an empty list of type List[str]
is distinct from an empty list of type List[int]
).
Optional[str]
is shorthand for Union[None, str]
, so List[Optional[str]]
is the type of lists that can contain str
values and None
s, not the type of list that may or may not have a str
value.