Type hints for nested defaultdict

Viewed 57

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"
1 Answers

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))

or just use defaultdict and set itself as @chepner mentioned:

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