Chapter 07
Modules, packages and pip
Create a module
A module is typically a .py file. A package is a directory of modules, usually with an __init__.py for a regular package.
# utils.py
def greet(name):
return f"Hello, {name}"
# main.py
from utils import greet
print(greet("Ada"))Hands-on lab: Split one program into main.py and utils.py.
Dependencies
Use python -m pip to install packages in the active environment. easy_install is obsolete and should not be used for modern projects.
python -m pip --version
python -m pip list
python -m pip freeze > requirements.txtHands-on lab: Create a fresh virtual environment and reinstall project dependencies.
Module search and __main__
Imports resolve using the module search path. Avoid shadowing standard library names and use the main guard for executable modules.
python -c "import sys; print(sys.path)"Hands-on lab: Explain the difference between importing and executing a module.