相关疑难解决方法(0)

如何创建通过多个别名定义的递归 Python 类型?

我想要这个逻辑类型结构:

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)

有没有办法对这种递归数据类型进行编码?

我相信我可以内联各个类型,每次都输入完整的定义,以允许递归。我宁愿避免这种情况,因为它体积庞大且不太清晰。

python mypy python-typing

6
推荐指数
1
解决办法
1241
查看次数

在Python中定义递归类型提示?

假设我有一个接受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)

type-hinting python-3.x

4
推荐指数
1
解决办法
527
查看次数

递归类型注解

我正在尝试在适用的情况下向我的代码库引入静态类型注释。一种情况是在读取 JSON 时,结果对象将是一个以字符串为键的字典,具有以下类型之一的值:

  • bool
  • str
  • float
  • int
  • list
  • dict

然而listdict以上可以包含相同类型的字典,导致递归定义。这在 Python3 的类型结构中可以表示吗?

python typing python-3.x

3
推荐指数
2
解决办法
2381
查看次数

标签 统计

python ×2

python-3.x ×2

mypy ×1

python-typing ×1

type-hinting ×1

typing ×1