Modules, packages & the import system
Writing modules, building packages, virtual environments and pip.
Writing and importing your own modules
Any .py file is a module; splitting code into modules is how programs grow past a single file.
Any .py file can serve as a module that other files import by its filename without the extension — as long as Python's import system can actually locate it, through sys.path, the enclosing package, or another import finder; a file sitting outside all of those is not importable just by existing. On the normal first import in a running interpreter, a module's top-level code runs once, and the result — every function, class and variable it defines — becomes accessible through the module's namespace and is cached in sys.modules, so a later import of the same module reuses that cached module object instead of re-running its code. Splitting a growing single-file script into multiple focused modules (one for data access, one for calculations, one for the command-line interface, for example) keeps each file's purpose clear and makes individual pieces easier to test in isolation.
Key points
- A .py file is importable by filename when Python's import system can find it (sys.path, package, etc.)
- A module's top-level code runs once, the first time it is imported
- Splitting a growing script into focused modules keeps each file's purpose clear
Code
# geometry.py
def rectangle_area(w, h):
return w * h
# main.py
from geometry import rectangle_area
print(rectangle_area(3, 4))A small helper function moved into its own module and imported by name from another file.
Common pitfalls
- Naming your own file the same as a standard-library module (like random.py) can shadow the real one and break unrelated imports
- Circular imports (module A imports B, which imports A) can expose a partially initialized module and cause ImportError, AttributeError, or other confusing failures — some complete successfully, but circular imports are usually a design smell worth restructuring
Practice exercise
Split a single script that validates emails and formats phone numbers into two modules, validators.py and formatters.py, then import both from a new main.py.
Packages and __init__.py
A package is a directory of modules; __init__.py runs on first import and can define what the package exposes.
A directory containing an __init__.py file (even an empty one) is a regular package, letting related modules be organized under one dotted name, like myapp.utils.strings; Python also supports namespace packages with no __init__.py at all, useful when one logical package's modules are split across multiple locations, though a regular package with an explicit __init__.py remains the normal choice for an ordinary project. __init__.py runs automatically the first time anything inside the package is imported, and commonly re-exports a curated set of names from deeper submodules so callers can write the shorter from myapp import helper_function instead of the fully-qualified from myapp.utils.strings import helper_function. This lets a package's internal file layout change without breaking its public import surface.
Key points
- A directory with __init__.py is a regular package with a dotted name; namespace packages can omit __init__.py
- __init__.py runs once, on the package's first import
- Re-exporting names in __init__.py gives a short, stable public import path
Code
# myapp/utils/strings.py
def slugify(text):
return text.lower().replace(" ", "-")
# myapp/__init__.py
from .utils.strings import slugify
# elsewhere
from myapp import slugifyRe-exporting a deeply nested function through __init__.py so callers use a short import path.
Common pitfalls
- Running a module inside a package directly with
python myapp/utils/strings.pybreaks its relative imports - An __init__.py that re-exports too much can create circular import problems between submodules
Practice exercise
Turn validators.py and formatters.py from the previous exercise into a package named toolkit with an __init__.py that re-exports validate_email and format_phone directly.
Virtual environments and pip
Every project gets its own isolated set of installed packages, so projects never fight over dependency versions.
python -m venv .venv creates an isolated virtual environment in the .venv directory, and activating it (source .venv/bin/activate on macOS/Linux, .venv\Scripts\activate on Windows) points python and pip at that isolated environment instead of the system-wide installation. pip install package_name then installs a package only into the active environment, and pip freeze > requirements.txt records the exact installed distribution versions, which meaningfully improves repeatability when another machine installs from that file with pip install -r requirements.txt — but it does not by itself guarantee an identical environment, since the target machine's Python version, OS/architecture, and available package artifacts can still differ. Stronger reproducibility comes from hash-checked installs (pip install --require-hashes) or a dedicated lock-file format such as the standardized pylock.toml (PEP 751). Every real project should still have its own virtual environment, never sharing one across unrelated projects.
Key points
- python -m venv .venv creates an isolated environment for one project
- Activating the environment points python and pip at it instead of the system installation
- pip freeze records exact versions, improving repeatability — but hashes/lock files go further toward true reproducibility
Code
python -m venv .venv
source .venv/bin/activate # .venv\Scripts\activate on Windows
pip install requests
pip freeze > requirements.txt
# on another machine:
python -m venv .venv && source .venv/bin/activate
pip install -r requirements.txtCreating a virtual environment, installing a package, freezing the exact version, and reproducing it elsewhere.
Common pitfalls
- Installing packages globally with pip (outside any venv) risks version conflicts between unrelated projects
- Forgetting to activate the venv before pip install puts the package somewhere unexpected
Practice exercise
Create a new virtual environment, install the requests package into it, generate a requirements.txt, and explain in one or two sentences what pip freeze does and does not guarantee about reproducing your exact environment on another machine.