【发布时间】:2022-06-23 16:59:00
【问题描述】:
我正在尝试创建一个带有类变量的类,该类变量表示该类的一个空实例。我目前拥有的是
from collections import namedtuple
# from typing import Optional
_Thing = namedtuple("_Thing", ["foo", "bar"])
class Thing(_Thing):
__slots__ = ()
def baz(self):
print("foo", self.foo)
# NameError: name 'Thing' is not defined
# EMPTY = Thing(None, None)
Thing.EMPTY = Thing(None, None)
if __name__ == '__main__':
thing = Thing.EMPTY
thing.baz()
print("Done")
我也在尝试在代码上运行 Mypy。当我运行python simple.py 时,它按预期运行:
$ python simple.py && mypy simple.py
foo None
Done
simple.py:15: error: "Type[Thing]" has no attribute "EMPTY"
simple.py:18: error: "Type[Thing]" has no attribute "EMPTY"
Found 2 errors in 1 file (checked 1 source file)
但 Mypy 很不高兴,因为 Thing 的声明没有定义 EMPTY。
如果我在类中取消注释EMPTY 的定义,我会得到一个NameError,因为我试图在定义Thing 时引用它。
如果我尝试在类中将EMPTY 声明为EMPTY = None 并将其分配到类外,Mypy 会不高兴,因为它认为EMPTY 的类型是None。
如果我尝试将 EMPTY 注释为 Optional[Thing] 作为类型,那么我会在定义之前重新使用 Thing。
是否有解决方案,或者我只需要告诉 Mypy 忽略 EMPTY 字段?
我正在使用 python 3.9。
【问题讨论】: