Home > Mobile >  Python typing: nested dictionary of unknown depth
Python typing: nested dictionary of unknown depth

Time:11-16

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 '???'?

CodePudding user response:

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

  • Related