Junior — Middle
What are the main differences between dataclass and namedtuple in Python, and in which cases are they preferable?
sobes.tech AI
Answer from AI
dataclass and namedtuple in Python are used for creating simple classes to store data, but they have different features:
-
namedtuple is an immutable tuple with named fields. It is lightweight and memory-efficient but does not allow changing values after creation.
-
dataclass is a class that automatically generates methods (
__init__,__repr__,__eq__, etc.) and supports mutability by default. You can specify field types, default values, and also use additional features like methods and inheritance.
When to use:
namedtupleis suitable if you need a simple, immutable data structure with minimal overhead.dataclassis preferable if you need mutability, more complex logic, methods, or ease of working with types.
Example of namedtuple:
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(1, 2)
Example of dataclass:
from dataclasses import dataclass
@dataclass
class Point:
x: int
y: int
p = Point(1, 2)
p.x = 3 # mutable field