Sub topic 4
Isolating projects with virtual environments
This chapter assumes you can use pip and the command line, and that you have trained or run a model in a framework such as PyTorch or scikit-learn. It covers what a virtual environment is, how it works inside, how to use one for an ML project, and the errors people hit most often. The next chapter builds on it by adding lock files.
Why isolation matters
A Python installation has one place where packages go. If you install packages with the system interpreter, every project on the machine shares that one set. Project A needs numpy==1.26.4 and project B needs numpy==2.1.0, and only one of them can be installed at a time.
This is a common cause of environment drift. You upgrade a package for one project and an older project quietly changes behavior, or stops importing. Shared installs also make it impossible to answer a basic question: which packages does this project actually need?
A virtual environment is a directory that holds its own Python interpreter link and its own site-packages folder. Packages installed into it are visible only when that environment is active. Each project gets its own set, and nothing you install for one project affects another.
Creating and using an environment
Python ships with the venv module. The usual convention is to create the environment in a .venv folder at the project root.
python3.11 -m venv .venv
source .venv/bin/activate
python -c "import sys; print(sys.prefix)"
pip install numpy scikit-learn
pip list
deactivateOn Windows, the activation command is .venv\Scripts\activate. After activation, python and pip refer to the copies inside .venv. The sys.prefix line prints the path of the active environment, which is a quick way to confirm you are where you think you are.
The interpreter version is fixed when you create the environment. The command above uses Python 3.11 because you named it explicitly. If you had typed python -m venv .venv, you would get whatever python resolved to at that moment, which differs between machines.
How it works inside
A virtual environment is smaller than it first looks. Understanding the mechanism helps when something goes wrong.
venvcreates abindirectory (Scriptson Windows) containing apythonentry that links or copies the base interpreter.- It writes a file named
pyvenv.cfgthat records the base interpreter's location and version. - When the interpreter starts, it finds
pyvenv.cfgnext to itself. It then setssys.prefixto the environment andsys.base_prefixto the original installation. - The
sitemodule adds the environment'slib/python3.11/site-packagestosys.path, so imports find packages there.
Activation does little. The activate script mostly puts .venv/bin at the front of your PATH and changes your prompt. You can skip activation and call .venv/bin/python directly, which is useful in scripts, cron jobs and CI because it removes any dependence on shell state.
.venv/bin/python -m pip install --upgrade pip
.venv/bin/python train.pyUsing python -m pip instead of bare pip guarantees that pip belongs to the interpreter you named.
What an environment does and does not isolate
| Isolated by a virtual environment | Not isolated |
|---|---|
| Installed Python packages | The Python version itself, which comes from the base interpreter |
| Console scripts installed with packages | System libraries such as `libgomp` or `libssl` |
| `sys.path` contents | The CUDA driver and CUDA toolkit on the host |
| Package versions per project | Environment variables, files, and the operating system |
The right-hand column is why virtual environments are not enough for reproducibility. Two machines can have identical site-packages and still differ in Python patch version, glibc, or GPU driver. Later chapters cover those gaps and close them with containers.
Keeping the environment out of Git
An environment is a build product. It contains absolute paths and compiled files tied to one machine, so it cannot be copied to another computer and expected to work. Add it to .gitignore and commit the files that describe it instead.
echo ".venv/" >> .gitignoreWhat you commit is the list of dependencies, which the following chapters turn into a lock file. The rule is that anyone should be able to delete .venv, recreate it from committed files, and get the same result.
rm -rf .venv
python3.11 -m venv .venv
.venv/bin/python -m pip install -r requirements.txtIf recreating the environment is painful, that is a sign the project's dependencies are not properly recorded.
Other tools that create environments
venv is the baseline, but you will meet others.
virtualenvis the older third-party tool thatvenvwas modeled on. It is faster and can find more Python versions.uv venvcreates an environment quickly and can fetch a requested Python version. It is covered with lock tools in a later chapter.condaenvironments isolate more, because they can install Python itself and some native libraries, but they use a different package system from pip.- Poetry and similar tools create and manage the environment for you.
All of them provide the same core idea: a private set of packages per project. The differences matter mainly in what else they can pin.
Common errors
Installing into the wrong environment. You forgot to activate, so pip install modified the system or user packages. Check with python -c "import sys; print(sys.prefix, sys.base_prefix)". Inside an environment the two values differ. Setting PIP_REQUIRE_VIRTUALENV=true makes pip refuse to install outside an environment.
Moving or renaming the folder. Scripts in .venv/bin contain absolute paths. After you move the project, tools fail with "bad interpreter". Delete the environment and recreate it.
The interpreter was upgraded underneath it. If the base Python is removed or upgraded (for example by an OS update), the environment's link breaks or compiled packages stop importing. Recreate the environment.
Mixing --user installs. Packages in your user directory are not visible inside an environment by default. Passing --system-site-packages at creation makes the base packages visible, which defeats isolation. Avoid it for reproducible work.
Notebook kernels pointing at the wrong environment. A Jupyter kernel runs the interpreter it was registered with. If you install packages in .venv but the notebook uses another interpreter, imports fail or load different versions. Check inside the notebook with import sys; print(sys.executable).
A check you can add to a script
A short guard at the top of a training script catches the wrong-interpreter problem early.
import sys
def require_virtualenv() -> None:
if sys.prefix == sys.base_prefix:
raise RuntimeError(
"Not running inside a virtual environment: "
f"sys.prefix is {sys.prefix}"
)
require_virtualenv()
print(f"Using environment: {sys.prefix}")Inside an environment the check passes. Under a plain system interpreter it fails. Containers, which later chapters introduce, are a deliberate exception, because the container itself is the isolation boundary.
Exercise
A teammate says their training script works on their laptop but fails on yours, although both of you use a virtual environment created from the same requirements.txt. Give two things the virtual environment does not isolate that could explain the difference, and one command that shows which interpreter your environment uses.
Show answer
A virtual environment does not isolate the Python version (the base interpreter can differ in minor or patch version) or system-level components such as system libraries and the CUDA driver. Any one of these fits, as would unpinned transitive packages resolved at different times. The command .venv/bin/python -c "import sys; print(sys.version, sys.prefix, sys.base_prefix)" shows the interpreter's version and which environment and base installation it belongs to.
Exercise
Why should .venv be listed in .gitignore, and what should you commit instead?
Show answer
The environment holds machine-specific absolute paths and compiled files, so it cannot be moved to another machine reliably. You commit the files that describe the dependencies, such as requirements.txt or, later, a lock file, so that anyone can delete and recreate the environment from them.