如何解决是否有一个 python linter 根据类型注释检查覆盖函数返回类型?
我正在寻找一个 Python linter,它可以根据类型注释检查覆盖函数返回类型。 示例:
from abc import ABC,abstractmethod
from typing import List,Dict
class A(ABC):
""" Some interface """
@abstractmethod
def f(self) -> List[str]:
pass
class B(A):
""" Interface implementation """
def f(self):
return dict() # Identify this case
class C(A):
""" Interface implementation """
def f(self) -> Dict[str,str]:
return dict() # Identify this case
我检查了 flake8、mypy 和 pylint
---- 编辑----
我故意错过了注释。 Mypy 和 flake8 可以识别何时有函数返回注释。 当我定义某个接口(A 类)并且可以强制从继承类返回函数类型时,我想确定这种情况
解决方法
您可以使用类型检查器,例如 mypy
例如:
$ mypy t.py --disallow-untyped-defs
t.py:8: error: Function is missing a return type annotation
Found 1 error in 1 file (checked 1 source file)
然后调整代码以修复该错误:
--- t.py.old 2021-03-07 08:01:43.555176748 -0800
+++ t.py 2021-03-07 08:00:30.376261148 -0800
@@ -5,5 +5,7 @@
return list()
class B(A):
- def f(self):
+ def f(self) -> dict:
return dict() # Identify this case
然后 mypy 产生关于错误类型覆盖的错误:
$ mypy t.py --disallow-untyped-defs
t.py:8: error: Return type "Dict[Any,Any]" of "f" incompatible with return type "List[str]" in supertype "A"
Found 1 error in 1 file (checked 1 source file)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。