dataclasses & enum in Python
Chapter 25: dataclasses & enum
6 short lessons, with 3D animations, quizzes and coding tasks.
The lessons
@dataclass: let Python write the boring parts
@dataclass reads the fields you list in a class and writes init, repr and eq for you.
Defaults, order=True and frozen=True
Dataclass fields can have defaults, order=True writes < and friends by comparing fields in order, and frozen=True makes objects read-only.
Enum: a fixed set of choices
An Enum is a class whose members are the only allowed choices, so a typo becomes an error right away instead of a hidden bug.
Designing with classes, dataclasses and Enums
Pick the tool by what the thing is: a fixed set of choices is an Enum, mostly data is a dataclass, rules to protect is a normal class, and "has a" is one object inside another.
Abstract base classes: a promise every subclass keeps
A class that inherits from ABC and marks some methods with @abstractmethod is a promise, not a finished class: you can't make an object from it, and a subclass can only make objects once it has written every method on the list.
Project: a library system
A school library lends books. A paper book can be with only one student at a time: once it's borrowed, the next student has to wait. An e-book is different: any number of students can read it at once. The librarian wants to add books, lend them, take them back, and print a list showing what's on the shelf. In this project you'll build that system with everything from World 4: an Enum, a dataclass, inheritance with an overridden method, and a class that protects its rules. The plan in one sentence: a Status Enum names the two states, a Book dataclass holds each book, an EBook child changes how lending works, and a Library class keeps the books and enforces the rules. Its words: state: whether a book is AVAILABLE or BORROWED rule: a borrowed paper book can't be borrowed again; the Library refuses with a ValueError override: EBook writes its own canborrow and lend, so the same calls behave differently **Step by step, the plan:** 1. Status(Enum): the only two states a book can be in. 2. @dataclass Book: title, author, status, plus canborrow, lend and giveback. 3. class EBook(Book): always borrowable, and lending changes nothing. 4. class Library: a dictionary of books by title, with add, borrow, giveback and report. When the library asks a book canborrow(), Python climbs the lookup tower. An e-book answers from its own class: **Steps 1 and 2: the data.** A book's state is one of a fixed set of choices, so it's an Enum: Status.BORROWED can't be misspelt the way "borowed" could. The book is mostly data, so @dataclass writes _init_ and _repr_, and the default status = Status.AVAILABLE means a new book starts on the shelf. **Step 3: the e-book.** An e-book **is a** book, so it inherits. It overrides two methods: canborrow always says True, and lend does nothing, because there's no copy to take off the shelf. Step 4: the rules. The Library is the only place that lends, so it's the place to check: a missing title or a book that can't be borrowed raises a ValueError with a clear message, and nothing changes. Why build it this way, and what it costs. Each class has one job, and the Library never asks "is this an e-book?": it just calls canborrow() and lend(), and each kind of book answers for itself (polymorphism, Lesson 22.3). Adding an audiobook later means one new child class, with no change to Library. Lending and returning look a book up by title in a dictionary, which takes about the same time for 10 books or 10,000; only report() walks and sorts them all. **Mistakes and edge cases.** **Checking the type in Library.** if isinstance(book, EBook): inside borrow works, but every new kind of book would need another if. **Changing status from outside.** library.books["Dune"].status = Status.AVAILABLE skips the rules; go through giveback. Comparing with a string. book.status == "AVAILABLE" is always False: compare with Status.AVAILABLE. A missing title. self.books[title] on an unknown title raises a KeyError; check in first and raise a clear ValueError instead.