Skip to content
Visual explainer 3h to learn 4 steps

Modules, packages, venv & pip

Structure a project into modules and manage dependencies in a virtual environment.

By Invicly Tech, , in Full DevOps with Python. About 11 minutes to read.

Topic 6 of 34

In short

Modules and packages organise Python code into importable files and folders. A virtual environment gives each project its own Python packages, so projects never fight over versions.

Explained simply

As a script grows, one file is not enough. A module is just a .py file, and you can import its functions into another file. A package is a folder of modules. Splitting code this way keeps each file small and lets tests import exactly the piece they need.

Python projects also depend on code other people wrote, like requests or PyYAML. pip downloads those packages from PyPI (the Python Package Index, the public package store). The problem: if every project installs into the same place, one project's upgrade can break another.

A virtual environment (venv) solves this. It is a folder, usually called .venv, with its own python command and its own place for packages. When it is active, pip installs into that folder only. Delete the folder and the project is clean again.

Finally, you write down exactly which versions you used, usually in requirements.txt. A teammate, a CI server or a Docker build reads that file and installs the same versions. That is how "works on my machine" becomes "works on every machine".

Press Play on a diagram to walk through it one step at a time.

LayersWhere your imports come from
  1. 1
    Your project code

    main.py imports from your own package folder.

  2. 2
    Virtual environment .venv

    Project-only packages installed by pip.

  3. 3
    Standard library

    Modules shipped with Python, like json and pathlib.

  4. 4
    Python interpreter

    The python binary the venv was created from.

SequenceWhat pip install -r requirements.txt does
You
pip
PyPI
.venv
  1. 1pip install -r requirements.txt
    You to pip: pip install -r requirements.txt
  2. 2Ask for requests==2.32.3
    pip to PyPI: Ask for requests==2.32.3
  3. 3Wheel file plus its dependency list
    PyPI to pip: Wheel file plus its dependency list
  4. 4Fetch dependencies like urllib3 and idna
    pip to PyPI: Fetch dependencies like urllib3 and idna
  5. 5Unpack everything into site-packages
    pip to .venv: Unpack everything into site-packages
  6. 6Successfully installed ...
    pip to You: Successfully installed ...
MapA typical small Python project
diskcheck/
  • pyproject.toml
    • Name, version, dependencies
    • Console script entry point
  • src/diskcheck/
    • __init__.py
    • cli.py (argparse, main)
    • core.py (logic)
  • tests/
    • test_core.py
    • conftest.py for shared fixtures
  • requirements.txt
    • Exact pins for deploys and CI
  • .gitignore
    • .venv/
    • __pycache__/

In depth

How import finds a module

When you write import tools, Python searches the folders listed in sys.path, in order, and uses the first match. The list starts with the folder of the script you ran (or the current folder when you use python -m), then any folders in the PYTHONPATH variable, then the standard library, then site-packages, where pip puts installed packages. Once loaded, a module is cached in sys.modules, so importing it again is free and its top-level code runs only once.

The first-match rule causes a classic bug: name your own file json.py or requests.py and it hides the real library. Avoid names that clash with the standard library or your dependencies.

The check if __name__ == "__main__": lets a file work both as an importable module and as a script. The block runs only when the file is executed directly.

  • python -c "import sys; print(sys.path)" prints the search list
  • python -m mytool.cli runs a module that lives inside a package
  • A folder with __init__.py is a regular package
FlowWhere import tools looks, in order
  1. 1
    sys.modules

    Already imported? Reuse it

  2. 2
    Script folder

    Or the current folder with -m

  3. 3
    PYTHONPATH

    Extra folders you set

  4. 4
    Standard library

    json, pathlib, subprocess

  5. 5
    site-packages

    Packages pip installed

  6. 6
    Not found

    ModuleNotFoundError

What a venv really is

A venv is less magic than it looks. python3 -m venv .venv creates a folder with a pyvenv.cfg file that points to the base interpreter, a bin folder (Scripts on Windows) holding python and pip, and lib/pythonX.Y/site-packages for packages. The python inside is a link to the original interpreter; at startup Python notices pyvenv.cfg and switches to the venv's package folder.

source .venv/bin/activate only changes your current shell: it puts .venv/bin first on PATH and sets VIRTUAL_ENV. You can skip it by calling .venv/bin/python directly, which is the reliable choice in cron jobs, systemd units and Dockerfiles.

A venv is tied to its location and to the Python it was made from. Moving or copying it breaks the paths written inside its scripts, and upgrading the system Python can break it too. Treat it as disposable: delete it and recreate it from requirements.txt.

MapInside .venv after python3 -m venv .venv
.venv
  • pyvenv.cfg
    • home = folder of the base Python
    • version of that Python
  • bin/
    • python and python3 links
    • pip
    • activate scripts for each shell
  • lib/python3.X/site-packages/
    • Where pip installs packages
    • Only pip at the start

Pinning versions without pain

pip install requests installs the newest version today, and maybe a breaking one next month. Version specifiers control this: ==2.32.3 means exactly that version, >=2.32 means that or newer, and ~=2.32.0 is the compatible release operator, meaning at least 2.32.0 but below 2.33.

pip freeze prints every installed package with its exact version, including the dependencies of your dependencies (transitive dependencies). That works as a lock file, but it mixes what you chose with what came along. Many teams keep a short requirements.in with their direct choices and generate the fully pinned requirements.txt from it with pip-compile from the pip-tools project.

For stricter builds, pin hashes too. pip install --require-hashes -r requirements.txt refuses any download whose checksum does not match the file, which protects you against a tampered package.

  • == exact, >= minimum, ~= compatible release, != exclude
  • pip list --outdated shows what could be upgraded
  • pip check reports missing or conflicting dependencies

pyproject.toml and installable tools

Modern Python projects describe themselves in pyproject.toml. The [project] table holds the name, version, required Python version and dependencies. A [project.scripts] entry like mytool = "mytool.cli:main" makes pip create a mytool command that calls that function.

During development run pip install -e . (an editable install). Your package becomes importable from anywhere in the venv, and code changes apply without reinstalling. Many projects use a src layout (src/mytool/...) so tests import the installed package instead of a folder that just happens to be on the path.

A common modern error: on recent Debian and Ubuntu releases (and some other distributions), pip install outside a venv fails with externally-managed-environment. That is deliberate (PEP 668): the system Python belongs to the operating system's package manager. Use a venv for projects, or pipx for standalone command-line tools.

Learn it in 4 short steps

About 45m each. Track them with a timer in your plan.

  1. 1
    Split code into modules and packages~45m
  2. 2
    Create and activate a venv~45m
  3. 3
    Install and pin packages with pip~45m
  4. 4
    Freeze dependencies to requirements.txt~45m

Key points

  • A module is one .py file; a package is a folder of modules you import together.
  • Create one venv per project and activate it before installing anything.
  • Pin versions in requirements.txt so every machine installs the same packages.
  • Never commit the .venv folder; commit requirements.txt instead.

Key terms

Tap a card to flip it. 0/5 known

Examples

bash
python3 -m venv .venv
source .venv/bin/activate
pip install requests==2.32.3 pyyaml
pip freeze > requirements.txt
echo ".venv/" >> .gitignore
# later, on another machine
pip install -r requirements.txt
python -m mytool.cli --help

Create, use and reproduce a virtual environment.

Turn a script into an installable command

You have a disk-check script that teammates keep copying around. Step 1: move the code into src/diskcheck/ with a cli.py that has a main() function. Step 2: write a pyproject.toml with the name, dependencies and a [project.scripts] entry. Step 3: in a fresh venv, run pip install -e . during development. Step 4: now diskcheck is a real command on PATH inside that venv, and anyone can install it the same way, or with pipx from a git URL.

toml
[project]
name = "diskcheck"
version = "0.1.0"
requires-python = ">=3.10"
dependencies = ["pyyaml>=6"]

[project.scripts]
diskcheck = "diskcheck.cli:main"

[build-system]
requires = ["setuptools>=68"]
build-backend = "setuptools.build_meta"

# then: pip install -e .   and run: diskcheck --help

Rebuild a broken environment

After a system Python upgrade your tool fails with ImportError or "No such file or directory" for .venv/bin/python. Step 1: check which interpreter is actually running. Step 2: throw the old venv away; it is disposable. Step 3: create a new one and install from requirements.txt, calling the venv's python directly so there is no doubt where packages go. Step 4: run pip check and the tests to confirm everything resolves.

bash
which python; python --version      # which interpreter is active?
deactivate 2>/dev/null
rm -rf .venv
python3 -m venv .venv
.venv/bin/python -m pip install --upgrade pip
.venv/bin/python -m pip install -r requirements.txt
.venv/bin/python -m pip check
.venv/bin/python -m pytest -q

Quick reference

  • python3 -m venv .venv creates a venv; source .venv/bin/activate turns it on
  • python -m pip install X guarantees pip matches the python you are running
  • pip freeze > requirements.txt records the exact version of everything installed
  • pip install -r requirements.txt reproduces the environment on another machine
  • ~=2.32.0 means >=2.32.0 and <2.33; == pins one exact version
  • pip install -e . installs your own project in editable mode
  • python -c "import sys; print(sys.prefix)" shows which environment is active
  • Add .venv/ to .gitignore; commit requirements.txt, never the venv

Common mistakes

  • Installing packages with sudo pip into the system Python.
  • Forgetting to activate the venv, so pip installs somewhere else.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1You created a file named json.py next to your script, and now import json behaves strangely. Why?

Question 2

2Which versions does the specifier ~=1.4.2 allow?

Question 3

3In a cron job, what is the most reliable way to run a script inside a venv?

Question 4

4pip install fails with externally-managed-environment. What is the right fix?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Create a venv, install requests into it, and prove where it was installed. Then show that the system python3 cannot import it (if it was not already installed there).

  2. Exercise 2medium

    Split a one-file script into a package mytool with core.py (the logic) and cli.py (argparse and main), and run it with python -m mytool.cli from the project root.

  3. Exercise 3hard

    Use pip-tools: keep direct dependencies in requirements.in, compile a fully pinned requirements.txt with hashes, then install it with --require-hashes into a brand-new venv.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Do I need to activate the venv every time?
Only for interactive work in a shell. Scripts, cron jobs, systemd units and Dockerfiles can call .venv/bin/python directly, which needs no activation.
What is the difference between pip and pipx?
pip installs libraries into the current environment. pipx installs a command-line application into its own hidden venv and puts just the command on your PATH, which is ideal for tools like ansible or httpie.
Should I use uv, Poetry or plain pip?
All work. uv is a very fast replacement for pip and venv, and Poetry manages pyproject.toml and a lock file for you. Plain venv plus pip is built in and works everywhere, which is why this path uses it.
Why does the python command not exist on my Linux server?
Many distributions only ship python3. Use python3 outside a venv; inside an activated venv, python and python3 both work.

Go deeper

ShareXLinkedInWhatsApp