Fundamentals 8 min read

Master Python’s @dataclass: Simplify Class Creation and Management

Learn how Python’s @dataclass decorator, introduced in Python 3.7, streamlines class definition by automatically generating constructors, string representations, and more, while covering default values, mutable defaults handling, field exclusion, read‑only classes, and conversion to tuples and dictionaries for efficient data handling.

Code Mala Tang
Code Mala Tang
Code Mala Tang
Master Python’s @dataclass: Simplify Class Creation and Management

1. Traditional class definition

The

dataclass

module was added to the standard library in Python 3.7, providing a convenient way to create and manage data classes. Traditional class definition requires writing an

__init__

method to initialise attributes.

<code>class CoinTrans:
    def __init__(self, id: str, symbol: str, price: float, is_success: bool, addrs: list) -> None:
        self.id = id
        self.symbol = symbol
        self.price = price
        self.is_success = is_success
        self.addrs = addrs
</code>

Instantiating and printing the object only shows its memory address because the default

__str__

is not overridden.

<code>if __name__ == "__main__":
    coin_trans = CoinTrans("id01", "BTC/USDT", 71000, True, ["0x1111", "0x2222"])
    print(coin_trans)
</code>

To obtain a readable representation, implement

__str__

:

<code>def __str__(self) -> str:
    return f"Transaction Information: {self.id}, {self.symbol}, {self.price}, {self.addrs}, {self.is_success}"
</code>

After adding

__str__

, printing displays the detailed transaction information.

2. Using @dataclass decorator

The decorator reduces boilerplate by automatically generating

__init__

,

__repr__

, and other methods.

<code>from dataclasses import dataclass

@dataclass
class CoinTrans:
    id: str
    symbol: str
    price: float
    is_success: bool
    addrs: list
</code>

Running the same instantiation now prints a nicely formatted representation:

<code>if __name__ == "__main__":
    coin_trans = CoinTrans("id01", "BTC/USDT", 71000, True, ["0x1111", "0x2222"])
    print(coin_trans)
</code>

2.1 Default values

Defaults can be set directly in the class definition, but mutable defaults such as

list

raise a

ValueError

. Use

default_factory

to provide a safe default.

<code>def gen_list():
    return ["0x1111", "0x2222"]

@dataclass
class CoinTrans:
    id: str = "id01"
    symbol: str = "BTC/USDT"
    price: float = 71000.8
    is_success: bool = True
    addrs: list[str] = field(default_factory=gen_list)
</code>

2.2 Hide sensitive information

Set

repr=False

on fields to exclude them from the generated

__repr__

output.

<code>@dataclass
class CoinTrans:
    id: str = "id01"
    symbol: str = "BTC/USDT"
    price: float = 71000.8
    is_success: bool = field(default=True, repr=False)
    addrs: list[str] = field(default_factory=gen_list, repr=False)
</code>

Printing now shows only the selected fields.

2.3 Read‑only objects

Adding

frozen=True

makes instances immutable, preventing accidental modification.

<code>@dataclass(frozen=True)
class CoinTrans:
    id: str = "id01"
    symbol: str = "BTC/USDT"
    price: float = 71000.8
    # other fields …
</code>

Attempting to assign to a field raises

dataclasses.FrozenInstanceError

.

2.4 Convert to tuple and dict

The

dataclasses

module provides

astuple

and

asdict

to transform a data class into simple structures, which is useful for interfacing with other programs.

<code>from dataclasses import astuple, asdict

coin = CoinTrans()
print(astuple(coin))
print(asdict(coin))
</code>

The output shows a tuple of field values and a dictionary mapping field names to values.

Conclusion

The

dataclass

decorator automates the generation of common methods, dramatically simplifying data class creation and management, and is a valuable tool for efficient Python development.

Pythondataclassdefault valuesasdictclass definitionfrozen
Code Mala Tang
Written by

Code Mala Tang

Read source code together, write articles together, and enjoy spicy hot pot together.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.