Reputation: 1125
I have a list which can have one or more items:
a_list = ["apple"]
But it can also be empty:
a_list = []
In this case, which of List[str]
and List[Optional[str]]
is the appropriate type-hint for this variable and why?
Upvotes: 7
Views: 7238
Reputation: 45
As of python 3.10 list
will do just fine:
# 3.10 and above
my_list: list[str] = []
# earlier versions of python
from typing import List
ma_list: List[str] = []
Upvotes: 1
Reputation: 532303
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.
Upvotes: 11