# Dataclasses

> What are Python dataclasses? How do they compare to regular classes and namedtuples?

Canonical: https://www.internhack.in/learn/interview/python-interview/python-dataclasses
Last updated: 2026-11-28

Difficulty: Intermediate

## Question

What are Python dataclasses? How do they compare to regular classes and namedtuples?

## Answer

@dataclass (Python 3.7+) automatically generates \__init_\_, \__repr_\_, \__eq_\_, and optionally \__lt_\_, \__hash_\_ based on class attributes.

Advantages over regular class:

- No boilerplate \__init_\_ with self.x = x
- Auto-generated \__repr_\_ and \__eq_\_
- Clean, declarative syntax with type annotations

Key parameters:

- frozen=True: makes instances immutable (generates \__hash_\_)
- order=True: generates \__lt_\_, \__le_\_, \__gt_\_, \__ge_\_
- slots=True (3.10+): generates \__slots_\_ for memory efficiency
- eq=False: skip \__eq_\_ generation

field() for defaults: use field(default_factory=list) for mutable defaults.

## Code examples

### Basic Dataclass

```
from dataclasses import dataclass, field
from typing import List

@dataclass
class Point:
    x: float
    y: float
    label: str = 'origin'

p1 = Point(1.0, 2.0)
p2 = Point(1.0, 2.0)
print(p1)            # Point(x=1.0, y=2.0, label='origin')
print(p1 == p2)      # True (auto __eq__)

# Mutable defaults must use field()
@dataclass
class Student:
    name: str
    grades: List[float] = field(default_factory=list)
    _id: int = field(default=0, repr=False, compare=False)

    def average(self):
        return sum(self.grades) / len(self.grades) if self.grades else 0

s = Student('Alice')
s.grades.extend([85, 90, 95])
print(s)              # Student(name='Alice', grades=[85, 90, 95])
print(s.average())    # 90.0
```

field(default_factory=list) is required for mutable defaults. repr=False and compare=False exclude \_id from \__repr_\_ and \__eq_\_.

### Frozen, Order, and \__post_init_\_

```
from dataclasses import dataclass
from math import sqrt

@dataclass(frozen=True, order=True)
class Version:
    major: int
    minor: int
    patch: int

    def __str__(self):
        return f'{self.major}.{self.minor}.{self.patch}'

v1 = Version(1, 2, 3)
v2 = Version(2, 0, 0)

try:
    v1.major = 99  # Raises FrozenInstanceError
except Exception as e:
    print(e)

print(v1 < v2)   # True (order=True)
print(sorted([v2, v1]))  # [Version(1,2,3), Version(2,0,0)]

# __post_init__ for derived fields
@dataclass
class Circle:
    radius: float
    area: float = field(init=False)

    def __post_init__(self):
        self.area = 3.14159 * self.radius  2

c = Circle(5)
print(c.area)  # 78.53975
```

frozen=True makes instances hashable and usable as dict keys or in sets. \__post_init_\_ computes derived fields after \__init_\_ runs.

## Key points

- field(default_factory=list) prevents the mutable default argument bug
- frozen=True sets \__hash_\_; without it, mutable dataclasses are unhashable (hash=None)
- slots=True (Python 3.10+) adds \__slots_\_ automatically - reduces memory by ~40%
- Pydantic's BaseModel is a more powerful alternative for validation and serialization

## Common follow-up questions

- What is the difference between @dataclass and Pydantic BaseModel?
- Why can't you use a mutable default value directly in a dataclass field?
- How does frozen=True affect hashability?

## Interview tips

- Show field(default_factory=list) - the mutable default bug is a classic interview question
- Mention frozen for immutable value objects and \__post_init_\_ for derived fields
- Compare to namedtuple: dataclass is mutable by default, has methods, more flexible

## Concepts covered

@dataclass, field(), frozen, post_init, slots

Previous: [Python vs Other Languages](https://www.internhack.in/learn/interview/python-interview/python-vs-others) · Next: [\__slots_\_ and Memory Optimization](https://www.internhack.in/learn/interview/python-interview/python-slots) · [All of Python Interview](https://www.internhack.in/learn/interview/python-interview)

## More Python Interview questions

- [@property and Descriptors](https://www.internhack.in/learn/interview/python-interview/python-property-descriptor)
- [Walrus Operator and Structural Pattern Matching](https://www.internhack.in/learn/interview/python-interview/python-walrus-operator)
- [Protocol and Structural Subtyping](https://www.internhack.in/learn/interview/python-interview/python-protocols)
- [concurrent.futures and Multiprocessing](https://www.internhack.in/learn/interview/python-interview/python-concurrent-futures)
- [Closures, LEGB Rule, and nonlocal](https://www.internhack.in/learn/interview/python-interview/python-closures-scope)
- [classmethod vs staticmethod](https://www.internhack.in/learn/interview/python-interview/python-classmethod-staticmethod)

## Related

- [Learn](https://www.internhack.in/learn)
- [Interview Prep](https://www.internhack.in/learn/interview)
- [Python Interview](https://www.internhack.in/learn/interview/python-interview)
