Python typehints和linters

tob*_*spr 7 python annotations lint type-hinting python-3.x

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

from typing import List
from something import MyOtherClass

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

但是,现在我们使用的linters(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]
Run Code Online (Sandbox Code Playgroud)

有没有更好的解决方案来解决这个问题?我们不想禁用所有未使用的导入警告.

Zer*_*eus 6

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
Run Code Online (Sandbox Code Playgroud)

... 或者:

from typing import List, Optional
from something import MyOtherClass

class MyClass:

    some_var: Optional[List[MyOtherClass]]

    def __init__(self) -> None:
        self.some_var = None
Run Code Online (Sandbox Code Playgroud)

由于ListMyOtherClass现在显示为代码的实际令牌,而不是评论,棉短绒应该没有问题,承认确实正在使用他们。

  • @Guillaume 根据 [PEP 484](https://www.python.org/dev/peps/pep-0484/#the-meaning-of-annotations),*"`__init__` 的返回类型应该被注释使用 `-> None` 。原因很微妙。如果 `__init__` 假定返回注释为 `-> None`,那是否意味着无参数、未注释的 `__init__` 方法仍然应该是 type-检查?与其让这个模棱两可或向异常引入异常,我们只是说`__init__`应该有一个返回注释”* (4认同)