Type hints for nested defaultdict

Question:

What is the right way to write type hints for defaultdict(lambda: defaultdict(set))?

I use Python 3.10.5 and mypy 0.971, and find mypy returns an error because var = defaultdict(lambda: defaultdict(set)) doesn’t have a type hint.

Premises

  • All keys of the first defaultdict and the second defaultdict are str.
  • Values of the first defaultdict are defaultdict. Values of the second defaultdict are set. (This may be obvious.)

Sample code

from collections import defaultdict
var = defaultdict(lambda: defaultdict(set))

Output

test.py:2: error: Need type annotation for "var"
Asked By: dmjy

||

Answers:

Starting from Python 3.9 you can use defaultdict and set itself as annotations:

var: defaultdict[str, defaultdict[str, set]] = defaultdict(lambda: defaultdict(set))

For earlier Python versions there’s a special DefaultDict type from typing module:

from collections import defaultdict
from typing import DefaultDict, Set

var: DefaultDict[str, DefaultDict[str, Set]] = defaultdict(lambda: defaultdict(set))
Answered By: funnydman