Skip to content

Python Modules and Packages: import, virtual environments, pip

  • 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.

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 a whole module — access via module.name
import math
print(math.pi) # 3.141592653589793
print(math.sqrt(9)) # 3.0
# Import specific names — no prefix needed
from pathlib import Path
from datetime import datetime, timedelta
# Import with an alias — conventional for large packages
import numpy as np
import pandas as pd
# Import everything — avoid in production code
from 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.

When you write import orders, Python checks in this order:

  1. sys.modules — already-imported modules are cached here.
  2. Built-in modules (compiled into the interpreter, e.g. sys, builtins).
  3. Frozen modules.
  4. The directories in sys.path:
    • The directory containing the script being run.
    • PYTHONPATH environment variable entries.
    • Installation-dependent default paths (including site-packages).
import sys
print(sys.path) # list of directories Python searches

Any .py file is a module. Create orders.py:

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:

main.py
import orders
total = orders.calculate_total(100.00)
print(total) # 108.0
print(orders.format_order_id(42)) # ORD-00042

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:

orders_portal/__init__.py
from .orders import calculate_total, format_order_id
from .customers import get_customer

Then callers can import from the top-level package:

from orders_portal import calculate_total
from orders_portal.payments.stripe import charge

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:

orders.py
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.0

A virtual environment is an isolated Python installation with its own site-packages. Use one per project to avoid dependency conflicts between projects.

Terminal window
# 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 path
which python # Linux/macOS
Get-Command python # Windows
# Deactivate
deactivate

Always activate the virtual environment before installing packages. Never install packages globally unless they are developer tools (pipx handles that case better).

Terminal window
# Install a package
pip install requests
# Install a specific version
pip install requests==2.32.0
# Install from a requirements file
pip install -r requirements.txt
# Upgrade a package
pip install --upgrade requests
# Uninstall
pip uninstall requests
# List installed packages
pip list
# Show details about a package
pip show requests
# Save current environment to a requirements file
pip freeze > requirements.txt

requirements.txt pins exact versions for reproducible installs:

requests==2.32.3
httpx==0.27.2
pydantic==2.8.2

For 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.

Inside a package, use relative imports to refer to sibling modules without hard-coding the package name:

orders_portal/payments/stripe.py
from ..orders import calculate_total # .. goes up one level to orders_portal
from .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.

  • Circular imports. Module A imports B, B imports A. Python partially initializes A before B is loaded, leading to ImportError or 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.py shadows the built-in json module 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 requests fails even though you installed it, because you’re using the system Python, not the venv Python.
  • Committing .venv/ to source control. Add .venv to .gitignore. Only commit requirements.txt or pyproject.toml.
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.py

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.

  • A module is a .py file; a package is a directory with __init__.py.
  • Python searches sys.path to find modules; order matters.
  • Use virtual environments (one per project) to isolate dependencies.
  • pip freeze > requirements.txt captures exact versions for reproducible installs.
  • Use the if __name__ == "__main__": guard to prevent code from running on import.