Python Foundations·Build real programs

Modules and packages

Split code into files, reuse the standard library and guard scripts.

Beginner 11 min read Lesson 13 of 480 Challenge included
What you will be able to do
  • 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.

modules.pyPython
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())
  1. 01
    Create the file

    Put related functions in a module such as tracker.py.

  2. 02
    Import it

    Use from tracker import load_progress in the script that needs it.

  3. 03
    Guard the entry point

    Only call main() when the file runs directly.

  4. 04
    Group later

    Move related modules into a package folder with an __init__.py.

Your turn

Parse a JSON payload

Medium

Parse the JSON text, then print the learner and progress in the form "Ada: 7/12".

PYTHON · starter
import json

payload = '{"learner": "Ada", "completed": 7, "total": 12}'
# your code here
Check your understanding before moving on.
Knowledge checkQuestion 1

What is the main purpose of if __name__ == "__main__"?

Select an answer to continue
Study tools

Make it yours.

Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.

Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign in
Finished reading?

Lock in what you just learned.

Mark this lesson complete to save your place and move one step closer to the certificate.

Next: Testing with pytest
Lesson 13 of 480 · 0% of course