collections. namedtuple
Creates tuples with named fields: you read data with student.points instead of student[2], and the object stays immutable.
- Returns
- A new class that inherits from
tuple.
Example
#from collections import namedtuple
Student = namedtuple("Student", ["name", "world", "points"])
emma = Student("Emma", 7, 250)
print(emma)
print(emma.name, emma.points)
print(emma[1], len(emma))
name, world, points = emma
print(f"{name} is in world {world}")Definition and usage
#The namedtuple() function from the collections module creates a new class of tuples in which every field has a name. Instead of remembering that in the tuple ("Emma", 7, 250) the points are at index 2, you write student.points. The objects are still ordinary tuples, so indexing, unpacking, comparing, and len() all work.
Like any tuple, the object is immutable: assigning to a field raises AttributeError. A new version with a changed field is created by the _replace() method, and _asdict() turns the object into a dictionary. The _fields attribute holds the field names, and _make() creates an object from any sequence, e.g. a row from a CSV file. The underscore in these names does not mean they are private, it just prevents conflicts with the names of your fields.
A more modern notation is a class that inherits from typing.NamedTuple, in which fields are declared with type annotations, similar to @dataclass. When you need an object whose fields can change, choose @dataclass.
Syntax
#from collections import namedtuple
Name = namedtuple("Name", ["field1", "field2"], defaults=None)
obj = Name(value1, value2)
obj.field1
obj._replace(field1=new_value)
obj._asdict()Parameters
#typename
str
The name of the new class, visible inrepr()among other places. Usually the same as the variable name.field_names
list of strings or a string
The field names, e.g.["x", "y"]or"x y".defaults
sequence, optional
Default values for the last fields.
More examples
#from collections import namedtuple
Student = namedtuple("Student", "name points level", defaults=[1])
jack = Student("Jack", 80)
print(jack)
try:
jack.points = 120
except AttributeError:
print("The field cannot be changed")
promoted = jack._replace(points=120, level=2)
print(promoted)
print(promoted._asdict())
print(Student._fields)from typing import NamedTuple
class Point(NamedTuple):
x: float
y: float = 0.0
def distance(self):
return (self.x ** 2 + self.y ** 2) ** 0.5
p = Point(3, 4)
print(p, p.distance())
print(Point(1.5))
print(sorted([Point(2, 1), Point(1, 5), Point(1, 2)]))Annotations do not convert types: Point(3, 4) stores integers. Sorting compares the fields one by one, as in ordinary tuples.
import csv
from collections import namedtuple
lines = ["name,world,points", "Emma,7,250", "Jack,2,80"]
reader = csv.reader(lines)
Row = namedtuple("Row", next(reader))
for row in map(Row._make, reader):
print(row.name, int(row.points))Good practices
#- The methods
_replace(),_asdict(), and_make()are public despite the underscore. The underscore protects against a conflict with the names of your fields. - A namedtuple works well for returning several values from a function: you unpack the result like a tuple or read it by field names.
- If fields need to change, or the class needs many methods, use
@dataclass.
Related entries
#- namedtuple vs dataclassnamedtuple creates an immutable, lightweight tuple with named fields, while @dataclass creates an ordinary, mutable class with a generated __init__, __repr__, and __eq__.
- tuple()Creates a tuple: an immutable sequence of items.
- Unpacking sequencesAssigning the items of a tuple or list to several variables at once.
- @dataclassA decorator that generates __init__, __repr__, and __eq__ for a data-storing class, based on type-annotated fields.
- typingType annotations: a description of what values a function expects and what it returns. Checked by editors and tools such as mypy.
- csvReading and writing CSV files, that is tables saved as text in which values are separated by a comma or a semicolon.
Spotted a mistake or missing an example? Write to us.