Search⌘ K
AI Features

namedtuple and dataclass

Explore how to use namedtuple and dataclass to define data-holding Python objects efficiently. Learn to replace verbose class code with automated methods, understand the differences in mutability and type hints, and choose the right approach for your data model design.

We have spent several lessons mastering classes, manually writing __init__, __repr__, and __eq__ methods. While this gives us total control, it becomes tedious when we simply want an object to hold data—like a coordinate, a database record, or a configuration setting. Python offers specialized tools that automate this work for us. In this lesson, we will evolve a single class, Point3D, moving from a verbose manual definition to modern, efficient data containers that write their own code.

The boilerplate problem

Classes used mainly to store data often repeat the same structure. This typically includes a constructor to set attributes, a string representation for readability, and an equality method for comparing instances. The following example shows the amount of code required to define a simple Point3D class using standard Python class syntax.

Python
class Point3D:
def __init__(self, x, y, z, label):
self.x = x
self.y = y
self.z = z
self.label = label
def __repr__(self):
return f"Point3D(x={self.x}, y={self.y}, z={self.z}, label='{self.label}')"
def __eq__(self, other):
if not isinstance(other, Point3D):
return NotImplemented
return (self.x, self.y, self.z, self.label) == (other.x, other.y, other.z, other.label)
# Creating and comparing instances
p1 = Point3D(10, 20, 30, "Origin")
p2 = Point3D(10, 20, 30, "Origin")
print(p1)
print(f"Points are equal: {p1 == p2}")
  • Lines 2–6: We define __init__. Its only purpose is to assign arguments to attributes, yet it takes five lines.

  • Lines 8–9: We manually define __repr__ so the object prints Point3D(...) instead of a cryptic memory address like <__main__.Point3D object at 0x104...>.

  • ...