Up Next: Automation

Look back at what Module 4 taught, tests with pytest, type hints checked by mypy and tidy code from Ruff, try a library fines calculator of your own written test first, and see what Module 5 adds, scripts that sort files, take options, run on a schedule and fetch live data.

Journeyman · Python · Updated

By

After this lesson you can

  • Describe what file automation, command-line options, scheduled runs and web APIs will let your scripts do

Key takeaways

  • After Module 4 you can prove your code works with pytest, say what each function takes and returns with type hints that mypy checks, and keep every file tidy with Ruff.
  • A fines calculator written test first puts all of it to work, with a test for each rule written before the code that meets it.
  • So far your programs run when you start them and work on values you hand them. Module 5 points them at real folders, real options and live data from the web.
  • Module 5's scripts sort and rename files, take options such as --dry-run, run on a schedule without you, and fetch a weather forecast from a web API.

At the start of this module, you knew your code worked because you ran it and looked. Now you have proof that runs itself: tests that check every rule in seconds, hints that say what each function takes and returns, and a checker and a linter that read your code before anyone runs it. That's how working programmers keep code they can change without fear.

This lesson looks back at what you can do, gives you a project to try with all of it, and shows what Module 5 adds: scripts that do real work on your computer while you do something else.

What you can do now

After Module 4, you can:

  • write tests with pytest: test_ functions with assert (read "make sure that"), run with python -m pytest, and read what a failing test tells you;
  • test the edges: zero, an empty list, the exact boundary, errors with pytest.raises, and many examples in one test with @pytest.mark.parametrize;
  • set up and clean up with fixtures, temporary files with tmp_path, and printed output with capsys;
  • say what a value should be with type hints such as list[float] and str | None, and let mypy find the line where a value can't be what its hint promises;
  • keep code tidy with Ruff: ruff check for likely mistakes, ruff format for one layout everywhere.

Here's a small piece of a fines calculator for a town library, with its checks right under it. Each assert stops the program if its comparison is false, so the last line prints only when all three are right. min() gives back the smaller of its values, which here keeps a fine from going over the cap:

def late_fee(days_late: int, daily_rate: float, cap: float) -> float:
    return min(days_late * daily_rate, cap)


assert late_fee(0, 0.25, 5.0) == 0
assert late_fee(4, 0.25, 5.0) == 1.0
assert late_fee(30, 0.25, 5.0) == 5.0
print("All three checks passed.")
All three checks passed.

Put it all together: a library fines calculator

Here's a way to prove it to yourself: build the whole fines calculator for a town library, test first. Make a folder of your own, library-fines, with a virtual environment that has pytest, mypy and Ruff, and work through the rules one at a time. For each rule, write the test, watch it fail, then write the code that makes it pass:

  • a daily rate by kind of item: 25 cents a day for a book, $1.00 for a DVD, 50 cents for a board game;
  • a cap per item, so a book that's three months late costs no more than $5.00;
  • no fine for days the library was closed, such as a holiday in the middle of the late days;
  • a receipt that lists each item, its fine and the total.

Use @pytest.mark.parametrize for the rates, an edge-case test for the exact cap, type hints that pass mypy ., and a file that ruff check . and ruff format --check . leave alone. When every check is green, you have a tool you could show anyone and explain line by line.

Where it still needs you

Look at how every program so far has started: you open the terminal and type python something.py. It works on values you wrote into the file, typed in, or put in a file it knows by name. Then it stops, and nothing happens until you run it again.

The jobs that save people the most time aren't like that. A Downloads folder with 400 files in it needs sorting by kind and by month, and you shouldn't have to edit the script to point it at another folder. A report should build itself every Monday morning, before you're awake. And the most useful data, such as this weekend's weather, isn't in a file on your computer at all: it lives on a server, and changes by the hour.

What Module 5 unlocks

Module 5 puts your Python to work on your own computer and the web:

  • Files and folders: pathlib finds, lists and names files; shutil copies and moves them, after a dry run that shows what it would do. The example is a messy Downloads folder.
  • From script to tool: argparse gives a script options, such as --dry-run, and a free --help page.
  • On a schedule: Task Scheduler on Windows and cron on a Mac run a script for you, every day or every Monday, and a log file says what happened.
  • Web APIs: the requests package fetches live data from a web API, here the US National Weather Service's forecast for a camping trip, and a saved copy keeps your script working when the network is down.

Here's a taste of pathlib, which treats a file's path as something with parts you can ask for:

from pathlib import Path

photo = Path("Downloads") / "beach-day.jpg"
print(photo.name)
print(photo.suffix)
print(photo.parent)
beach-day.jpg
.jpg
Downloads

/ between two parts joins them into one path, the right way for Windows and for a Mac. A sorting script asks every file for its .suffix and sends .jpg files to a Pictures folder. Everything you built in this module comes with you: the sorter gets tests, hints and a clean bill from Ruff, like the rest of your code.

Check yourself

2 questions to try on the lesson page.

So what

Module 4 gave you proof that your code works and stays readable; Module 5 points that code at real folders, real schedules and live data, where it saves you real time.

Key terms

Related