Python Academy · Lesson

Defining a Dataclass

Use @dataclass to remove boilerplate.

Lesson 1 of 413 steps

Defining a Dataclass is a free Python Academy lesson on CoddyKit. This is lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Python Academy learning path, and your progress syncs across the web and the CoddyKit app. The Python Academy course includes 4 lessons in total.

Why Dataclasses?

When you write a class that mostly holds data, you end up repeating the same boilerplate: an __init__, a __repr__, and an __eq__. The dataclasses module generates all of that for you from simple field declarations.

  • Less code to write and read.
  • Fewer chances for typos in __init__.
  • Built into the standard library since Python 3.7.

The Old Way

Here is a plain class that stores a point. Notice how much typing it takes just to store two numbers.

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

p = Point(1, 2)
print(p.x, p.y)

The @dataclass Decorator

Apply @dataclass above a class and declare fields with type annotations. Python generates __init__ automatically.

from dataclasses import dataclass

@dataclass
class Point:
    x: int
    y: int

p = Point(1, 2)
print(p.x, p.y)

Automatic __repr__

Dataclasses also build a readable __repr__, so printing the object shows its fields instead of a memory address.

from dataclasses import dataclass

@dataclass
class Point:
    x: int
    y: int

print(Point(3, 4))

Automatic __eq__

Two dataclass instances compare equal when all their fields are equal. No need to write __eq__ by hand.

from dataclasses import dataclass

@dataclass
class Point:
    x: int
    y: int

print(Point(1, 2) == Point(1, 2))
print(Point(1, 2) == Point(9, 9))

Type Annotations Are Required

Each field must have a type annotation. The annotation is what tells the dataclass machinery that the name is a field. A bare assignment without an annotation becomes a regular class attribute, not a field.

from dataclasses import dataclass

@dataclass
class User:
    name: str
    age: int

u = User('Alice', 30)
print(u)

Adding Methods

A dataclass is still a normal class. You can add ordinary methods that use the generated fields.

from dataclasses import dataclass

@dataclass
class Rectangle:
    width: int
    height: int

    def area(self):
        return self.width * self.height

r = Rectangle(3, 4)
print(r.area())

Mutating Fields

By default dataclass instances are mutable, so you can reassign fields after creation just like normal attributes.

from dataclasses import dataclass

@dataclass
class Counter:
    value: int

c = Counter(0)
c.value += 5
print(c.value)

asdict and astuple

The helpers asdict() and astuple() convert an instance into a dictionary or tuple, which is handy for serialization.

from dataclasses import dataclass, asdict, astuple

@dataclass
class Point:
    x: int
    y: int

p = Point(1, 2)
print(asdict(p))
print(astuple(p))

Nested Dataclasses

A dataclass field can itself be another dataclass. The generated __repr__ and asdict() recurse into nested structures.

from dataclasses import dataclass, asdict

@dataclass
class Address:
    city: str

@dataclass
class Person:
    name: str
    address: Address

p = Person('Bob', Address('Paris'))
print(asdict(p))

When to Use Dataclasses

Reach for a dataclass when a class mainly groups related values together.

  • Configuration objects.
  • Records returned from a function.
  • Simple value types like coordinates or money.

For classes dominated by behavior rather than data, a regular class may read more clearly.

Quick Check

What does the @dataclass decorator generate automatically?

Recap

You learned to use @dataclass to remove boilerplate.

  • Declare fields with type annotations.
  • __init__, __repr__, and __eq__ are generated.
  • Use asdict() and astuple() to convert instances.
  • You can still add methods and nest dataclasses.
Free to start

Learn Python with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
76
Lessons
320

Frequently Asked Questions

Is the “Defining a Dataclass” lesson free?

Yes — the full text of “Defining a Dataclass” is free to read here on the web. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Python Academy course, upgrade to CoddyKit PRO. The Python Academy course includes 4 lessons in total.

What will I learn in “Defining a Dataclass”?

Use @dataclass to remove boilerplate. You practise Python Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Python Academy?

No prior experience is required. Python Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 1 of 4.

How long does the “Defining a Dataclass” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Python Academy lesson?

Yes. Every Python Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Defining a Dataclass
  2. Default Values and field()
  3. Frozen and Comparison Options
  4. The attrs Library
← Back to Python Academy