Home > Net >  Type hint for a list of string with 0 or more items in python
Type hint for a list of string with 0 or more items in python

Time:12-19

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 Nones, not the type of list that may or may not have a str value.

  • Related