我经常使用以下习惯用法进行静态初始化:
def compute_answer() -> int:
if compute_answer.ret is None:
# Do stuff that only happens the first time
compute_answer.ret = 42
return compute_answer.ret
compute_answer.ret = None
Run Code Online (Sandbox Code Playgroud)
但是,使用 mypy 进行类型检查会出现以下错误:
compute.py:2: error: "Callable[[], int]" has no attribute "ret"
compute.py:4: error: "Callable[[], int]" has no attribute "ret"
compute.py:5: error: "Callable[[], int]" has no attribute "ret"
compute.py:7: error: "Callable[[], int]" has no attribute "ret"
Run Code Online (Sandbox Code Playgroud)
如何抑制这些错误,尤其是本地错误(例如,仅此函数/属性)?
python typechecking static-initialization mypy python-typing