Writing

Building Data Classes with Python's dataclasses Module

While exploring examples of WebSocket servers in Sanic, I noticed a decorator applied to a class definition: @dataclass.

from dataclasses import dataclass, field

# ... (omitted)

@dataclass
class Client:
    interface: websockets.server.WebSocketServerProtocol = field(repr=False)
    sid: str = field(default_factory=partial(generate_code, 36))

    # ... (omitted)

Introduced in Python 3.7 as part of the standard library, dataclasses requires no external installation. It offers an elegant, declarative way to define data-centric classes using standard type annotations.

What Problem Does @dataclass Solve?

In everyday Python, classes created primarily to store state often require repetitive boilerplate: setting up __init__, implementing a readable __repr__, and defining value-based equality in __eq__.

The @dataclass decorator inspects class-level type annotations and generates these special methods automatically.

from dataclasses import dataclass

# Simply decorate your class with @dataclass
@dataclass
class Item:
    id: int
    name: str


print(Item(1, "Apple"))
print(Item(2, "Banana"))

Output:

Item(id=1, name='Apple')
Item(id=2, name='Banana')

Without @dataclass, creating Item(1, "Apple") would raise a TypeError unless you explicitly wrote __init__. Furthermore, without an explicit __repr__, printing the instance would only yield an unhelpful memory address:

class Item:
    id: int
    name: str

    def __init__(self, id: int, name: str):
        self.id = id
        self.name = name


print(Item(1, "Apple"))
print(Item(2, "Banana"))

Output:

<__main__.Item object at 0x7fd501796898>
<__main__.Item object at 0x7fd501796898>

How It Compares to namedtuple

Python has long offered collections.namedtuple for grouping values under named attributes. However, classes decorated with @dataclass are true Python classes:

  • You can define custom regular methods, properties, and class attributes naturally.
  • They support standard inheritance hierarchies.
  • Fields can be easily mutated (unless you explicitly specify @dataclass(frozen=True)).

Customizing Fields with field()

When a field requires more than a simple default value—such as a mutable default or custom display behavior in repr—use dataclasses.field.

[!NOTE] Python Version Note Never use mutable defaults directly (like items: list = []). In Python dataclasses, always use field(default_factory=list) to ensure each instance receives a fresh list object.

from dataclasses import dataclass, field
import uuid


@dataclass
class Factory:
    id: uuid.UUID = field(default_factory=uuid.uuid4)
    items: list = field(default_factory=list)


f1 = Factory()
print(f1.items)
f1.items += ['apple', 'banana']
print(f1.items)
print(f1)

Output:

[]
['apple', 'banana']
Factory(id=UUID('990091ef-6058-4754-b1f5-78e3546cc7bd'), items=['apple', 'banana'])

Common parameters for field() include:

  • default_factory: A zero-argument callable invoked to generate default values for mutable types (list, dict, set, etc.) or unique values like UUIDs.
  • repr=False: Excludes the field from the auto-generated __repr__ output (useful for sensitive tokens or bulky internal objects).
  • compare=False: Excludes the field from equality comparisons (__eq__).

Type Annotations vs. Runtime Validation

It is important to remember that standard Python dataclasses use type annotations solely for schema definition; they do not validate types at runtime. Passing a string into an integer field will succeed without error.

If your application demands strict runtime type enforcement and parsing (e.g., handling incoming API payloads), consider pairing dataclasses with or migrating to Pydantic (pydantic.dataclasses or pydantic.BaseModel).

References