Python Modules and Packages: import, virtual environments, pip
What you’ll learn
Section titled “What you’ll learn”- How Python’s import system finds and loads modules.
- The difference between a module, a package, and a distribution package.
- Creating and using virtual environments with
venv. - Installing, pinning, and managing dependencies with
pip. - Project layout conventions for small scripts and larger applications.
Summary
Section titled “Summary”A module is any .py file. A package is a directory containing an __init__.py file. When you write import orders, Python searches sys.path for a file called orders.py or a directory called orders/ with an __init__.py. Distribution packages — installed with pip — live in site-packages.
Understanding the module system is prerequisite to structuring any Python project beyond a single script.
Save examples as .py files and run with python <filename>.py (Python 3.9+).
Import basics
Section titled “Import basics”# Import a whole module — access via module.nameimport mathprint(math.pi) # 3.141592653589793print(math.sqrt(9)) # 3.0
# Import specific names — no prefix neededfrom pathlib import Pathfrom datetime import datetime, timedelta
# Import with an alias — conventional for large packagesimport numpy as npimport pandas as pd
# Import everything — avoid in production codefrom math import *Why avoid from module import *: it pollutes the namespace and makes it impossible to tell where a name came from without reading the entire file. Use explicit imports.
How Python finds modules
Section titled “How Python finds modules”When you write import orders, Python checks in this order:
sys.modules— already-imported modules are cached here.- Built-in modules (compiled into the interpreter, e.g.
sys,builtins). - Frozen modules.
- The directories in
sys.path:- The directory containing the script being run.
PYTHONPATHenvironment variable entries.- Installation-dependent default paths (including
site-packages).
import sysprint(sys.path) # list of directories Python searchesCreating a module
Section titled “Creating a module”Any .py file is a module. Create orders.py:
"""Order management utilities for OrdersPortal."""
TAX_RATE = 0.08
def calculate_total(subtotal: float) -> float: """Return subtotal plus tax.""" return round(subtotal * (1 + TAX_RATE), 2)
def format_order_id(raw_id: int) -> str: """Format a numeric ID as an ORD- prefixed string.""" return f"ORD-{raw_id:05d}"Use it from another file in the same directory:
import orders
total = orders.calculate_total(100.00)print(total) # 108.0print(orders.format_order_id(42)) # ORD-00042Creating a package
Section titled “Creating a package”A package groups related modules into a directory:
orders_portal/├── __init__.py # makes this a package├── orders.py├── customers.py└── payments/ ├── __init__.py ├── stripe.py └── paypal.py__init__.py can be empty or can expose a public API:
from .orders import calculate_total, format_order_idfrom .customers import get_customerThen callers can import from the top-level package:
from orders_portal import calculate_totalfrom orders_portal.payments.stripe import chargeThe __name__ guard
Section titled “The __name__ guard”Every module has a __name__ attribute. When a file is run directly, __name__ is "__main__". When it is imported, __name__ is the module name. This lets you include runnable examples without executing them on import:
def calculate_total(subtotal: float) -> float: return round(subtotal * 1.08, 2)
if __name__ == "__main__": # Only runs when this file is executed directly, not when imported print(calculate_total(50.00)) # 54.0Virtual environments
Section titled “Virtual environments”A virtual environment is an isolated Python installation with its own site-packages. Use one per project to avoid dependency conflicts between projects.
# Create a virtual environment in .venv/python -m venv .venv
# Activate (Linux/macOS)source .venv/bin/activate
# Activate (Windows PowerShell).venv\Scripts\Activate.ps1
# Confirm: should show the .venv pathwhich python # Linux/macOSGet-Command python # Windows
# DeactivatedeactivateAlways activate the virtual environment before installing packages. Never install packages globally unless they are developer tools (pipx handles that case better).
pip: installing and managing dependencies
Section titled “pip: installing and managing dependencies”# Install a packagepip install requests
# Install a specific versionpip install requests==2.32.0
# Install from a requirements filepip install -r requirements.txt
# Upgrade a packagepip install --upgrade requests
# Uninstallpip uninstall requests
# List installed packagespip list
# Show details about a packagepip show requests
# Save current environment to a requirements filepip freeze > requirements.txtrequirements.txt pins exact versions for reproducible installs:
requests==2.32.3httpx==0.27.2pydantic==2.8.2For more reliable dependency resolution and lock files, consider uv (a fast pip replacement) or poetry. For simple projects, pip with a requirements.txt is sufficient.
Relative imports
Section titled “Relative imports”Inside a package, use relative imports to refer to sibling modules without hard-coding the package name:
from ..orders import calculate_total # .. goes up one level to orders_portalfrom .paypal import process_refund # . refers to the current package (payments)Relative imports only work inside packages (not in top-level scripts). Use absolute imports in scripts.
Common mistakes
Section titled “Common mistakes”- Circular imports. Module A imports B, B imports A. Python partially initializes A before B is loaded, leading to
ImportErroror missing attributes. Fix by restructuring (extract shared code into a third module) or by moving imports inside functions. - Naming a file the same as a standard library module. A file called
json.pyshadows the built-injsonmodule in that directory. - Installing packages globally. Packages installed globally affect every project on the machine. Always use a virtual environment.
- Forgetting to activate the virtual environment.
import requestsfails even though you installed it, because you’re using the system Python, not the venv Python. - Committing
.venv/to source control. Add.venvto.gitignore. Only commitrequirements.txtorpyproject.toml.
Project layout reference
Section titled “Project layout reference”orders-portal/├── .venv/ # virtual environment (not committed)├── .gitignore├── requirements.txt # or pyproject.toml├── README.md├── orders_portal/ # your package│ ├── __init__.py│ ├── orders.py│ ├── customers.py│ └── payments/│ ├── __init__.py│ └── stripe.py└── tests/ ├── __init__.py └── test_orders.pyInterview questions
Section titled “Interview questions”1. What is the difference between a module, a package, and a distribution package?
A module is a single .py file. A package is a directory of modules with an __init__.py. A distribution package is what you install with pip — it may contain one or many modules and packages. The word “package” in everyday conversation usually means a distribution package, but technically it refers to a directory-based group of modules.
2. What happens when you run import orders and there is both an orders.py in the current directory and an orders package installed in site-packages?
Python searches sys.path in order. The current directory (or the script’s directory) comes first by default, so the local orders.py is found first and shadows the installed package. This is a common source of confusion — name local files carefully to avoid shadowing standard library or third-party modules.
3. Senior scenario: an OrdersPortal service has ten Python microservices sharing a common orders_portal utility library. How do you manage the shared code?
Package the shared library as a proper distribution package (pyproject.toml, versioned releases). Host it on a private PyPI registry (AWS CodeArtifact, Azure Artifacts, or a simple pypiserver). Each microservice pins the version it needs in its requirements.txt. This gives each service independent upgrade control, reproducible installs, and clear versioning — avoiding the “shared directory on a network drive” anti-pattern that leads to implicit coupling.
Key takeaways
Section titled “Key takeaways”- A module is a
.pyfile; a package is a directory with__init__.py. - Python searches
sys.pathto find modules; order matters. - Use virtual environments (one per project) to isolate dependencies.
pip freeze > requirements.txtcaptures exact versions for reproducible installs.- Use the
if __name__ == "__main__":guard to prevent code from running on import.
Related pages
Section titled “Related pages”- Python install guide — setting up Python 3.14 with venv
- Python tools overview — pip, uv, poetry, pyenv
- Functions and lambdas — the previous article in this series
- Object-oriented programming — the next article in this series
Official references
Section titled “Official references”- Python docs: Modules — official tutorial chapter
- Python docs: The import system — complete import reference
- pip documentation — pip user guide
- PEP 517 / PEP 518 —
pyproject.tomlbuild system standard