Python 3.5 typed NamedTuple syntax produces SyntaxError

依然范特西╮ 提交于 2019-11-28 03:17:51

问题


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

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

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.


回答1:


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.

From the typing.NamedTuple documentation:

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

Use the backwards compatible syntax also included in the documentation:

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

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

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).



来源:https://stackoverflow.com/questions/42002596/python-3-5-typed-namedtuple-syntax-produces-syntaxerror

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!