我想要这个逻辑类型结构:
ObjectType = Dict[str, 'EntryType']
ListType = List['EntryType']
EntryType = Union[str, 'ListType', 'ObjectType']
Run Code Online (Sandbox Code Playgroud)
mypy 报告这些错误:
mdl/structure.py:7: error: Cannot resolve name "ObjectType" (possible cyclic definition)
mdl/structure.py:7: error: Cannot resolve name "EntryType" (possible cyclic definition)
mdl/structure.py:8: error: Cannot resolve name "ListType" (possible cyclic definition)
...
Run Code Online (Sandbox Code Playgroud)
有没有办法对这种递归数据类型进行编码?
我相信我可以内联各个类型,每次都输入完整的定义,以允许递归。我宁愿避免这种情况,因为它体积庞大且不太清晰。
假设我有一个接受a Garthok,an Iterable[Garthok],an Iterable[Iterable[Garthok]]等的函数。
def narfle_the_garthoks(arg):
if isinstance(arg, Iterable):
for value in arg:
narfle(arg)
else:
arg.narfle()
Run Code Online (Sandbox Code Playgroud)
有什么方法可以为arg指定类型提示,以指示它接受Iterables中Garthoks的任何级别?我怀疑不是,但以为我会检查我是否缺少某些东西。
解决方法是,我仅指定几个级别,然后以结尾Iterable[Any]。
Union[Garthok,
Iterable[Union[Garthok,
Iterable[Union[Garthok,
Iterable[Union[Garthok, Iterable[Any]]]]]]]]
Run Code Online (Sandbox Code Playgroud) 我正在尝试在适用的情况下向我的代码库引入静态类型注释。一种情况是在读取 JSON 时,结果对象将是一个以字符串为键的字典,具有以下类型之一的值:
boolstrfloatintlistdict然而list,dict以上可以包含相同类型的字典,导致递归定义。这在 Python3 的类型结构中可以表示吗?