Capstone · lesson 3 of 9
Parts in this lesson
ABorrowingPolicya strategy object
B@dataclass(frozen=True)4.4: can't be changed
Cget_name(), set_name()4.3: getters and setters
D__eq__, __hash__3.5: equal by id

Members

Last updated

A library lends to members, and not every member gets the same deal: students borrow fewer items and pay smaller fines, and staff pay none. In this lesson you'll write members.py: a Member that keeps its own data valid, and a BorrowingPolicy it holds, so the rules for each kind of member live in one small object.

By the end of this lesson you can

  • Give a class a policy object instead of a subclass for each kind (composition and strategy)
  • Make a policy that can't be changed by accident, with frozen=True
  • Guard a member's data with getters and setters
  • Make two objects equal by their id, and keep them usable in a set

Three kinds of member, one class

The library has three kinds of member:

  • standard: up to 5 items, 25 cents a day when late, at most $5 a loan (the rule from lesson 1.P);
  • student: up to 3 items, 10 cents a day, at most $2;
  • staff: up to 10 items, no fines.

Lesson 4.15 weighed two ways to model "kinds of" something:

Two ways to give members different rules
DesignWhat happens
A subclass for each kind: StudentMember(Member)A member who graduates must be made again as a new object. A rule shared by students and staff is written twice.
A policy object the member holdsOne set_policy() call changes a member’s deal. A new kind of member is one more policy, with no new class.

The reference uses the second. A member has a BorrowingPolicy (composition), and asks it for the rules. That's the Strategy pattern from lesson 4.16: the part that changes from one member to another is pulled out into an object of its own.

members.py
100%
Member
  • #_member_id: str
  • #_name: str
  • #_policy: BorrowingPolicy
  • +__init__(member_id: str, name: str, policy: BorrowingPolicy)
  • +get_id(): str
  • +get_name(): str
  • +set_name(name: str)
  • +get_policy(): BorrowingPolicy
  • +set_policy(policy: BorrowingPolicy)
  • +check_can_borrow(loans_now: int)
  • +__str__(): str
  • +__eq__(other: object): bool
  • +__hash__(): int
  • +to_dict(): dict[str, Any]
  • +from_dict(data: dict[str, Any]): "Member"
«dataclass, frozen» BorrowingPolicy
  • +name: str
  • +max_loans: int
  • +fine_per_day: int
  • +max_fine: int
  • +fine_for(days_late: int): int
  • Dataclass BorrowingPolicy; attributes: name, max_loans, fine_per_day, max_fine; methods: fine_for.
  • Class Member; attributes: _member_id, _name, _policy; methods: __init__, get_id, get_name, set_name, get_policy, set_policy, check_can_borrow, __str__, __eq__, __hash__, to_dict, from_dict.
  • Member holds one BorrowingPolicy in _policy.

The policy does one sum, fine_for, which is the fine rule from 1.P with the numbers taken from the policy:

How the reference does it library/members.py, lines 8–24
@dataclass(frozen=True)
class BorrowingPolicy:
    """How much a kind of member may borrow, and what they pay when it's late: a strategy."""

    name: str
    max_loans: int
    fine_per_day: int  # cents
    max_fine: int  # cents: the most one loan can cost

    def fine_for(self, days_late: int) -> int:
        return min(max(days_late, 0) * self.fine_per_day, self.max_fine)


STANDARD = BorrowingPolicy("standard", max_loans=5, fine_per_day=25, max_fine=500)
STUDENT = BorrowingPolicy("student", max_loans=3, fine_per_day=10, max_fine=200)
STAFF = BorrowingPolicy("staff", max_loans=10, fine_per_day=0, max_fine=0)
POLICIES = {p.name: p for p in (STANDARD, STUDENT, STAFF)}

Press Run to see every policy's fines for 1, 4 and 30 days late:

Step 1 code
Edit the code, then run it again

POLICIES maps each name to its policy. The menu and the saved file use it in C.6 and C.7 to turn the word "student" back into the policy.

The policy can't be changed by accident

There's only one STUDENT policy, and every student member holds it. So if one line of code changed it, every student would change. The wrong way: press Run.

Step 2 code
Edit the code, then run it again

Read the bottom line: dataclasses.FrozenInstanceError: cannot assign to field 'max_loans'. The policy is a frozen dataclass (lesson 4.4), so once it's made, its fields can't be set. The error comes from line 3, where the change was tried, not later when a student finds they can borrow 30 items.

To give one member a different deal, give them a different policy with set_policy(), as the next step does. To change the rules for every student, change the line where STUDENT is made.

Why is it safe for every student member to hold the same STUDENT object?

A member that stays valid

Member is an ordinary class, because it has rules to keep: an id that's never empty, and a name that's never blank. As in lesson 4.3, its data is in "protected" attributes (_name), read with getters and changed with setters that check first:

How the reference does it library/members.py, lines 27–58
class Member:
    def __init__(self, member_id: str, name: str, policy: BorrowingPolicy = STANDARD) -> None:
        if not member_id.strip():
            raise ValueError("a member needs an id")
        self._member_id = member_id
        self._name = ""
        self.set_name(name)
        self._policy = policy

    def get_id(self) -> str:
        return self._member_id

    def get_name(self) -> str:
        return self._name

    def set_name(self, name: str) -> None:
        if not name.strip():
            raise ValueError("a member needs a name")
        self._name = name.strip()

    def get_policy(self) -> BorrowingPolicy:
        return self._policy

    def set_policy(self, policy: BorrowingPolicy) -> None:
        self._policy = policy

    def check_can_borrow(self, loans_now: int) -> None:
        if loans_now >= self._policy.max_loans:
            raise LimitReached(
                f"{self._name} already has {loans_now} items, "
                f"the most a {self._policy.name} member can borrow"
            )

__init__ uses set_name too, so the check is written once and a new member can't skip it. check_can_borrow asks the policy for the limit, and raises LimitReached, one of the library's own errors from errors.py (C.4 shows the family). The member doesn't count its own loans: the library keeps every loan, and passes the count in.

Step 3 code
Edit the code, then run it again

Ana starts as a student, so a fourth item is refused. After set_policy(STAFF), the same object can borrow 10, and nothing else about Ana changed. A blank new name is refused, and her old one stays.

The same member twice

When the library loads its file again (C.6), it makes new Member objects. They must count as the same members as before. Two members are the same member if they have the same id, so Member writes its own __eq__ (lesson 3.5):

How the reference does it library/members.py, lines 63–69
    def __eq__(self, other: object) -> bool:
        if not isinstance(other, Member):
            return NotImplemented
        return self._member_id == other._member_id

    def __hash__(self) -> int:
        return hash(self._member_id)

Python's rule is that objects that are equal must have the same hash, the number sets and dictionary keys use to find things. Writing __eq__ alone turns hashing off, so Member also writes __hash__, from the same id.

Step 4 code
Edit the code, then run it again

sam and again have the same id, so they're equal, even with different policies, and the set keeps only one of them: 2 members, not 3. Try deleting __hash__ in the library/members.py tab and running it. The last line then fails with TypeError: unhashable type: 'Member'.

Check what you learned

On your computer, write library/errors.py with the error family (it's in C.4, step 4, if you want it now) and library/members.py, and test them. The reference's tests are in tests/test_members.py.

A student becomes a member of staff. How does the reference change their rules?
Which pattern is a Member holding a BorrowingPolicy?
Member writes __eq__. Why must it write __hash__ too?

Sources

Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.

All sources for Simple Python