【问题标题】:Is there a python linter that checks override function return types according to type annotations?是否有根据类型注释检查覆盖函数返回类型的python linter?
【发布时间】:2021-06-05 13:42:37
【问题描述】:

我正在寻找一个 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.readthedocs.io/en/stable/… 中的示例完全相同,在这种情况下,Mypy 不会产生错误,因为函数 B.f 是动态类型的,因此您应该明确使用类型提示。
  • 这正是我想要确定的。假设 A 类是 API,我想强制返回值类型而不强制注释函数

标签: python linter


【解决方案1】:

您可以使用类型检查器,例如 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)

【讨论】:

  • 我知道可以做到,但我需要它来强制通过覆盖函数(在 A 类上)进行类型匹配。我可以控制 A 类(某种接口),但不能控制 B 类(我只想检查返回值的类型是否正确)
  • @eerez 这不是它的作用吗?
  • 是的,但我不想强制注释只是为了检查返回值和父返回函数注释之间是否匹配。谢谢!
  • 那么我会说你的问题是棘手的——在一般情况下,你不能知道函数会从它的代码中返回什么类型(否则就不需要类型注释)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-18
  • 1970-01-01
相关资源
最近更新 更多