CodeBlanks Logo Icon CodeBlanks

@dataclass

Learn data classes with @dataclass.

The @dataclass decorator

The @dataclass decorator simplifies class boilerplate. From type-annotated attributes it auto-generates __init__, __repr__ and __eq__ methods.

Example: from dataclasses import dataclass\n@dataclass\nclass Product:\n name: str\n price: float. This removes the need for hand-written __init__ and __repr__. The instance Product("Pen", 5.0) is ready; print(p) shows a clean representation. It is useful for data-carrying classes with encapsulation.

Type annotations

In a @dataclass class, each attribute is written with a type annotation: name: str, price: float. These annotations tell the decorator which attributes to generate.

For mutable defaults, field(default_factory=list) is used; [] cannot be written directly. In this lesson we'll only use constant defaults. The annotation does not break encapsulation; it just states the data layout.

Practice Define the Product data class

First write from dataclasses import dataclass. Then add the @dataclass decorator and class Product:. In the body add the annotations name: str and price: float. Then create an instance with p = Product("Pen", 5.0) and print it with print(p).

Starter code

main.py
# Define the Product data class

Sample solution

main.py
# Define the Product data class
from dataclasses import dataclass

@dataclass
class Product:
    name: str
    price: float

p = Product("Pen", 5.0)
print(p)

Expected output

Product(name='Pen', price=5.0)

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which decorator auto-generates __init__?

  • @dataclass Correct answer
  • @classmethod
  • @property
  • @staticmethod

Explanation: @dataclass generates __init__ from type-annotated attributes.

2 Complete the dataclass import

Question
from dataclasses import ____

@dataclass
class Product:
    name: str
    price: float
Answer
from dataclasses import dataclass

@dataclass
class Product:
    name: str
    price: float

Explanation: The dataclass function is imported from the dataclasses module.

3 Match the @dataclass concepts

Term Meaning
@dataclass Decorator
name: str Type annotation
__repr__ Auto-generated

All lessons in Intermediate