Python 类型提示和 linter

Python typehints and linters

我一直在为我们的 python 项目添加静态类型检查,例如:

from typing import List
from something import MyOtherClass

class MyClass:
    def __init__(self) -> None:
        self.some_var = None  # type: List[MyOtherClass]

但是,现在我们使用的 linter(flake8 和 pylint)报告例如 List 为未使用的变量,因为它们未在实际代码中使用。 (顺便说一下,pep8 处理得很好)。

所以我们最终将代码更改为:

from typing import List  # noqa # pylint: disable=unused-import
from something import MyOtherClass  # noqa # pylint: disable=unused-import

class MyClass:
    def __init__(self) -> None:
        self.some_var = None  # type: List[MyOtherClass]

有没有更好的办法解决这个问题?我们不想禁用所有未使用的导入警告。

Python 3.6 实现了 PEP 526: Syntax for Variable Annotations,顾名思义,它引入了变量注释的新语法,不再需要类型注释。

在新语法中,您的代码将被重写为:

from typing import List, Optional
from something import MyOtherClass

class MyClass:

    def __init__(self) -> None:
        self.some_var: Optional[List[MyOtherClass]] = None

... 或者:

from typing import List, Optional
from something import MyOtherClass

class MyClass:

    some_var: Optional[List[MyOtherClass]]

    def __init__(self) -> None:
        self.some_var = None

由于 ListMyOtherClass 现在在代码中显示为实际标记,而不是注释,所以 linters 应该可以毫不费力地确认它们确实被使用了。

@Zero Piraeus answer offers the most recent solution to this (i.e use variable annotations, also see: )。

除此之外,当您使用 # type: 评论时,您甚至 不需要 导入 List。据我所知,mypy 不需要导入它们,也不需要导入 pyflakespylint

没有必要从 typing 导入名字,除非你需要在 Python 实际执行名字查找的地方使用他们的名字(在注释中,这不是必需的。)