我读过关于这个主题的其他问题-所有这些问题都是关于另一个层次的(类,方法或函数)。我试图找到一种方法来抑制"没有属性"。模块级别名字。
代码如下所示
service: Service | None = None
@on_startup
def init():
global service
inject.configure(config)
service = get_service()
所以我100%确定服务将不是None
,无论何时我将访问它。我现在看到的唯一方法是将service.*
标记为# type: ignore
。这导致了大量的评论。还有别的办法让这个密码通过我的吗?
错误信息为:Item "None" of "Optional[Service]" has no attribute "..."
添加显式保护将告诉MyPy您处理了这种情况,从而消除了警告。
assert service is not None
在访问变量之前使用就足够了,但是为了保证健壮性,您可能需要使用适当的
。try:
... # access service.attribute
except AttributeError:
raise Hell()
,即使在禁用断言时也执行显式检查。