mypy error: Need type annotation for (tested)
mypy says Need type annotation for "x" when you assign an empty [], {{}} or set() and nothing in the same scope tells it the element type. Annotate the variable: items: list[str] = [], counts: dict[str, int] = {{}}.
1. Reproduce it, then fix it
b1.py:
items = []
counts = {}
seen = set()
result = None
result = 5
b2.py, the annotated version:
from typing import Optional
items: list[str] = []
counts: dict[str, int] = {}
seen: set[int] = set()
result: Optional[int] = None
result = 5
def collect() -> list[str]:
out = [] # inferred from the append below: no error
out.append("a")
return out
Output (mypy 2.4.0, Python 3.13.5, --no-incremental):
$ mypy b1.py
b1.py:1: error: Need type annotation for "items" (hint: "items: list[<type>] = ...") [var-annotated]
b1.py:2: error: Need type annotation for "counts" (hint: "counts: dict[<type>, <type>] = ...") [var-annotated]
b1.py:3: error: Need type annotation for "seen" (hint: "seen: set[<type>] = ...") [var-annotated]
Found 3 errors in 1 file (checked 1 source file)
$ mypy b2.py
Success: no issues found in 1 source file
- mypy cannot infer an element type from an empty
[],{}orset()when nothing later in the same scope adds to it, so it asks for an annotation (error codevar-annotated). The hint shows the exact syntax:items: list[str] = []. result = Nonefollowed byresult = 5was not an error here: mypy accepted it, using the later assignment in the same scope to complete the type. AnnotatingOptional[int](orint | None) is still clearer.- Inside a function, an empty list followed by
.append("a")in the same scope is inferred aslist[str]without an annotation (collect()inb2.py).
To silence just this check for a line, add # type: ignore[var-annotated]; prefer the annotation.
Frequently asked questions
How do I fix mypy Need type annotation for?
Annotate the empty container with its element type, e.g. items: list[str] = [] or counts: dict[str, int] = {}.
Why does mypy not need an annotation for some empty lists?
If the same scope later appends to the list (out.append("a")), mypy infers the element type from that.
Written with AI assistance. Measured on 2026-10-23 with mypy 2.4.0 and Python 3.13.5 on Linux. Files were checked verbatim and the output pasted unedited. PlainTables is our extension; mypy is free.