runtime
273 / 500
question 273 Data Models & Typing · easy

A CSV catalogue into dataclasses

A supplier sends its catalogue as CSV text. Write a dataclass Product with fields sku, name, price and stock, whose __post_init__ upper-cases and strips the SKU, strips the name, and converts price to float and stock to int. Then write parse_catalogue(text), which reads the CSV (header sku,name,price,stock) into a list of Products and raises ValueError if a SKU appears twice.

DataclassProduct with sku: str, name: str, price: float, stock: int; __post_init__ tidies and converts
Functionparse_catalogue(text) → list of Product, in file order
RaisesValueError for a SKU that appears twice (after tidying)
Hintcsv.DictReader(io.StringIO(text)) reads CSV from a text

Loading your progress…

A CSV catalogue into dataclasses — Python practice · Runtime