Python 3.5 类型化 NamedTuple 语法产生 SyntaxError [英] Python 3.5 typed NamedTuple syntax produces SyntaxError

查看:50
本文介绍了Python 3.5 类型化 NamedTuple 语法产生 SyntaxError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试新的类型化命名元组语法时,出现 SyntaxError: invalid syntax 错误:

I get a SyntaxError: invalid syntax error when I try the new typed namedtuple syntax:

class Employee(NamedTuple):
    name: str
    id: int

在 Python 3.5.2 中,即使根据 文档 它应该是从 3.5+ 开始有效.我错过了什么吗?我已经从代码中的 typing 导入了 NamedTuple.

in Python 3.5.2 even though according to the documentation it should be valid from 3.5+ onwards. Am I missing something? I've imported NamedTuple from typing in the code.

推荐答案

声明您正在使用的 nameid 字段类型的语法需要 Python 3.6 或更高版本.Python 3.5 不支持所需的变量级类型提示.

The syntax to declare the types for the name and id fields you are using requires Python 3.6 or up. Python 3.5 does not support the variable-level type hints required.

来自 typing.NamedTuple 文档:

From the typing.NamedTuple documentation:

在 3.6 版中更改:添加了对 PEP 526 变量注释语法的支持.

Changed in version 3.6: Added support for PEP 526 variable annotation syntax.

使用文档中还包含的向后兼容语法:

Employee = NamedTuple('Employee', [('name', str), ('id', int)])

因此将字段名称列为 (name, type) 元组.

so listing the field names as (name, type) tuples.

如果您使用的是 Python 3.5,您可能需要切换到 Python 3.5 版本的文档 代替(左上角有一个选择器,或者您可以将 URL 中的 3 替换为 3.5).

If you are using Python 3.5, you may want to switch to the Python 3.5 version of the documentation instead (there is a selector in the top-left corner, or you can just replace the 3 in the URL with 3.5).

这篇关于Python 3.5 类型化 NamedTuple 语法产生 SyntaxError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆