Python typing: nested dictionary of unknown depth

Question:

I am using Python 3.11. Type hinting for dict of dicts of strs will look like this:

dict[dict[str, str]]

But what if I want to make hints for dict of unknown depth?

For example, I want to write a function, which construct tree in dict form from list of tuples (parent, offspring):

source = [('a', 'b'), ('b', 'c'), ('d', 'e')]
target = {'a': {'b': {'c': {}}}, 'd': {'e': {}}}


def tree_form(source: list[tuple[str, str]]) -> ???:
    """code"""
    pass

What should I write instead of ‘???’?

Asked By: eightlay

||

Answers:

You can use a type alias with a forward reference to itself:

from typing import TypeAlias

NestedDict: TypeAlias = dict[str, str | 'NestedDict']

def tree_form(source: list[tuple[str, str]]) -> NestedDict:
    return {'a': {'b': {'c': {}}}, 'd': {'e': {}}}

print(tree_form([('a', 'b'), ('b', 'c'), ('d', 'e')]))

Demo of this code passing mypy:

https://mypy-play.net/?mypy=latest&python=3.10&gist=6d359c16ab3f5e82b5cd2cdf9e142a6d

Answered By: blhsing
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.