Types of empty collections
You often need to specify the type when you assign an empty list ordict to a new variable, as mentioned earlier:
- a: List[int] = []
Without the annotation mypy can’t always figure out theprecise type of a
.
You can use a simple empty list literal in a dynamically typed function (as thetype of a
would be implicitly Any
and need not be inferred), if typeof the variable has been declared or inferred before, or if you perform a simplemodification operation in the same scope (such as append
for a list):
- a = [] # Okay because followed by append, inferred type List[int]
- for i in range(n):
- a.append(i * i)
However, in more complex cases an explicit type annotation can berequired (mypy will tell you this). Often the annotation canmake your code easier to understand, so it doesn’t only help mypy buteverybody who is reading the code!