Exercise: Tidy the Gym Memberships

Add type hints to a gym's working but messy membership code until mypy passes, fix the bug mypy finds for a plan that doesn't exist, and tidy the file until ruff check and ruff format have nothing left to change, while the tests prove every answer stays the same.

Journeyman · Python · Software Development · Updated

By

Peak Fitness's membership code gives the right price for every plan the gym sells. It also has no type hints, imports two modules it never uses, has spacing all over the place, and hides a bug: ask it about a plan the gym doesn't sell and it crashes with a message nobody at the front desk could make sense of. You'll do what developers do with code like this every week: add the hints, let mypy find the bug, fix it, and let Ruff tidy the rest, with tests that prove no answer changed along the way.

Get the exercise code

Open this lesson's GitHub repository, github.com/ask-codey/exercise-python-tidy-gym-memberships, also linked from the Exercise box beside the lesson. Clone it into your python-course folder. In VS Code's terminal:

cd ~/python-course
git clone https://github.com/ask-codey/exercise-python-tidy-gym-memberships.git

Git makes a folder, exercise-python-tidy-gym-memberships, with the exercise code inside. Open that folder in VS Code (File > Open Folder), open its terminal with Terminal > New Terminal, and make the exercise's virtual environment. On Windows (PowerShell):

python -m venv .venv
.venv\Scripts\Activate.ps1
pip install -r requirements.txt

On a Mac (zsh):

python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt

This time requirements.txt installs three packages: pytest, mypy and Ruff. The prompt starts with (.venv) once the virtual environment is on.

The folder holds:

  • memberships.py: the gym's four functions, plan_price, monthly_price, cost_for_months and member_line, for you to hint, fix and tidy.
  • report.py: prints the front desk's report with your functions. Ready to use.
  • tests/test_memberships.py: the tests. They call your functions, then run mypy, ruff check and ruff format --check. You don't need to change it.
  • pyproject.toml: the settings for mypy and Ruff, the same ones Checking Types with mypy and Linting and Formatting with Ruff showed. Ready to use.
  • requirements.txt, pytest.ini and .gitignore: the packages, where pytest finds the tests, and what Git leaves out.

What to do

The docstring at the top of memberships.py lists your three jobs, and the docstring under each function says what it returns, with examples. Here's where you start:

def plan_price(code):
    """Return the plan's full monthly price, or None when Peak Fitness has no such plan.

    The code can be in any capitals.

    plan_price("plus") -> 40.0
    plan_price("Premium") -> 60.0
    plan_price("gold") -> None
    """
    return PLANS.get(code.lower())
  1. Add type hints to all four functions: each parameter and each return value. Run mypy . after each one. Until every function has its hints, mypy reports Function is missing a type annotation, because pyproject.toml says every function needs them.
  2. Fix the bug mypy finds. Once the hints are in, mypy reports two lines in monthly_price: the price it works with can be None. Make monthly_price raise a ValueError for a plan Peak Fitness doesn't sell, with the message its docstring gives: monthly_price("gold", False) raises ValueError: Peak Fitness has no plan called 'gold'.
  3. Tidy the file until ruff check . says All checks passed! and ruff format --check . says every file is already formatted.

Keep every function's name, parameters and answers as they are. The only answer that changes is the one for a plan that doesn't exist.

Check your work

Run the tests from the exercise folder, with the virtual environment on:

pytest

At first 11 tests pass and 4 fail. That's expected: the code already gives the right answers for the gym's plans, and those tests make sure it still does when you're done. The four that fail are your work: test 7 (the bug), and tests 13, 14 and 15, which run mypy, ruff check and ruff format --check. A failing checker test shows what the checker printed, starting with a line such as python -m mypy . found something to change:. The checker tests take a few seconds each, since they run real tools.

To see the report, run python report.py. It prints the same lines before and after your changes.

Hints

  • Hints first, then the bug. mypy skips a function that has no hints at all, so it can't see the bug until the hints are in. Checking Types with mypy shows why.
  • Say what plan_price really returns. It gives a float for a plan the gym sells and None for one it doesn't. Type Hints: Saying What a Value Should Be shows the hint for "a float, or None".
  • Read mypy's message from left to right: the file, the line, then what's wrong. The line it names is where a possible None is used as a number.
  • Deal with None before you use the price, with is None, and stop the function with raise ValueError(...) as Raising Your Own Exceptions shows. After that check, mypy knows the price is a float.
  • Let Ruff do the typing. ruff format . fixes the layout and ruff check --fix . removes the unused imports. Ruff leaves one finding for you, with its rule code and line: Linting and Formatting with Ruff reads one with you.

When you're done

Every test is green: pytest's last line says 15 passed. And python report.py prints:

Peak Fitness: members at the front desk
Rosa: Plus, $32.00 a month (student)
Dev: Basic, $25.00 a month
Ana: Premium, $60.00 a month

Rosa's year, with 2 months frozen: 330.0
Is there a gold plan? None

Now look at the first line of each function. Could someone who has never seen this file call cost_for_months correctly from that line alone? That's what your hints bought the next person who reads it.

Submit your exercise

The exercise is how you finish this lesson. When your work is done, put it on GitHub in a repo of your own, then submit that repo's address here. Hand In Your Work with Git walks through each step.

  1. On GitHub, click +, then New repository. Name it (for example exercise-python-tidy-gym-memberships), choose Public, and click Create repository. Leave out the README: your folder already has one.

  2. In VS Code's terminal, in your exercise folder, send your work to your new repo. Point your copy at your own repo, then commit and push:

    git remote set-url origin https://github.com/your-name/exercise-python-tidy-gym-memberships.git
    git add .
    git commit -m "My solution"
    git push -u origin main
    
  3. Paste your repo's address, such as https://github.com/your-name/exercise-python-tidy-gym-memberships, into Submit your exercise on this page. The site checks that the repo is public and holds your commits, and then the lesson is complete.

Changed something after you submitted? Push it, and submit again: your latest submission is the one that counts.

So what

Hints that mypy checks, and a layout nobody has to think about, are what make code safe to hand to the next person, and the tests are how you know tidying it broke nothing.

Key terms

Related