我正在尝试对一些代码(一个可识别的模块)进行类型检查。问题是我导入了此类AnsibleModule
。该类是一个单例,几乎每个函数都需要它,因此我将其设置为全局。在我的代码顶部
module: Optional[AnsibleModule] = None
实际上,main的第一行然后将module
设置为需要的值(大约module = AnsibleModule(...)
,但几乎是20行且无关紧要)。
每次调用AnsibleModule具有的函数时,都会不断收到类似error: Item "None" of "Optional[AnsibleModule]" has no attribute "run_command"
的错误。如果我放弃了可选项而只拥有module: AnsibleModule
,一切都将消失(由我无法将None
分配给AnsibleModule
然后我制定了该行为的最小工作示例
# me_mod.py
from typing import Optional
class Thing:
def me_func(self, stuff: str) -> None:
print(stuff)
meThing: Thing
meThing.me_func("words")
meThing2: Optional[Thing] = None
meThing2 = meThing
meThing2.me_func("more words")
# other_mod.py
from typing import Optional
from me_mod import Thing
meThing: Optional[Thing] = None
meThing = Thing
meThing.me_func("better words")
当我在other_mod.py上运行mypy时得到
other_mod.py:5: error: Incompatible types in assignment (expression has type "Type[Thing]", variable has type "Optional[Thing]")
other_mod.py:6: error: Item "None" of "Optional[Thing]" has no attribute "me_func"
当我在me_mod.py上运行mypy时,一切都很好。
那么怎么回事,我该如何解决?
我正在制作一个Ansible模块,用于从AUR安装,卸载和升级内容。我之所以选择自己的方法来解决其他问题,是因为我的软件具有花哨的检查模式,在这里它不打印所有软件包(希望在某些时候还可以下载和安装总大小)。