Python Dataclasses

Learn Python Dataclasses with practical examples, explanations, best practices, and real-world coding techniques.

Python dataclasses provide a convenient way to define classes that primarily store structured data. Instead of repeatedly writing boilerplate methods such as __init__(), __repr__(), and __eq__(), the @dataclass decorator can generate much of that code automatically.

Dataclasses are especially useful for models, configuration objects, request data, application state, value objects, and other structures where the relationship between fields is more important than a large amount of custom behavior. They keep the class definition compact while still giving you control over comparison, mutability, defaults, representation, and other behaviors.

What You Will Learn

  • How the @dataclass decorator works
  • How dataclasses generate constructors and representations
  • How default values and default_factory work
  • How field() controls individual fields
  • How frozen dataclasses provide immutable-style objects
  • How __post_init__ can validate or derive values
  • How dataclass inheritance works
  • How asdict(), astuple(), replace(), and other helpers work
  • How to choose between a dataclass and a regular class

What Is a Dataclass?

A dataclass is a regular Python class enhanced by the dataclasses module. You define fields using type annotations, and the @dataclass decorator can generate common methods based on those fields.

from dataclasses import dataclass


@dataclass
class User:
    name: str
    age: int


user = User("Alex", 25)

print(user)
print(user.name)
print(user.age)

Without manually writing an __init__() method, the dataclass can create a constructor matching the declared fields. It also provides a useful string representation for the object.

Why Use Dataclasses?

A traditional data-oriented class often contains repetitive initialization and representation code. Dataclasses reduce that boilerplate while preserving the ability to add normal methods when behavior is required.

class User:
    def __init__(self, name: str, age: int):
        self.name = name
        self.age = age

    def __repr__(self):
        return (
            f"User(name={self.name!r}, "
            f"age={self.age!r})"
        )

The dataclass version is much smaller:

from dataclasses import dataclass


@dataclass
class User:
    name: str
    age: int

This makes dataclasses a good fit when most of the class consists of data fields and straightforward object behavior.

How @dataclass Works

The @dataclass decorator examines the class annotations and generates methods according to its configuration. By default, a dataclass generates an initializer, a representation method, and equality behavior.

from dataclasses import dataclass


@dataclass
class Product:
    name: str
    price: float


first = Product("Keyboard", 2500)
second = Product("Keyboard", 2500)

print(first)
print(first == second)

The generated equality behavior compares the dataclass fields rather than simply checking whether both variables refer to the exact same object.

Generated __init__()

Type annotations become dataclass fields, and those fields are normally included in the generated constructor in declaration order.

from dataclasses import dataclass


@dataclass
class Product:
    name: str
    price: float
    stock: int


product = Product(
    "Monitor",
    15000,
    10
)

print(product)

You can also use keyword arguments, which can make object creation clearer when a class contains several fields.

product = Product(
    name="Monitor",
    price=15000,
    stock=10
)

Default Values

Dataclass fields can have default values. Fields without defaults should generally appear before fields with defaults, just as they would in a normal Python function signature.

from dataclasses import dataclass


@dataclass
class User:
    name: str
    active: bool = True
    role: str = "user"


first = User("Alex")

print(first)

second = User(
    name="Sam",
    active=False,
    role="admin"
)

print(second)

Default values make optional configuration explicit and remove the need to write repetitive constructor logic.

Mutable Defaults and default_factory

A common mistake is using a mutable object such as a list directly as a field default. Instead, use field(default_factory=...) to create a fresh object for each instance.

from dataclasses import dataclass, field


@dataclass
class Team:
    name: str
    members: list[str] = field(
        default_factory=list
    )


first = Team("Backend")
second = Team("Frontend")

first.members.append("Alex")

print(first.members)
print(second.members)

The factory is called separately for each object, so every Team receives its own list.

Using field()

The field() function provides more control over individual dataclass fields. It can configure defaults, factories, representation, comparisons, initialization, and keyword-only behavior.

from dataclasses import dataclass, field


@dataclass
class User:
    username: str
    password_hash: str = field(repr=False)


user = User(
    "alex",
    "hidden-hash"
)

print(user)

The repr=False option prevents that field from appearing in the generated representation. This can be useful for sensitive or noisy values.

Controlling Equality with compare

By default, dataclass fields participate in generated equality comparisons. You can exclude a field from comparison with compare=False when that field should not determine whether two instances are considered equal.

from dataclasses import dataclass, field


@dataclass
class Product:
    product_id: int
    name: str
    cached_price: float = field(
        compare=False,
        default=0.0
    )


first = Product(1, "Keyboard", 2500)
second = Product(1, "Keyboard", 3000)

print(first == second)

Here, the cached price does not participate in equality, so objects with the same identity fields and name can compare equal even when their cached price differs.

Frozen Dataclasses

Passing frozen=True creates a dataclass that prevents normal attribute assignment and deletion after initialization.

from dataclasses import dataclass


@dataclass(frozen=True)
class User:
    name: str
    active: bool = True


user = User("Alex")

print(user)

# user.name = "Sam"

Attempting to assign to a field on the frozen instance raises an exception. Frozen dataclasses are useful for value-like objects and state that should not be reassigned after construction.

Frozen Does Not Automatically Make Nested Data Immutable

A frozen dataclass prevents assignment to its own fields, but objects stored inside those fields may still be mutable.

from dataclasses import dataclass, field


@dataclass(frozen=True)
class Team:
    members: list[str] = field(
        default_factory=list
    )


team = Team()

team.members.append("Alex")

print(team.members)

The field reference cannot be reassigned, but the list itself remains mutable. Full immutability requires immutable values to be used inside the object as well.

The __post_init__ Method

A dataclass can define __post_init__() for additional initialization or validation after the generated __init__() has run.

from dataclasses import dataclass


@dataclass
class Product:
    name: str
    price: float

    def __post_init__(self):
        if self.price < 0:
            raise ValueError(
                "Price cannot be negative"
            )


product = Product("Keyboard", 2500)

print(product)

This keeps validation close to the model while allowing the dataclass to continue generating the normal constructor.

Derived Fields

A field can also be calculated from other fields during __post_init__(). Use field(init=False) when the derived value should not be provided by the caller.

from dataclasses import dataclass, field


@dataclass
class Order:
    price: float
    quantity: int
    total: float = field(init=False)

    def __post_init__(self):
        self.total = self.price * self.quantity


order = Order(250, 3)

print(order.total)

The caller provides price and quantity, while the dataclass derives the total internally.

InitVar

Sometimes a value is needed during initialization but should not become a normal dataclass field. The InitVar type can be used for this purpose.

from dataclasses import dataclass, InitVar


@dataclass
class User:
    username: str
    password: InitVar[str]

    def __post_init__(self, password):
        if len(password) < 8:
            raise ValueError(
                "Password must contain at least 8 characters"
            )


user = User(
    username="alex",
    password="secure-password"
)

print(user)

The password value is passed to initialization and __post_init__(), but it is not stored as a normal dataclass field.

ClassVar and Dataclasses

A ClassVar annotation can identify an attribute as a class-level value rather than a dataclass field.

from dataclasses import dataclass
from typing import ClassVar


@dataclass
class Employee:
    company: ClassVar[str] = "IgKnight"

    name: str
    role: str


employee = Employee(
    name="Alex",
    role="Developer"
)

print(employee)
print(Employee.company)

The company attribute is not treated as an instance field by the dataclass.

Keyword-Only Fields

Dataclasses can make fields keyword-only. This can improve readability when a class contains several optional values or when positional arguments could easily be confused.

from dataclasses import dataclass, field


@dataclass
class User:
    name: str
    age: int
    active: bool = field(
        default=True,
        kw_only=True
    )


user = User(
    "Alex",
    25,
    active=False
)

print(user)

The active field must be supplied by keyword when explicitly provided.

Slots with Dataclasses

Dataclasses can also be configured with slots=True to generate a slotted class layout. Slots can be useful when many small instances are created and the design does not require arbitrary instance attributes.

from dataclasses import dataclass


@dataclass(slots=True)
class Point:
    x: float
    y: float


point = Point(10, 20)

print(point)
print(point.x)

Slotted dataclasses are an advanced option. Use them when their memory or attribute-layout characteristics are useful for the application's workload rather than adding them automatically to every model.

Dataclass Methods

A dataclass is still a normal Python class. You can add methods when the object needs behavior in addition to its data.

from dataclasses import dataclass


@dataclass
class Rectangle:
    width: float
    height: float

    def area(self) -> float:
        return self.width * self.height

    def perimeter(self) -> float:
        return 2 * (self.width + self.height)


rectangle = Rectangle(10, 5)

print(rectangle.area())
print(rectangle.perimeter())

Dataclasses are therefore not limited to passive data containers. They are useful for classes where fields and relatively focused behavior belong together.

Dataclass Inheritance

Dataclasses can participate in inheritance. A child dataclass can add fields to a parent dataclass and inherit its generated behavior.

from dataclasses import dataclass


@dataclass
class Person:
    name: str
    age: int


@dataclass
class Developer(Person):
    language: str


developer = Developer(
    name="Alex",
    age=25,
    language="Python"
)

print(developer)

The child contains the parent fields along with its own additional field. As with normal class inheritance, constructor design should be considered carefully when defaults or custom initialization are involved.

Dataclass Conversion Helpers

The dataclasses module includes helpers for converting and copying dataclass instances. Common functions include asdict(), astuple(), and replace().

asdict()

from dataclasses import dataclass, asdict


@dataclass
class User:
    name: str
    age: int


user = User("Alex", 25)

data = asdict(user)

print(data)

asdict() recursively converts dataclass instances into dictionaries, making it useful when preparing structured data for serialization or other processing.

astuple()

from dataclasses import dataclass, astuple


@dataclass
class Point:
    x: int
    y: int


point = Point(10, 20)

print(astuple(point))

replace()

from dataclasses import dataclass, replace


@dataclass
class User:
    name: str
    active: bool = True


first = User("Alex")

second = replace(
    first,
    active=False
)

print(first)
print(second)

replace() creates a new dataclass instance with selected field values changed. This is particularly useful with immutable-style models.

Ordering Dataclasses

A dataclass can optionally generate ordering methods when order=True is appropriate for the model. The generated comparisons use the fields participating in comparison.

from dataclasses import dataclass


@dataclass(order=True)
class Score:
    points: int
    player: str


scores = [
    Score(80, "Alex"),
    Score(95, "Sam"),
    Score(70, "Ravi")
]

scores.sort()

for score in scores:
    print(score)

Ordering should only be enabled when the ordering semantics make sense for the domain. A sortable object is not automatically a meaningfully ordered object.

Equality, Hashing, and frozen

Dataclass configuration also affects how equality and hashing behave. Mutable objects should be designed carefully before being used as dictionary keys or set elements. A frozen dataclass provides an immutable-style model and can participate in hashing under appropriate dataclass configuration.

The important design question is whether the object's field values can change and whether equality represents value identity. Do not enable hashing simply because a class contains only a few fields.

A Practical API Model

Dataclasses are useful for request and response models because they make the expected shape of data easy to read.

from dataclasses import dataclass


@dataclass
class CreateUserRequest:
    username: str
    email: str
    active: bool = True


request = CreateUserRequest(
    username="alex",
    email="alex@example.com"
)

print(request)

The class clearly describes the expected values and provides a convenient constructor. Serialization to JSON or another transport format can then be handled by the application's chosen serialization layer.

Dataclasses for Configuration

Configuration objects are another good fit because they often contain a collection of related settings with defaults.

from dataclasses import dataclass


@dataclass
class AppConfig:
    host: str = "localhost"
    port: int = 8000
    debug: bool = False


config = AppConfig(
    port=9000,
    debug=True
)

print(config)

The configuration type makes supported settings explicit and reduces the need for loosely structured dictionaries throughout the application.

Dataclasses for Value Objects

A value object is typically identified by its values rather than by object identity. Dataclasses can represent these models particularly well because generated equality naturally compares their declared fields.

from dataclasses import dataclass


@dataclass(frozen=True)
class Money:
    amount: float
    currency: str


first = Money(100, "USD")
second = Money(100, "USD")

print(first == second)

The combination of value-based equality and frozen state can make a dataclass a natural representation for immutable-style value objects.

Dataclass vs Regular Class

Dataclass Regular Class
Excellent for structured data models. Useful when custom initialization or behavior dominates.
Reduces repetitive boilerplate. Provides complete control over generated behavior.
Provides configurable generated methods. Requires explicit implementation of those methods when needed.
Fields are explicit through annotations. Can support designs that do not fit a field-oriented model.

Common Dataclass Mistakes

Mutable Default Values

Use default_factory for mutable defaults such as lists, sets, and dictionaries instead of sharing one mutable object across instances.

Using Dataclasses for Complex Behavior

A regular class may be clearer when construction, lifecycle, or domain behavior is much more complex than the data model itself.

Incorrect Equality Semantics

Generated equality compares fields. Make sure that field-based equality actually represents the identity or value semantics required by the domain.

Blindly Using frozen=True

Frozen objects are useful when immutability is part of the design, but not every data model needs to be immutable.

Best Practices for Python Dataclasses

  • Use dataclasses when a class primarily represents structured data and value-oriented behavior.
  • Give fields clear type annotations and meaningful names.
  • Use field(default_factory=...) for mutable defaults.
  • Use __post_init__() for validation or derived initialization that belongs to the model.
  • Use frozen=True when immutable-style behavior is a real requirement.
  • Use repr=False for fields that should not appear in generated representations.
  • Use compare=False when a field should not participate in generated equality or ordering comparisons.
  • Use ClassVar for class-level values that should not become dataclass fields.
  • Use InitVar when a value is needed during initialization but should not be stored as a field.
  • Do not use dataclass features simply because they exist; choose configuration that reflects the domain semantics.

Practical Example: User Model

The following example combines several common dataclass features: default values, a generated identifier, validation, and controlled representation.

from dataclasses import dataclass, field


@dataclass
class User:
    username: str
    email: str
    active: bool = True
    roles: list[str] = field(
        default_factory=list,
        repr=True
    )

    def __post_init__(self):
        if not self.username.strip():
            raise ValueError(
                "Username cannot be empty"
            )

        if "@" not in self.email:
            raise ValueError(
                "Email must contain @"
            )

    def add_role(self, role: str) -> None:
        if role not in self.roles:
            self.roles.append(role)


user = User(
    username="alex",
    email="alex@example.com"
)

user.add_role("developer")

print(user)

The dataclass removes repetitive constructor and representation code while still allowing the model to contain validation and domain behavior. This is an important point: using @dataclass does not prevent you from writing normal methods.

When Should You Use Dataclasses?

Dataclasses are a strong choice when the primary responsibility of a class is to represent structured information and the generated behavior matches the semantics you need.

  • Configuration objects
  • Request and response models
  • Value objects
  • Application state
  • Parsed structured data
  • Simple domain entities with focused behavior

A normal class is often more appropriate when the object's lifecycle, construction logic, inheritance behavior, or internal state management is complex enough that the generated dataclass behavior becomes restrictive or confusing.

Interview Questions to Prepare

  • What is a Python dataclass?
  • What does the @dataclass decorator generate?
  • What is the difference between a dataclass and a regular Python class?
  • Why should default_factory be used for mutable default values?
  • What is field() used for?
  • What does frozen=True do?
  • What is __post_init__() used for?
  • What are InitVar and ClassVar?
  • How do asdict(), astuple(), and replace() work?
  • When should you avoid using a dataclass?

Summary

Python dataclasses reduce boilerplate when building classes that primarily represent structured data. With @dataclass, Python can generate common methods while allowing developers to customize individual fields and object behavior.

Features such as default_factory, field(), frozen=True, __post_init__(), InitVar, ClassVar, and helper functions such as asdict() make dataclasses flexible enough for many real-world models. The key is to use them where their generated semantics match the domain rather than treating them as a replacement for every regular Python class.

Code Examples

Basic Dataclass

python
from dataclasses import dataclass


@dataclass
class User:
    name: str
    age: int


user = User("Alex", 25)

print(user)
print(user.name)
print(user.age)
    

default_factory for Mutable Fields

python
from dataclasses import dataclass, field


@dataclass
class Team:
    name: str
    members: list[str] = field(
        default_factory=list
    )


first = Team("Backend")
second = Team("Frontend")

first.members.append("Alex")

print(first.members)
print(second.members)
    

Frozen Dataclass

python
from dataclasses import dataclass


@dataclass(frozen=True)
class User:
    name: str
    active: bool = True


user = User("Alex")

print(user)

# Attribute reassignment is not allowed
# user.name = "Sam"
    

Validation with __post_init__

python
from dataclasses import dataclass


@dataclass
class Product:
    name: str
    price: float

    def __post_init__(self):
        if self.price < 0:
            raise ValueError(
                "Price cannot be negative"
            )


product = Product(
    "Keyboard",
    2500
)

print(product)
    

Dataclass Conversion

python
from dataclasses import (
    dataclass,
    asdict,
    replace
)


@dataclass
class User:
    name: str
    active: bool = True


user = User("Alex")

data = asdict(user)

updated_user = replace(
    user,
    active=False
)

print(data)
print(updated_user)
    

Pro Tip

Use dataclasses when the class is primarily a structured data model. Prefer default_factory for mutable fields, use frozen=True for value-like immutable models, and use __post_init__() for validation or derived initialization.

More Python lessons

🎨 IgKnight Docs

Master HTML, CSS, JS, Python, .NET and more with easy-to-follow lessons and practical code examples.

© 2025 IgKnight Learning Platform. All rights reserved.