类型自引用类型别名

3

我希望有一个类型可以引用它自己:

SelfReferenceType = Dict[str, Union[str, 'SelfReferenceType']]

使用Python 3.5和最新的mypy,我得到以下结果:

test.py:1: error: Invalid type "test.SelfReferenceType"

有没有一种简单的方法来做到这一点?我猜向前引用只支持类,而不是别名?

这是我试图做的事情:

SelfReferenceType = Dict[str, Union[str, 'SelfReferenceType']]

class Foo(object):
    def __init__(self):
        self.data = {} # type: SelfReferenceType

    # Functions that work on self.data

2
很遗憾,mypy目前不支持递归类型 -- 你可以在这里跟踪它的开放问题:https://github.com/python/mypy/issues/731 - Michael0x2a
1个回答

阿里云服务器只需要99元/年,新老用户同享,点击查看详情
0

我认为你的例子是正确的,并且在较新版本的Python中可以运行:

SelfReferenceType = Dict[str, Union[str, 'SelfReferenceType']]

我已经测试了3.10.6版本,没有发现任何错误。看起来这个问题已经被解决了。

通常情况下,对于循环或“前向”引用,使用带引号的字符串是正确的方法,如https://peps.python.org/pep-0484/#forward-referencesthis comment by Guido所述。我没有找到关于是否要遵循这种类型别名模式的信息,但我不认为它会有什么不同。

值得注意的是,像这样的引用在足够新的mypy版本中可能可以不加引号工作(that include this PR,也许需要启用一个标志)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,