Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 3.5 typed NamedTuple syntax produces SyntaxError

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.

like image 787
daj Avatar asked Feb 02 '17 12:02

daj


People also ask

What is a Namedtuple in Python?

Python's namedtuple() is a factory function available in collections . It allows you to create tuple subclasses with named fields. You can access the values in a given named tuple using the dot notation and the field names, like in obj. attr .

What does Namedtuple Python return?

The namedtuple is a function that returns a new named tuple class. In other words, the namedtuple() is a class factory. The namedtuple function accepts the following arguments to generate a class: A class name that specifies the name of the named tuple class.

How do I change Namedtuple value?

Since a named tuple is a tuple, and tuples are immutable, it is impossible to change the value of a field. In this case, we have to use another private method _replace() to replace values of the field. The _replace() method will return a new named tuple.

Is Namedtuple immutable?

Named Tuple Python's tuple is a simple data structure for grouping objects with different types. Its defining feature is being immutable. An immutable object is an object whose state cannot be modified after it is created.


1 Answers

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

like image 142
Martijn Pieters Avatar answered Oct 06 '22 15:10

Martijn Pieters