Modules, Packages, and Virtual Environments¶
As your program grows, splitting code into reusable files and packages becomes necessary. Python uses modules and packages for code organization, and virtual environments for isolated dependency management.
1. Modules¶
A module is simply a Python file containing statements and definitions ending in .py.
Suppose you create a file named math_utils.py:
You can now import it in another script:
Import Styles¶
# Direct import
import math
print(math.sqrt(25))
# Specific attribute import
from math import sqrt, ceil
print(sqrt(25))
# Import with alias
import datetime as dt
print(dt.date.today())
Module Search Path (sys.path)¶
When a module named example is imported, the interpreter searches for it in this sequence: 1. Built-in modules compiled into the interpreter. 2. The directory containing the input script (or the current directory). 3. PYTHONPATH (a list of directory names). 4. Installation-dependent default directory (site-packages).
These paths are stored in the list sys.path:
2. Packages (__init__.py)¶
A package is a directory that contains multiple modules. It typically contains an __init__.py file:
Exposing Package Contents¶
Inside my_package/__init__.py:
Users can import from the package directly:
3. Virtual Environments (venv)¶
A virtual environment is a self-contained directory tree that contains a specific Python installation plus several additional packages. It prevents dependency conflicts between different projects.