What are Dataclasses?
A dataclass is a special type of class introduced in Python 3.7 (PEP 557) that automatically generates common methods for classes whose primary purpose is to store data. Instead of writing boilerplate methods like__init__(), __repr__(), and __eq__(), Python generates them automatically.
Import the dataclass decorator from the dataclasses module.
Why use Dataclasses?
Dataclasses help you:- Reduce boilerplate code
- Create clean, readable models
- Automatically generate constructors
- Automatically generate string representations
- Automatically compare objects
- Easily convert objects into dictionaries
Basic Example
Without Dataclass__init__()__repr__()__eq__()
Generated Methods
GivenFields
Every type-annotated attribute becomes a dataclass field.Default Values
Fields can have default values.Using default_factory
Never use mutable objects directly as defaults.
❌ Incorrect
Adding Methods
Dataclasses can contain normal methods.Immutable Dataclasses
Usefrozen=True to make objects immutable.
Ordering Support
<<=>>=
Useful Decorator Options
Example
Instance Variables vs Class Variables
Instance Variables
Type-annotated attributes become instance fields.Class Variables
UseClassVar.
school attribute is not part of the dataclass fields because it is marked as a ClassVar.
What happens without ClassVar?
school becomes an instance field and appears in the constructor and object representation.
Dataclass Utility Functions
asdict()
Convert a dataclass object into a dictionary.
astuple()
Convert to a tuple.
replace()
Create a modified copy.
Dataclass vs Pydantic BaseModel
Both are used for modeling structured data, but they serve different purposes.Type Validation
DataclassSerialization
DataclassValidation Errors
DataclassWhen to Use Dataclasses
Use dataclasses when:- Objects primarily hold data.
- Validation is unnecessary.
- The data is created within your application.
- Performance and simplicity are important.
- Building internal domain or business models.
- Product
- Employee
- Student
- Point
- Configuration objects
- Domain entities
When to Use Pydantic BaseModel
Use BaseModel when:- Accepting external input.
- Building REST APIs.
- Reading JSON data.
- Parsing configuration files.
- Validating user input.
- Returning API responses.
- Request models
- Response models
- Configuration settings
- API payloads
Summary
Rule of Thumb
- Dataclass → “I already trust the data; I just need a convenient container.”
- Pydantic BaseModel → “I don’t trust the data yet; validate and parse it before using it.”