Sobes.tech
Middle
226

What are the similarities and differences between dataclasses and namedtuple?

Answer from AI

sobes.tech AI

dataclasses and namedtuple are used for creating simple data structures where the main goal is to store data and access it by name.

Similarities:

  • Allow creating classes with clearly defined fields.
  • Provide access to fields by name (e.g., obj.field).
  • Automatically generate __repr__ methods for convenient string representation.
  • Support unpacking.

Differences:

Difference collections.namedtuple dataclasses.dataclass
Mutability Immutable type Mutable by default, can be made immutable (frozen=True)
Type annotations Optional, based on type hints Mandatory, based on type annotations
Inheritance Tuple-based, hard to extend Full-fledged classes, support inheritance
Functionality Only data storage, simple repr More features: automatic __init__, __eq__, __hash__, __order__, default values for fields, post-initialization (__post_init__)
Python version Available in Python 2 and 3 Available from Python 3.7 onwards
Syntax Function returning a class @dataclass decorator

Examples:

# namedtuple
from collections import namedtuple

PointNT = namedtuple('PointNT', ['x', 'y'])
p1 = PointNT(1, 2)
# p1.x = 10 # Will raise an error because it is immutable

print(p1)
# dataclass
from dataclasses import dataclass, field

@dataclass
class PointDC:
    x: int
    y: int = 0 # Field with default value
    z: int = field(init=False) # Field not initialized automatically

    def __post_init__(self):
        self.z = self.x + self.y

p2 = PointDC(1)
print(p2)

p2.y = 5 # Mutable by default
print(p2)

# To create an immutable dataclass
@dataclass(frozen=True)
class ImmutablePoint:
    x: int
    y: int

p3 = ImmutablePoint(3, 4)
# p3.x = 10 # Will raise an error
print(p3)