Search code examples
pythondictionarymypy

Python: return type hint of arbitrary depth dictionary


I am using a defaultdict collection to easily build an arbitrary depth python dictionary as follows:

from collections import defaultdict
from datetime import datetime


def recursive_dict() -> defaultdict:
    """enable arbitrary depth dictionary declaration"""
    return defaultdict(recursive_dict)


dbdict = recursive_dict()

dbdict["entity"]["surface"] = "this is a string"
dbdict["entity"]["spotlight"]["uri"] = "http://test.com/test"
dbdict["entity"]["spotlight"]["curation"]["date"] = datetime.now()

which works fine as expected but mypy type checking fails with the following error message:

error: Missing type parameters for generic type "defaultdict"  [type-arg]

I am confused as how to fix this since I'd like to use the recursive_dict function for any type of dictionary that I'll build.


Solution

  • Defauldict is expecting a typing of its parameters.

    In this case the typing wont be so trivial since its an returning a defaultdict once and after that a nested defaultdict.

    A way how you could satisfy mypy would providing the type str and Any to the defaultdict.

    from typing import Any
        
    def recursive_dict() -> defaultdict[str , Any]: 
        """enable arbitrary depth dictionary declaration"""
        return defaultdict(recursive_dict)