Sobes.tech
Junior — Middle

What common features do dataclass and namedtuple in Python share?

sobes.tech AI

Answer from AI

Both dataclass and namedtuple in Python are used for convenient storage of data with named fields. Common features:

  • Both allow creating objects with a fixed set of fields.
  • Fields are accessible by name, which improves code readability.
  • Both automatically implement methods for easy data access (e.g., __repr__ for pretty printing).
  • They are used for structuring data without the need to write a lot of boilerplate code.

Example of usage:

from dataclasses import dataclass
from collections import namedtuple

PointDataClass = dataclass(type('PointDataClass', (), {}))

@dataclass
class PointDC:
    x: int
    y: int

PointNT = namedtuple('PointNT', ['x', 'y'])

p1 = PointDC(1, 2)
p2 = PointNT(1, 2)

print(p1.x, p1.y)  # 1 2
print(p2.x, p2.y)  # 1 2

Both options are convenient for storing simple data structures.

What common features do dataclass and namedtuple in… - sobes.tech