如何创建通过多个别名定义的递归 Python 类型? [英] How can I make a recursive Python type defined over several aliases?

查看:58
本文介绍了如何创建通过多个别名定义的递归 Python 类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want this logical type structure:

ObjectType = Dict[str, 'EntryType']
ListType = List['EntryType']
EntryType = Union[str, 'ListType', 'ObjectType']

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)
...

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

Is there some way to encode this recursive data type?

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

推荐答案

递归类型是 还没有在 mypy 中支持.不过,它们肯定在路线图上,尽管我不确定何时开始实施工作.它原定于今年早些时候开始,但语义分析阶段的先决条件重构(它进行了许多内部更改以干净地支持递归类型)最终花费的时间比预期的要长,所以我不确定新的时间线是.也许在未来半年左右的某个时候?

Recursive types are not yet supported in mypy. They're definitely on the roadmap though, although I'm not exactly sure when the implementation work will begin. It was slated to begin earlier this year, but the prerequisite refactor of the semantic analysis phase (which made a lot of the internal changes needed to cleanly support recursive types) ended up taking longer than expected, so I'm not sure what the new timeline is. Maybe sometime in the next half-year or so?

您可以研究的一种可能的替代方法是使用 TypedDicts,它允许您将特定类型分配给某些键.如果您已经提前知道输入 dict 的结构,这将特别有用——如果您确切地知道您的 ObjectType 将具有哪些键,以及它们将映射到什么.像 pydantic 之类的库在这里也很有帮助,如果您更喜欢使用对象而不是 dicts 并且不想不得不这样做写一堆验证逻辑.

A possible alternative approach you could look into is to use TypedDicts, which let you assign specific types to certain keys. This is particularly useful if you already know ahead of time what the structure of your input dicts will be -- if you know exactly what keys your ObjectTypes will have, and precisely what they'll map to. Libraries like pydantic are also helpful here, if you prefer working with objects over dicts and prefer not to have to write a bunch of validation logic.

但实际上,如果您的 dict 结构是真正自由格式的,最好使用 ObjectType = Dict[str, object].毕竟,为了准确识别您正在处理的 EntryType,您无论如何都必须添加一些 isinstance 检查以适当缩小类型.因此,虽然从 object 而不是 Union[str, ListType, ObjectType] 开始会有点烦人,但根据您的情况,它可能不会太大正在做.

Pragmatically though, if your dict structure is genuinely free-form, it might be best to just go with ObjectType = Dict[str, object]. After all, in order to identify exactly which EntryType you're dealing with, you're going to have to add in a few isinstance checks anyways to appropriate narrow the type. So, while starting off with object instead of Union[str, ListType, ObjectType] will be mildly annoying, it might not be too huge of an imposition depending on what you're doing.

这篇关于如何创建通过多个别名定义的递归 Python 类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆