39
Packages
Packages: Directory-Level Organization for Multi-Module Code
What might confuse you right now
"I already know modules. Why do I need packages?"
When you've got a bunch of modules, you need directory-level structure. A package is basically "a collection of modules + a namespace."
One-line definition
A package is a directory containing multiple modules, typically marked and managed by __init__.py.
Real-life analogy
A module is like a book. A package is like a section on a bookshelf.
Minimal runnable example
myapp/
__init__.py
math_utils.py
string_utils.py
from myapp.math_utils import add
print(add(2, 3))
Quick quiz (5 min)
- Create a
utilspackage. - Add two modules inside it and import from them.
- Use
__init__.pyto expose a unified entry point.
Quiz answer guidelines & grading criteria
- Answer direction: working code that covers core conditions and edge inputs from the prompt.
- Criterion 1 (Correctness): Main flow produces correct results, key branches execute.
- Criterion 2 (Readability): Clear variable names, no excessive nesting.
- Criterion 3 (Robustness): Basic protection against null values, type errors, or unexpected input.
Transfer task (homework)
Take your existing utility functions and split them into three modules (string/number/file), all under one package.
Acceptance criteria
You can independently:
- Create a package directory structure
- Import functions across modules
- Manage a package's public API
Common errors & debugging steps (beginner edition)
- Can't understand the error: read the last line for the error type (e.g.,
TypeError,NameError), then trace back to the relevant code line. - Not sure about a variable's value: temporarily add
print(variable, type(variable))at key points to verify data matches expectations. - Code changes aren't taking effect: confirm the file is saved, you're running the right file, and your terminal environment (venv) is correct.
Common misconceptions
- Misconception: Any directory is automatically a package.
- Reality: You need a clear import path and well-defined structural responsibilities.