Python
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.
Exercise 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)).
Show example solution
# 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))
Test yourself
-
Which combination is wrong?
- @dataclass + field(default_factory=list)
- @dataclass(frozen=True) + members: list = []
- @dataclass + asdict + astuple
- @dataclass(frozen=True) + __post_init__
Show answer
@dataclass(frozen=True) + members: list = [] — A frozen class cannot hold a mutable list.
-
Match the dataclass concepts
- @dataclass
- Auto constructor
- field(default_factory=list)
- Empty-list factory
- frozen=True
- Immutability
- __post_init__
- Validation
-
Import asdict
from dataclasses import dataclass, field, ____
@dataclass
class Product:
name: str = ""
price: int = 0
Show answer
from dataclasses import dataclass, field, asdict
@dataclass
class Product:
name: str = ""
price: int = 0
-
Match the class parts
- @dataclass
- Decorator
- field(default_factory=list)
- Mutable default
- __post_init__
- Validation method
- asdict(p)
- Dict conversion
Next lesson: Model design