Skip to main content

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
With Dataclass
Output
Python automatically generates:
  • __init__()
  • __repr__()
  • __eq__()

Generated Methods

Given
Python roughly creates

Fields

Every type-annotated attribute becomes a dataclass field.
Each object stores its own copy of these fields.

Default Values

Fields can have default values.

Using default_factory

Never use mutable objects directly as defaults. ❌ Incorrect
All objects share the same list. ✅ Correct
Each object gets a separate list.

Adding Methods

Dataclasses can contain normal methods.

Immutable Dataclasses

Use frozen=True to make objects immutable.
Attempting to modify an attribute raises an error.

Ordering Support

Python automatically generates comparison methods like
  • <
  • <=
  • >
  • >=

Useful Decorator Options

Example

Instance Variables vs Class Variables

Instance Variables

Type-annotated attributes become instance fields.
Each object has its own values.

Class Variables

Use ClassVar.
Usage
Output
Notice
Output
The school attribute is not part of the dataclass fields because it is marked as a ClassVar.

What happens without ClassVar?

Now school becomes an instance field and appears in the constructor and object representation.

Dataclass Utility Functions

asdict()

Convert a dataclass object into a dictionary.
Output

astuple()

Convert to a tuple.
Output

replace()

Create a modified copy.

Dataclass vs Pydantic BaseModel

Both are used for modeling structured data, but they serve different purposes.

Type Validation

Dataclass
Output
Dataclasses do not validate or convert types. Pydantic BaseModel
Output
Pydantic automatically validates and converts the value to the declared type.

Serialization

Dataclass
Pydantic BaseModel

Validation Errors

Dataclass
No error is raised during object creation because type hints are not enforced at runtime. Pydantic
Raises
with detailed information about the invalid field.

When 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.
Examples:
  • 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.
Examples:
  • 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.”