4.2 Modules and Packages
Python modules and packages help structure larger codebases for reuse and maintainability.
Modules
A module is a .py file containing definitions and statements.
import mymodule
from mymodule import helper
Script entry point pattern
if __name__ == "__main__":
main()
When run directly, __name__ is "__main__"; when imported, module-level entry logic does not execute.
Import search path
sys.path determines where imports are resolved from, including script directory and environment locations.
Packages
A regular package is a directory containing __init__.py that organizes related modules.
Python also supports namespace packages (an advanced case) that may not include __init__.py.
Example import patterns:
from package import submodule
from package.submodule import function
Use explicit imports in production code; avoid wildcard imports (from x import *) except for limited interactive exploration.
Official references
- Tutorial modules: https://docs.python.org/3/tutorial/modules.html
- Import statement reference: https://docs.python.org/3/reference/simple_stmts.html#import