python 3.5 代码中的变量需要类型注释

Need type annotation for variable in python 3.5 code

我在我的 python 3.5 代码上使用 mypy,我收到了很多这样的消息:

file:line number: error: Need type annotation for variable

但我读到 python 3.6 中的新功能,它仅在 python 3.6 中引入了变量注释的语法:

PEP 484 introduced the standard for type annotations of function parameters, a.k.a. type hints. This PEP adds syntax to Python for annotating the types of variables including class variables and instance variables...

如果我试图在 python 3.5 程序中为我的变量添加变量类型注释,它会抛出 SyntaxError.

我该怎么办?忽略此消息?更新到 python 3.6?为什么 mypypython 3.6 中编写的那样编译我的代码?

使用注释来注解变量类型

x = 5  # type: int
my_list = []  # type: List[str]

检查作弊sheet

https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html

您的代码混淆了 mypy 尝试进行的类型推断。例如,在以下代码段中重新定义名称,不允许 mypy 推断 f:

的类型
f = []
f = {}

因为它无法理解 f 的类型应该是什么,它会抱怨并告诉您它需要变量的注释。您可以显式提供类型提示:

  • Python3.5 的类型注释。
  • Python3.6
  • 的变量注释

mypy 未在 3.6 中编译,此错误在两个版本中都存在。区别在于你如何解决它。

如果你有空值,你必须定义变量的类型。例如:

my_val: str = ""
my_val1: dict = {}
my_val2: list = []

等你的情况,我会考虑把python的版本改成3.6,需要更新代码。

mypy 文档提到空集合通常需要对某些复杂情况进行类型注释。

https://mypy.readthedocs.io/en/stable/common_issues.html#types-of-empty-collections