Learning goals
Split a program into files, import reusable code, and isolate installed dependencies.
Explanation
A module is typically a .py file containing definitions. An import makes its contents available to another module. A regular package groups modules in a directory with an __init__.py file. Namespace packages are an exception to that file requirement, but use regular packages in this course.
Built-in and standard library modules ship with Python. Third party packages need installation. A virtual environment isolates a project's Python packages so different projects can use different dependencies.
Example 1 Your own module
Create these two files in the same folder. File price_tools.py:
def subtotal(quantity, unit_price):
return quantity * unit_price
if __name__ == "__main__":
print(subtotal(2, 50))File main.py:
import math
import price_tools
from datetime import date
print(price_tools.subtotal(3, 100))
print(math.isqrt(81))
print(date(2026, 9, 23).isoformat())Run main.py. Expected output: 300, 9, and 2026-09-23. The guarded print in price_tools does not execute during import; it executes when you run that file directly.
Example 2 A regular package
Create a folder named shop beside main.py. Inside it, create an empty __init__.py and copy price_tools.py. Change the import and call in main.py:
from shop.price_tools import subtotal
print(subtotal(4, 25))Expected output: 100. Start from the project folder so the package can be found. Avoid wildcard imports because they make it harder to know where names originate.
Environment and package commands
On Windows, using the environment's interpreter directly avoids activation issues:
py -m venv .venv
.venv\Scripts\python.exe -m pip install requests
.venv\Scripts\python.exe -m pip show requests
.venv\Scripts\python.exe main.pyOn macOS or Linux, create it with python3 -m venv .venv and use .venv/bin/python for the subsequent commands. Activation is optional: PowerShell uses .\.venv\Scripts\Activate.ps1; POSIX shells use source .venv/bin/activate. After activation, python normally resolves to the environment's interpreter. deactivate leaves it.
Student tasks
1. Create geometry.py with rectangle_area and square_area. Import both into main.py and print verified results.
2. Put geometry.py into a shapes package and update the import.
3. Create a virtual environment and record the interpreter path using import sys followed by print(sys.executable).
4. Explain why naming your own file math.py could break an import.
Completion check: show the files, successful imports, and which interpreter ran the program.