CodeBlanks Logo Icon CodeBlanks

Summary - Dataclasses

Combine @dataclass, field and frozen to write a Product class.

Summary - Dataclasses

In this group we covered @dataclass basics, mutable defaults with field(), immutability with frozen=True, validation with __post_init__, and the asdict/astuple conversions.

A dataclass auto-generates constructor, repr and eq; field(default_factory=...) gives each instance its own container; frozen=True provides immutability; __post_init__ is for validation; asdict and astuple convert data to other forms. Now we'll write an example that combines these.

Practice Combined summary example

Start with from dataclasses import dataclass, field, asdict. Define a Product class with @dataclass; include fields name: str = "", price: int = 0 and tags: list = field(default_factory=list). Add a method def __post_init__(self):; in the body write if self.price < 0: and raise ValueError("negative not allowed"). Then create p = Product(name="Pen", price=10) and call print(p.name, p.price) and print(asdict(p)).

Starter code

main.py
# Write the Product class with field, __post_init__ and asdict

Sample solution

main.py
# Write the Product class with field, __post_init__ and asdict
from dataclasses import dataclass, field, asdict

@dataclass
class Product:
    name: str = ""
    price: int = 0
    tags: list = field(default_factory=list)

    def __post_init__(self):
        if self.price < 0:
            raise ValueError("negative not allowed")

p = Product(name="Pen", price=10)
print(p.name, p.price)
print(asdict(p))

Expected output

Pen 10
{'name': 'Pen', 'price': 10, 'tags': []}

Questions and answers

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

1 Which combination is wrong?

  • @dataclass + field(default_factory=list)
  • @dataclass(frozen=True) + members: list = [] Correct answer
  • @dataclass + asdict + astuple
  • @dataclass(frozen=True) + __post_init__

Explanation: A frozen class cannot hold a mutable list.

2 Match the dataclass concepts

Term Meaning
@dataclass Auto constructor
field(default_factory=list) Empty-list factory
frozen=True Immutability
__post_init__ Validation

3 Import asdict

Question
from dataclasses import dataclass, field, ____

@dataclass
class Product:
    name: str = ""
    price: int = 0
Answer
from dataclasses import dataclass, field, asdict

@dataclass
class Product:
    name: str = ""
    price: int = 0

Explanation: asdict is in the dataclasses module.

4 Match the class parts

Term Meaning
@dataclass Decorator
field(default_factory=list) Mutable default
__post_init__ Validation method
asdict(p) Dict conversion

All lessons in Intermediate