Python dataclasses remove the most boring part of writing classes: the __init__ that copies every argument to self, the __repr__ you only remember to write after a confusing log line, and the __eq__ that compares objects by value. You list the fields with type hints, add @dataclass, and the standard library generates those methods for you. This guide goes past the basics into the parts that matter in real projects: safe defaults, validation, immutable value objects, memory-lean classes with slots, keyword-only fields, inheritance, JSON round trips and when a dataclass is the wrong tool. Every example was run on Python 3.13; examples that need Python 3.10 or newer are marked.

Python dataclasses overview: type-annotated fields become a generated __init__, __repr__ and __eq__, with options for defaults, validation, frozen objects, slots and JSON conversion
What the @dataclass decorator generates from type-annotated fields, and the options that change its behaviour.

From my own work: In code reviews, the biggest win from dataclasses is not fewer lines. It is replacing loose dictionaries that travel between functions, where nobody knows which keys exist, with a named type that an editor can autocomplete and a type checker can verify. Most of the bugs I find in dictionary-heavy code are misspelled or missing keys.

The basics: what @dataclass generates

A dataclass is a normal class. The decorator reads the class attributes that have type annotations, in order, and uses them as fields:

from dataclasses import dataclass

@dataclass
class Product:
    name: str
    price: float
    quantity: int = 0

    def total(self) -> float:
        return self.price * self.quantity

p = Product("Keyboard", 49.5, 2)
print(p)                                  # Product(name='Keyboard', price=49.5, quantity=2)
print(p.total())                          # 99.0
print(p == Product("Keyboard", 49.5, 2))  # True: fields are compared, not identity

From those three lines of fields, Python generated:

  • __init__(self, name, price, quantity=0) with parameters in field order.
  • __repr__ that prints the class name and every field, which makes logs and debugger output readable.
  • __eq__ that compares the fields as a tuple, so two products with the same values are equal.

The type hints are not enforced at runtime: Product("Keyboard", "cheap") runs without error. They document intent and let tools such as mypy, Pyright and your editor catch mistakes before the code runs. The full list of generated methods and decorator parameters is in the dataclasses documentation, and the design reasoning is in PEP 557.

Defaults and the mutable default trap

Fields with defaults must come after fields without them, exactly like function parameters. Immutable defaults such as numbers, strings, None and tuples can be written directly. Lists, dicts and sets cannot, because one object would be shared by every instance. Dataclasses refuse them outright and point you to default_factory:

from dataclasses import dataclass, field

try:
    @dataclass
    class BadCart:
        items: list = []
except ValueError as err:
    print(err)  # mutable default <class 'list'> for field items is not allowed: use default_factory

@dataclass
class Cart:
    owner: str
    items: list[str] = field(default_factory=list)
    meta: dict[str, str] = field(default_factory=dict)

a, b = Cart("ana"), Cart("ben")
a.items.append("mouse")
print(a.items, b.items)  # ['mouse'] []  -> every instance gets its own list

default_factory takes any zero-argument callable and calls it for each new instance. Use list, dict, set or a lambda, for example field(default_factory=lambda: ["en"]) for a non-empty default.

Field options: repr, compare and init

field() controls how each field takes part in the generated methods. The three options used most often are hiding secrets from repr, excluding bookkeeping values from equality and computing a field instead of accepting it as a parameter. __post_init__ runs right after the generated __init__, which makes it the place for normalisation and validation:

from dataclasses import dataclass, field

@dataclass
class User:
    email: str
    password_hash: str = field(repr=False)              # never printed in logs
    login_count: int = field(default=0, compare=False)  # ignored by ==
    domain: str = field(init=False)                     # computed, not a parameter

    def __post_init__(self):
        self.email = self.email.strip().lower()
        if "@" not in self.email:
            raise ValueError(f"invalid email: {self.email!r}")
        self.domain = self.email.split("@", 1)[1]

u = User("  Ana@Example.COM ", "$2y$12$abc")
print(u)          # User(email='ana@example.com', login_count=0, domain='example.com')
print(u == User("ana@example.com", "$2y$12$abc", login_count=7))  # True

try:
    User("not-an-email", "x")
except ValueError as err:
    print(err)    # invalid email: 'not-an-email' 
Option Default Effect Typical use
default / default_factory none Value when the argument is omitted Counters, empty lists, timestamps
repr=False True Field left out of repr() Password hashes, tokens, large blobs
compare=False True Ignored by == and ordering Caches, counters, timestamps
init=False True Not an __init__ parameter Values derived in __post_init__
kw_only=True False Keyword-only parameter (3.10+) Optional settings
metadata empty Free-form mapping for your own tools Column names, help text

Keep __post_init__ small. It is good for checks that make an invalid object impossible to build, such as a missing @ or a negative quantity. It is the wrong place for network calls or database lookups, because constructing an object should stay cheap and predictable.

Immutable value objects with frozen=True

frozen=True makes assignment to any field raise FrozenInstanceError. Combined with the default eq=True, Python also generates __hash__, so frozen instances can be dictionary keys and set members. That is a good fit for money, coordinates, date ranges and cache keys:

from dataclasses import dataclass, replace, FrozenInstanceError

@dataclass(frozen=True)
class Money:
    amount: int            # store cents, never floats, for money
    currency: str = "USD"

    def __post_init__(self):
        # frozen blocks normal assignment, so normalise through object.__setattr__
        object.__setattr__(self, "currency", self.currency.upper())

    def __add__(self, other: "Money") -> "Money":
        if self.currency != other.currency:
            raise ValueError("currency mismatch")
        return Money(self.amount + other.amount, self.currency)

price = Money(1999, "usd")
try:
    price.amount = 0
except FrozenInstanceError as err:
    print("blocked:", err)              # blocked: cannot assign to field 'amount'

print(price + Money(1))                 # Money(amount=2000, currency='USD')
print(replace(price, currency="eur"))   # Money(amount=1999, currency='EUR')
print({price: "list price"}[Money(1999)])  # list price  -> frozen + eq means hashable
  • Change a frozen object by making a new one. dataclasses.replace(obj, field=value) copies every field and overrides the ones you name. It also runs __post_init__ again, which is why the currency above is upper-cased in the copy too.
  • On Python 3.13 the general copy.replace() function does the same for dataclasses, named tuples and other supporting types (copy.replace).
  • Frozen is shallow. A frozen dataclass holding a list still lets you call .append() on that list. Use tuples or frozenset inside value objects.

Sorting with order=True

order=True adds <, <=, > and >=, which compare fields as a tuple in declaration order. Put the sort key first and exclude the rest with compare=False:

from dataclasses import dataclass, field

@dataclass(order=True)
class Job:
    priority: int
    created: int
    name: str = field(compare=False)   # not part of the sort key

jobs = [Job(2, 105, "resize images"), Job(1, 110, "send invoices"), Job(2, 101, "rebuild sitemap")]
for job in sorted(jobs):
    print(job.priority, job.created, job.name)
# 1 110 send invoices
# 2 101 rebuild sitemap
# 2 105 resize images

This works nicely with heapq for priority queues. If you need several different orderings, skip order=True and pass key= to sorted() instead.

slots=True and kw_only=True (Python 3.10+)

Python 3.10 added two decorator flags that are worth using in most new code (What is new in Python 3.10). slots=True generates __slots__, so instances have no per-object __dict__: they use less memory, attribute access is slightly faster, and a misspelled attribute assignment raises an error instead of silently creating a new attribute. kw_only=True makes every field keyword-only, which keeps call sites readable when a class has many optional settings:

# Python 3.10+
from dataclasses import dataclass, field, KW_ONLY

@dataclass(slots=True, kw_only=True)
class DbConfig:
    host: str
    port: int = 5432
    user: str = "app"
    debug: bool = False

cfg = DbConfig(host="db.internal", debug=True)
print(cfg)                    # DbConfig(host='db.internal', port=5432, user='app', debug=True)
print(hasattr(cfg, "__dict__"))   # False: attributes live in fixed slots

try:
    cfg.prot = 6432           # typo
except AttributeError as err:
    print("typo caught:", err)   # 'DbConfig' object has no attribute 'prot' ...

try:
    DbConfig("db.internal")   # positional call rejected
except TypeError as err:
    print(err)                # DbConfig.__init__() takes 1 positional argument but 2 were given

@dataclass
class Point:
    x: float
    y: float
    _: KW_ONLY                # everything after this marker is keyword-only
    label: str = ""

print(Point(1, 2, label="A"))  # Point(x=1, y=2, label='A')

The KW_ONLY marker gives you a mix: fields before it stay positional, fields after it must be passed by name. Two cautions for slots=True: the decorator returns a new class, so code that relies on adding attributes dynamically will break, and using a bare super() call inside the methods of a slotted dataclass raises a TypeError on Python 3.13 and earlier; call the parent class explicitly there, for example object.__repr__(self), if you need it.

Inheritance and the default-argument error

A subclass of a dataclass appends its fields after the parent’s fields. If the parent has a field with a default, every new field in the child also needs a default, or the generated __init__ would be invalid. On Python 3.10 and newer the clean fix is to make the child’s fields keyword-only:

from dataclasses import dataclass

@dataclass
class Base:
    id: int
    active: bool = True

try:
    @dataclass
    class Customer(Base):
        name: str             # no default after a default -> error
except TypeError as err:
    print(err)                # non-default argument 'name' follows default argument ...

@dataclass(kw_only=True)      # Python 3.10+: fix by making the new fields keyword-only
class Customer(Base):
    name: str
    tier: str = "free"

print(Customer(7, name="Ana"))  # Customer(id=7, active=True, name='Ana', tier='free')

On older Python versions the options are giving every child field a default or restructuring so that defaults live only in the leaf class. In general, keep dataclass hierarchies shallow; composition, where one dataclass holds another as a field, is usually easier to follow.

Converting dataclasses to and from JSON

asdict() converts a dataclass to a dictionary, recursing into nested dataclasses, lists, tuples and dicts. That dictionary goes straight into json.dumps(). The way back is not automatic: you rebuild nested objects explicitly, which is also where you would put any version handling for old payloads:

import json
from dataclasses import dataclass, field, asdict
from datetime import datetime, timezone

@dataclass
class LineItem:
    sku: str
    qty: int
    unit_cents: int

@dataclass
class Order:
    id: int
    items: list[LineItem] = field(default_factory=list)
    created: datetime = field(default_factory=lambda: datetime.now(timezone.utc))

    @property
    def total_cents(self) -> int:
        return sum(i.qty * i.unit_cents for i in self.items)

def order_to_json(order: Order) -> str:
    # asdict() recurses into nested dataclasses, lists and dicts;
    # default=str handles the datetime (and any other non-JSON type)
    return json.dumps(asdict(order), default=str)

def order_from_json(text: str) -> Order:
    data = json.loads(text)
    return Order(
        id=data["id"],
        items=[LineItem(**item) for item in data["items"]],
        created=datetime.fromisoformat(data["created"]),
    )

order = Order(42, [LineItem("KB-01", 2, 4950), LineItem("MS-07", 1, 1999)],
              created=datetime(2026, 11, 29, 10, 30, tzinfo=timezone.utc))
text = order_to_json(order)
print(text)
# {"id": 42, "items": [{"sku": "KB-01", "qty": 2, "unit_cents": 4950}, {"sku": "MS-07", "qty": 1, "unit_cents": 1999}], "created": "2026-11-29 10:30:00+00:00"}
again = order_from_json(text)
print(again == order, again.total_cents)   # True 11899

Note that default=str writes the datetime with a space instead of a T; datetime.fromisoformat() accepts both. If you need strict ISO 8601 output, pass a small function such as lambda o: o.isoformat() instead. For APIs that receive untrusted JSON with many nested types, a validation library is a better fit, as the comparison below explains. The same asdict() pattern is handy for structured log fields, as used in Python logging best practices.

InitVar: arguments that are not stored

Sometimes the constructor needs a value that the object should not keep, such as a raw secret used to derive a fingerprint. Annotate it with InitVar: it becomes an __init__ parameter and is passed to __post_init__, but it is not a field:

import hashlib
from dataclasses import dataclass, field, InitVar

@dataclass
class ApiKey:
    name: str
    raw_key: InitVar[str]                 # passed to __init__, never stored
    fingerprint: str = field(init=False)

    def __post_init__(self, raw_key: str):
        self.fingerprint = hashlib.sha256(raw_key.encode()).hexdigest()[:12]

key = ApiKey("billing-worker", "sk_test_example_123")
print(key)                       # ApiKey(name='billing-worker', fingerprint='9119902c409d')
print(hasattr(key, "raw_key"))   # False

The same pattern works for building a config object from environment variables without keeping the raw environment around; the rules for handling those secrets are in .env files and secrets best practices.

Introspection helpers: fields, astuple, is_dataclass

The module also exposes the field list at runtime, which makes small generic utilities possible without a framework:

from dataclasses import dataclass, fields, astuple, is_dataclass

@dataclass
class Row:
    url: str
    status: int
    ms: float

r = Row("https://example.com/", 200, 81.4)
print([f.name for f in fields(Row)])   # ['url', 'status', 'ms']
print(astuple(r))                      # ('https://example.com/', 200, 81.4)
print(is_dataclass(r), is_dataclass(Row))  # True True

# fields() makes generic helpers easy, for example a CSV header and rows
import csv, io
buf = io.StringIO()
w = csv.writer(buf)
w.writerow([f.name for f in fields(Row)])
w.writerow(astuple(r))
print(buf.getvalue(), end="")
# url,status,ms
# https://example.com/,200,81.4

Dataclass vs NamedTuple vs TypedDict vs Pydantic

Dataclasses are not the only way to describe structured data in Python. Pick by what you need from the object (typing.NamedTuple):

Tool Mutable Runtime validation Best for
@dataclass Yes, or frozen Only what you write in __post_init__ Internal domain objects, configs, results
typing.NamedTuple No None Small immutable records that must also behave as tuples
typing.TypedDict Yes (it is a dict) None, type checker only Typing JSON-shaped dicts you cannot change, such as API responses
Pydantic or attrs Configurable Yes, with type coercion Untrusted input: request bodies, settings files, external APIs

A practical split that works well: validate untrusted input at the edge of the application with a validation library or explicit checks, then pass plain dataclasses through the rest of the code. If you publish a package that exposes dataclasses, set the minimum Python version in your project metadata, as described in the pyproject.toml packaging guide, so users on old versions do not hit slots or kw_only errors.

Common dataclass mistakes

  • Forgetting the type annotation. name = "x" without : str is a plain class attribute, not a field, and does not appear in __init__.
  • Expecting type checking at runtime. Annotations are hints. Validate in __post_init__ or at the input boundary.
  • Defining __eq__ on a non-frozen dataclass and expecting it to be hashable. With eq=True and frozen=False, __hash__ is set to None, so instances cannot go into sets. Freeze it, or use unsafe_hash=True only if you know the fields never change.
  • Overriding __init__. If you write your own __init__, the decorator does not replace it and __post_init__ is no longer called automatically. Prefer __post_init__ or a @classmethod constructor such as from_dict().
  • Using floats for money. Not a dataclass problem, but it shows up in every invoice class: store integer cents or use decimal.Decimal.

Python dataclasses checklist

  • Every field annotated; required fields before defaulted ones.
  • field(default_factory=...) for lists, dicts and sets.
  • Secrets hidden with repr=False; bookkeeping excluded with compare=False.
  • Validation and normalisation in __post_init__, kept cheap.
  • frozen=True for value objects and keys; changes through replace().
  • slots=True and kw_only=True on Python 3.10+ for configs and many small objects.
  • Explicit from_dict() or from_json() for the way back from JSON.
  • A validation library at the edge for untrusted input.

Want this done on your own server or site?

I am Saizul Amin, a web developer and technical SEO consultant. I set up and harden VPS servers, migrate WordPress sites, fix indexing problems and build automations. See my portfolio or get in touch.

FAQ

What is a dataclass in Python?

A dataclass is a regular class decorated with @dataclass from the dataclasses module. Python reads its type-annotated class attributes as fields and generates __init__, __repr__ and __eq__ from them, and optionally ordering methods, __hash__ and __slots__.

How do I set a list as a default value in a dataclass?

Use field(default_factory=list). Writing items: list = [] raises ValueError because one list would be shared by every instance. default_factory calls list() each time a new object is created, so every instance gets its own list.

Do Python dataclasses validate types?

No. Type hints in a dataclass are not checked at runtime. Add checks in __post_init__, run a static type checker such as mypy or Pyright, or use a validation library such as Pydantic when the data comes from untrusted input.

What is the difference between frozen=True and slots=True?

frozen=True blocks assignment to fields after creation and makes instances hashable. slots=True, available from Python 3.10, removes the per-instance __dict__ to save memory and reject unknown attributes. They are independent and can be combined.

Should I use a dataclass or a NamedTuple?

Use a dataclass for most domain objects, because it can be mutable or frozen, supports defaults with factories, validation in __post_init__, slots and inheritance. Use a NamedTuple when the object must be immutable and also behave like a tuple, for example for unpacking or compatibility with code that expects tuples.

Sources

NEW BLOGS. REAL STRATEGIES. REAL RESULTS.

Join our community and receive powerful SEO tips, web optimization guides, and growth strategies as soon as they’re published.

Don’t just read blogs — stay ahead of the competition.

We don’t spam! Read our privacy policy for more info.

Share.

Comments are closed.