Validated Dataclasses

easy
Unit 8 · Dataclasses0/3 to milestone

Bad data should fail loudly at the edge of your system, not three functions later. Use a @dataclass with validation.

Define:

  • LineItem(sku: str, quantity: int, unit_price: float). In __post_init__, raise ValueError if sku is empty, quantity < 1, or unit_price < 0. Add a property subtotal = quantity × unit_price.
  • Order(order_id: str, items: list[LineItem], discount: float = 0.0). items must be non-empty and discount must be between 0 and 1 inclusive (ValueError otherwise). Give it a property total, the sum of subtotals × (1 − discount), rounded to 2 decimal places.

Use dataclasses.field(default_factory=...) if you need a mutable default. Dataclasses get __eq__ and __repr__ for free.

#dataclasses#validation#classes2 visible + 3 hidden tests
solution.py · Python 3.13
Loading editor…
Run your code to see results. ⌘↵ to run · ⌘⇧↵ to submit
Validated Dataclasses · TechGradify