Explicit types for collections
The type checker cannot always infer the type of a list or adictionary. This often arises when creating an empty list ordictionary and assigning it to a new variable that doesn’t have an explicitvariable type. Here is an example where mypy can’t infer the typewithout some help:
- l = [] # Error: Need type annotation for 'l'
In these cases you can give the type explicitly using a type annotation:
- l: List[int] = [] # Create empty list with type List[int]
- d: Dict[str, int] = {} # Create empty dictionary (str -> int)
Similarly, you can also give an explicit type when creating an empty set:
- s: Set[int] = set()