30. Build Records from CSV Rows
Difficulty: Medium · Topic: OOP & classes
Write a dataclass Trip with fields trip_id: int, city: str, fare: float and tags: list (default: an empty list), plus a class method Trip.from_row(row) that parses a line like "7, Pune ,120.5,airport|night":
- Fields are comma-separated; strip spaces.
trip_idbecomes anint,fareafloat, and tags are|-separated (an empty field means no tags). - A row without exactly 4 fields raises
ValueError. - Called on a subclass,
from_rowreturns an instance of that subclass. - Every
Tripgets its own tags list.
Your code runs in CPython on our servers against 6 tests, including hidden ones.
Sample test
Trip.from_row("7, Pune ,120.5,airport|night") == Trip(7, 'Pune', 120.5, ['airport', 'night'])Expected: True
Hints
Hint 1
@dataclass writes __init__, __repr__ and __eq__ from the annotated fields.Hint 2
A mutable default needsfield(default_factory=list).Hint 3
@classmethod receives the class as cls; return cls(...) builds the right subclass.Learn the concepts
- Classes, properties and dataclasses · 4 min read. Invariants, validated and read-only attributes, alternate constructors and record types.
More Python problems
- Bank Account with Validation · Easy
- Temperature with Properties · Easy
- An Abstract Connector Class · Medium
- A Comparable Version Class · Medium
- LRU Cache · Hard
- A Transaction Context Manager · Hard