Modules and packages
Split code into files, reuse the standard library and guard scripts.
- Import modules and specific names
- Use pathlib, json and datetime
- Guard executable code with __main__
A module is a Python file. A package is a folder of modules. The standard library already solves common problems, so import before you build.
import json
from datetime import date
from pathlib import Path
payload = {"learner": "Ada", "completed": 7}
text = json.dumps(payload, indent=2)
print(text)
loaded = json.loads(text)
print(loaded["completed"])
path = Path("progress.json")
print(path.name, path.suffix)
print(date(2026, 10, 27).isoformat())- 01Create the file
Put related functions in a module such as tracker.py.
- 02Import it
Use from tracker import load_progress in the script that needs it.
- 03Guard the entry point
Only call main() when the file runs directly.
- 04Group later
Move related modules into a package folder with an __init__.py.
Parse a JSON payload
Parse the JSON text, then print the learner and progress in the form "Ada: 7/12".
import json
payload = '{"learner": "Ada", "completed": 7, "total": 12}'
# your code hereWhat is the main purpose of if __name__ == "__main__"?
Make it yours.
Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.
Lock in what you just learned.
Mark this lesson complete to save your place and move one step closer to the certificate.