我的Py:需要Python 3.5代码中变量的类型注释

2024-05-17 10:18:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我在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?为什么mypy像用python 3.6编写一样编译我的代码?


Tags: ofthe代码消息numberfortypeline
3条回答

使用注释注释注释变量类型

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

检查备忘单

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

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

f = []
f = {}

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

  • Python 3.5的类型注释。
  • Python 3.6的变量注释

mypy没有在3.6中编译,这一错误存在于两个版本中。不同之处在于你如何处理它。

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

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

等等,在您的情况下,我将考虑将python的版本更改为3.6,并且需要更新代码。

相关问题 更多 >