Advertisement
Beginner Python, Dataclasses & NamedTuples

What does the @dataclass decorator automatically generate for a class?

Short answer

@dataclass automatically generates __init__ (accepting each declared field as a parameter), __repr__ (a readable string representation), and __eq__ (comparing all fields for equality) based on the class's type-annotated attributes, eliminating boilerplate you'd otherwise write…

Save Python mock interview
Advertisement
AModel answer
@dataclass automatically generates __init__ (accepting each declared field as a parameter), __repr__ (a readable string representation), and __eq__ (comparing all fields for equality) based on the class's type-annotated attributes, eliminating boilerplate you'd otherwise write by hand.
from dataclasses import dataclass

@dataclass
class Point:
    x: int
    y: int

p1 = Point(1, 2)
print(p1)              # Point(x=1, y=2) -- auto-generated __repr__
print(p1 == Point(1, 2))  # True -- auto-generated __eq__
Real-world example
Quickly defining a simple data-holder class (like a Point or Config) without manually writing __init__ and __repr__.
Likely follow-ups
  • Does @dataclass generate an __init__ that supports default values for fields, similar to a regular function?
Related topics