Python, properly · Chapter 25 of 42
Dataclasses
By the end of this chapter you can turn a list of typed fields into a full class with @dataclass: defaults, its own list per object, objects that refuse changes, sorting, and checks that run after __init__. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.
- Part: Objects
- 4 tasks
- Python
- In the all labs plan
The first 2 chapters of Python, properly are free. This one comes with the all labs plan.
Why you need this
DabbaDrop now has classes for dishes, orders, riders and bills, and most of them are just data with a name. Kunal counted: every one of them repeats each field three times in __init__, prints as an address, and says two identical deliveries are different:
class Delivery:
def __init__(self, order_id, rider_id, km):
self.order_id = order_id
self.rider_id = rider_id
self.km = km
a = Delivery("D0412", "R3", 4.5)
b = Delivery("D0412", "R3", 4.5)
print(a)
print(a == b)
<__main__.Delivery object at 0xffff91932900>
False
== on plain objects asks "is this the same object?", not "do they hold the same values?". Fixing that by hand for every class is the boilerplate Python's dataclasses module writes for you.
What you build: 4 tasks
Each task has tests. You write the code in the lab's editor and press Check.
- Task 1
dish.py: a frozen Dish
Write Dish as a frozen dataclass with four fields in this order: id (str), name (str), price (int) and available (bool, True by default).
repr(Dish("jeera-rice", "Jeera Rice", 90)) must be exactly Dish(id='jeera-rice', name='Jeera Rice', price=90, available=True). Two dishes with the same values are equal, d.price = 100 raises dataclasses.FrozenInstanceError, and a set of two equal dishes holds one.
- Task 2
order.py: an Order with a list of its own
Write Order as a dataclass with four fields in this order: order_id (str), customer_id (str), items (a list of str, an empty list by default) and status (str, "placed" by default). It is not frozen.
repr(Order("D0700", "C010")) must be exactly Order(order_id='D0700', customer_id='C010', items=[], status='placed'). Appending to one order's items never changes another order's, and Order("D0702", "C012", ["roti"], status="cooking") sets both.
- Task 3
tiffin.py: tiffins in packing order
Write Tiffin as a dataclass that can be sorted, with four fields in this order: slot (int), area (str), order_id (str) and note (str, "" by default, left out of comparisons).
Sorting tiffins puts them by slot, then area, then order id. Tiffin(1, "Dadar", "D0305", "no onion") == Tiffin(1, "Dadar", "D0305") is True, and the note never changes the order.
- Task 4 · interview question
Interview: line.py, a bill line that checks itself
Write BillLine as a dataclass with three fields: dish (str), qty (int) and unit_price (int). Making one with qty below 1 or unit_price below 0 raises ValueError. amount is a read-only property, qty times unit_price, worked out when it is read (not a field, so not in the repr).
BillLine("Roti", 4, 15).amount is 60, BillLine("Water", 1, 0).amount is 0, and BillLine("Roti", 0, 15) and BillLine("Roti", 2, -15) raise ValueError. repr(BillLine("Chole", 2, 150)) is BillLine(dish='Chole', qty=2, unit_price=150).
What you will learn
- @dataclass: __init__, __repr__ and __eq__ written from a list of fields.
- Defaults and field(default_factory=list) for a list per object.
- frozen=True: objects that refuse changes, and can go in a set.
- order=True and field(compare=False): sorting by fields.
- __post_init__: your own checks, after the generated __init__.
More in Objects
Build "Dataclasses" yourself
DabbaDrop, a Mumbai tiffin startup, runs on Excel and WhatsApp. You are its first Python developer. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.
The first 2 chapters of Python, properly are free. This one comes with the all labs plan.