如何解决将新属性分配给函数时,如何抑制 mypy 中的“无属性”错误?
我经常使用以下习惯用法进行静态初始化:
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
但是,使用 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"
如何抑制这些错误,尤其是在本地(例如,仅此函数/属性)?
解决方法
您可以使用装饰器为函数对象返回自定义 Protocol
。像这样:
from typing import Any,Protocol,Optional
class ComputeAnswerProto(Protocol):
ret: Optional[int]
def __call__(self) -> int: ...
def compute_decorator(func: Any) -> ComputeAnswerProto:
return func
@compute_decorator
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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。