DEV Community

qing
qing

Posted on

2-Minute Python Guide: dataclasses (2026)

2-Minute Python Guide: dataclasses

Python's @dataclass decorator is a powerful tool for simplifying class definitions, especially when working with data-centric objects. Let's compare a regular class with its @dataclass equivalent.

Regular Class

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __repr__(self):
        return f"Person(name={self.name}, age={self.age})"
Enter fullscreen mode Exit fullscreen mode

@dataclass

from dataclasses import dataclass

@dataclass
class Person:
    name: str
    age: int
Enter fullscreen mode Exit fullscreen mode

Notice the significant reduction in boilerplate code. The @dataclass decorator automatically generates special methods like __init__ and __repr__.

You can also use the field() function to customize attributes, such as setting a default value:

@dataclass
class Person:
    name: str
    age: int = field(default=18)
Enter fullscreen mode Exit fullscreen mode

To make the class immutable, use frozen=True:

@dataclass(frozen=True)
class Person:
    name: str
    age: int
Enter fullscreen mode Exit fullscreen mode

Takeaway: By using @dataclass, you can write more concise and readable code, focusing on the data structure rather than the boilerplate. This simplification can significantly improve your productivity and code maintainability. Give @dataclass a try in your next Python project!


Follow me on Dev.to for daily Python tips and quick guides!

Top comments (0)