Python dataclasses are a feature introduced in Python 3.7 that simplify the creation of classes primarily used to store data. They reduce boilerplate code by automatically generating common special methods like __init__, __repr__, __eq__, and __hash__ based on field type annotations.

Key Features

  • Automatic Method Generation: The @dataclass decorator generates __init__, __repr__, and __eq__ methods, enabling instantiating, printing, and comparing objects without writing them manually.

  • Default Values: Fields can have default values using standard Python syntax. Non-default fields must come before default ones.

  • Customization: Use the field() function to control behavior like repr, compare, default_factory, or init (e.g., field(default_factory=list) for mutable defaults).

  • Immutability: Set frozen=True to make instances immutable and enable hashing, allowing use as dictionary keys.

  • Memory Efficiency: Use slots=True to reduce memory usage by limiting instance attributes to defined fields.

  • Keyword-Only Arguments: Use kw_only=True to require all arguments to be passed as keywords.

Common Use Cases

  • Data containers (e.g., Person, Book, Point).

  • Configuration objects.

  • API response models.

  • Representing structured data in pipelines or databases.

Conversion Methods

  • asdict() – Convert a dataclass instance to a dictionary.

  • astuple() – Convert to a tuple of values.

  • replace() – Create a new instance with specified fields updated.

Example

from dataclasses import dataclass, field
from typing import List

@dataclass
class Person:
    name: str
    age: int
    hobbies: List[str] = field(default_factory=list)
    is_active: bool = True

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

person = Person("Alice", 30, ["reading"])
print(person)  # Person(name='Alice', age=30, hobbies=['reading'], is_active=True)
print(asdict(person))  # {'name': 'Alice', 'age': 30, 'hobbies': ['reading'], 'is_active': True}

Dataclasses are ideal for clean, readable, and maintainable code when working with structured data.

The dataclass decorator helps you build, wait for it, data classes. In short, it takes care of some annoying things for you: defining a couple of methods, such as init, str, repr, eq, gt, etc. It does tuple equality and comparison. It also defines match args for use in match statements. It lets you freeze instances, making them immutable. It's quite convenient honestly. Say you're coding a die roll challenge for an rpg, you could write a RollResult class that holds the roll and the roll/challenge ratio: @dataclass(frozen=True) class RollResult: roll: int ratio: float And you can use it wherever it makes sense: if result.ratio >= 1: print("success") match result: case RollResult(20, _): print("nat 20") Answer from lekkerste_wiener on reddit.com
🌐
Python
docs.python.org › 3 › library › dataclasses.html
dataclasses — Data Classes
3 weeks ago - It should take the class object as a first argument and the same keyword arguments as @dataclass. By default, the @dataclass function is used. This function is not strictly required, because any Python mechanism for creating a new class with __annotations__ can then apply the @dataclass function to convert that class to a dataclass.
🌐
Reddit
reddit.com › r/learnpython › dataclass - what is it [for]?
r/learnpython on Reddit: Dataclass - what is it [for]?
May 22, 2025 -

I've been learning OOP but the dataclass decorator's use case sort of escapes me.

I understand classes and methods superficially but I quite don't understand how it differs from just creating a regular class. What's the advantage of using a dataclass?

How does it work and what is it for? (ELI5, please!)


My use case would be a collection of constants. I was wondering if I should be using dataclasses...

class MyCreatures:
        T_REX_CALLNAME = "t-rex"
        T_REX_RESPONSE = "The awesome king of Dinosaurs!"
        PTERODACTYL_CALLNAME = "pterodactyl"
        PTERODACTYL_RESPONSE = "The flying Menace!"
        ...

 def check_dino():
        name = input("Please give a dinosaur: ")
        if name == MyCreature.T_REX_CALLNAME:
                print(MyCreatures.T_REX_RESPONSE)
        if name = ...

Halp?

Discussions

Dataclasses: subclassing a dataclass without its fields inherited as init-fields
I was wondering if it would be possible to allow subclassing a dataclass without automatically including its fields in Subclass.__init__ (in some sense, hiding the inherited fields). When subclassing the dataclass AB below to create CD, the fields of AB become fields of CD, automatically included ... More on discuss.python.org
🌐 discuss.python.org
0
August 12, 2024
python - understanding dataclass field usage - Stack Overflow
I am confused about how the usage of field() in dataclasses works. I have this (senseless) example: from dataclasses import dataclass, field @dataclass class Person: name: str = field(init=Fal... More on stackoverflow.com
🌐 stackoverflow.com
What are dataclasses so famous?
it's not another dependency since it's a part of the python standard library More on reddit.com
🌐 r/Python
48
0
December 5, 2024
Any reason not to use dataclasses everywhere?
Absolutely use data classes when they do the job. Cases when this is not true (or it's awkward): custom init method custom new method various patterns that use inheritance if you want different names for the attributes,. including implementing encapsulation probably more things :) Changing later might have some cost, so use dataclasses when you are fairly certain you won't need those things. This is still a lot of cases, I use them often. More on reddit.com
🌐 r/Python
70
44
October 24, 2022
🌐
Dataquest
dataquest.io › blog › how-to-use-python-data-classes
How to Use Python Data Classes (A Beginner's Guide) – Dataquest
May 12, 2025 - The dataclasses module, a feature introduced in Python 3.7, provides a way to create data classes in a simpler manner without the need to write methods.
🌐
Molssi
education.molssi.org › type-hints-pydantic-tutorial › chapters › DataclassInPython.html
Dataclasses In Python — Python Type Hints, Dataclasses, and Pydantic
Typing out attribute assignments in the __init__ of a class to the same name as the argument variable is a very common use case, especially in scientific computing. It is so common to do this argument-to-attribute-of-the-same-name operation that Python provides a built-in library called dataclasses to do it for you.
🌐
Real Python
realpython.com › python-data-classes
Data Classes in Python (Guide) – Real Python
March 8, 2024 - A Python dataclass lets you define classes for storing data with less boilerplate. Use @dataclass to generate .__init__(), .__repr__(), and .__eq__() automatically.
🌐
Medium
medium.com › @laurentkubaski › python-data-classes-f98f8368f5c2
Python Data Classes. This is a quick intro to Python Data… | by Laurent Kubaski | Medium
November 25, 2025 - @dataclass(unsafe_hash=True) class MyDataClass: var1: str var2: int # non-frozen Data Class: __hash__() method is STILL generated because of unsafe_hash=True assert [name for (name, value) in inspect.getmembers(MyDataClass, predicate=inspect.isfunction)] == ['__eq__', '__hash__', '__init__', '__repr__'] my_dataclass = MyDataClass("Hello", 5) assert my_dataclass.__hash__ is not None · The official Python documentation is amazingly unclear on why you would want to do this: “This might be the case if your class is logically immutable but can still be mutated.
Find elsewhere
🌐
Python
peps.python.org › pep-0557
PEP 557 – Data Classes | peps.python.org
If the default value of a field is specified by a call to field(), then the class attribute for this field will be replaced by the specified default value. If no default is provided, then the class attribute will be deleted. The intent is that after the dataclass decorator runs, the class ...
🌐
DataCamp
datacamp.com › tutorial › python-data-classes
Python Data Classes: A Comprehensive Tutorial | DataCamp
March 15, 2024 - Let’s cover some of the fundamental concepts of Python data classes that make the so useful. Despite all their features, data classes are regular classes that take much less code to implement the same functionality. Here is the Exercise class again: from dataclasses import dataclass @dataclass class Exercise: name: str reps: int sets: int weight: float ex1 = Exercise("Bench press", 10, 3, 52.5) # Verifying Exercise is a regular class ex1.name 'Bench press'
🌐
CoinGecko
coingecko.com › learn › how-to-build-a-solana-sniper-bot-in-python
How to Build a Solana Sniper Bot in Python | CoinGecko API
2 weeks ago - To make it easier to work with the response data and safely access its properties, including nested objects, we’re going to model it using Python’s @dataclass decorator.
🌐
GeeksforGeeks
geeksforgeeks.org › python › understanding-python-dataclasses
Understanding Python Dataclasses - GeeksforGeeks
July 15, 2025 - DataClasses are like normal classes in Python, but they have some basic functions like instantiation, comparing, and printing the classes already implemented.
🌐
GeeksforGeeks
geeksforgeeks.org › python › data-classes-in-python-an-introduction
Data Classes in Python | An Introduction - GeeksforGeeks
July 11, 2025 - dataclass module is introduced in Python 3.7 as a utility tool to make structured classes specially for storing data. These classes hold certain properties and functions to deal specifically with the data and its representation.
🌐
Python.org
discuss.python.org › python help
Dataclasses: subclassing a dataclass without its fields inherited as init-fields - Python Help - Discussions on Python.org
August 12, 2024 - I was wondering if it would be possible to allow subclassing a dataclass without automatically including its fields in Subclass.__init__ (in some sense, hiding the inherited fields). When subclassing the dataclass AB below to create CD, the fields of AB become fields of CD, automatically included in __init__, __repr__, and other methods of CD.
🌐
InfoWorld
infoworld.com › home › software development › programming languages › python
How to use Python dataclasses | InfoWorld
October 22, 2025 - But creating classes in Python sometimes means writing loads of repetitive, boilerplate code; for example, to set up the class instance from the parameters passed to it or to create common functions like comparison operators. Dataclasses, introduced in Python 3.7 (and backported to Python 3.6), provide a handy, less-verbose way to create classes.
🌐
Real Python
realpython.com › ref › stdlib › dataclasses
dataclasses | Python Standard Library – Real Python
The Python dataclasses module provides functionality for creating and working with user-defined data classes.
🌐
W3Schools
w3schools.com › python › ref_module_dataclasses.asp
Python dataclasses Module
The dataclasses module helps you write classes that mainly store data by generating methods like __init__, __repr__, and comparisons.
🌐
Reddit
reddit.com › r/python › what are dataclasses so famous?
r/Python on Reddit: What are dataclasses so famous?
December 5, 2024 -

As the title says, I've read the whole documentation more than once and have used them plenty of times. But in practice for me it's just a way to avoid writing an init method. This is a good QL improvement, I guess, but now means that my code uses another dependency and extra complexity for what? I won't argue the merits of options like hash and frozen, but i don't find myself needing that functionality that often. So I return to my genuine question, why has the community so quickly adopted and recommended the use of dataclasses? I'm referring to articles and YouTube videos about them.

In what use cases are you finding success with them?

🌐
Medium
medium.com › @akashsdas_dev › dataclasses-in-python-804db8e149c3
Dataclasses in Python. Reduce writing boilerplate code when… | by AkashSDas | Medium
March 23, 2024 - A lot of this boilerplate can be ... (introduced in Python3.7). Data classes provide a convenient way to create classes that primarily store data and have a minimal amount of custom methods....