Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Type hints for nested defaultdict

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  • 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"

>Solution :

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))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading