Python 类型:未知深度的嵌套字典

eig*_*lay 4 python python-typing

我正在使用Python 3.11。strs 的 dicts 的 dict 的类型提示将如下所示:

dict[dict[str, str]]
Run Code Online (Sandbox Code Playgroud)

但是如果我想为未知深度的字典提供提示怎么办?

例如,我想编写一个函数,它从元组列表(父级,后代)以字典形式构造树:

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


def tree_form(source: list[tuple[str, str]]) -> ???:
    """code"""
    pass
Run Code Online (Sandbox Code Playgroud)

我应该写什么而不是“???”?

blh*_*ing 6

您可以使用带有对其自身的前向引用的类型别名:

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')]))
Run Code Online (Sandbox Code Playgroud)

此代码通过 mypy 的演示:

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