Sub topic 5
Isolating the Environment
This chapter assumes you can run Python and Jupyter, use a terminal, and install packages with pip. It covers why a notebook needs its own environment, how to create one, and how to connect it to Jupyter. Pinning exact versions is the next chapter's topic.
Why a shared environment breaks results
Python installs packages into a single location by default. Every project that uses that interpreter shares those packages. Three problems follow.
- Version conflicts. Project A needs
pandas1.5 and project B needspandas2.2. Only one can be installed at a time. - Silent drift. Upgrading a package for one project changes the results of another project, and you may not notice.
- Missing records. A global install holds dozens of packages from unrelated work. You cannot tell which ones your notebook really needs.
An isolated environment is a separate directory that holds its own copy of the interpreter link and its own installed packages. Each project gets one, so changes in one project cannot affect another.
Creating a virtual environment
The standard tool is venv, which ships with Python. Create the environment inside the project folder so the two travel together.
python -m venv .venv
source .venv/bin/activate
pip install pandas matplotlib
pip freeze > requirements.txt
# Later, on another machine:
python -m venv .venv
source .venv/bin/activate
pip install -r requirements.txtOn Windows, activate with .venv\Scripts\activate instead of the source line.
The first four commands create the environment, activate it, install packages, and record what is installed. The last three repeat the setup on another machine from the recorded file.
Activation changes your shell's PATH so that python and pip point at the copies inside .venv. Your prompt usually shows (.venv) while it is active. Closing the terminal ends the activation. The environment itself stays on disk.
Check which Python you are using
Most "it works in the terminal but not in the notebook" problems come from using the wrong interpreter. Verify it directly.
which python # macOS and Linux
python -c "import sys; print(sys.executable)"The printed path should end in .venv/bin/python (or .venv\Scripts\python.exe on Windows). If it shows a system path, the environment is not active.
Why name it `.venv` and keep it in the project
- Many editors and tools detect a folder named
.venvautomatically. - The leading dot hides it from most file listings.
- A per-project location makes it obvious which environment belongs to which project.
Do not commit .venv to Git. It contains absolute paths and platform-specific binaries, so it does not work when copied to another machine. Add it to .gitignore and commit the requirements file instead.
Connecting the environment to Jupyter
Installing Jupyter in one environment does not make its kernel use another. A kernel is the process that runs your notebook's code. Each kernel is tied to a specific Python interpreter. If you launch Jupyter from your global Python, the notebook runs against global packages even when a .venv exists.
There are two reliable approaches.
- Install Jupyter inside the project environment. Activate
.venv, runpip install jupyterlab, then startjupyter labfrom the same shell. The default kernel then uses.venv. - Register the environment as a named kernel. This is useful when one Jupyter installation serves several projects.
source .venv/bin/activate
pip install ipykernel
python -m ipykernel install --user --name my-analysis --display-name "Python (my-analysis)"After this, choose "Python (my-analysis)" from the kernel menu in the notebook. Registered kernels are stored per user, not in the project, so each collaborator must run this step once on their own machine.
You can list registered kernels and remove stale ones.
jupyter kernelspec list
jupyter kernelspec remove my-analysisConfirm the notebook uses the right environment
Put a check at the top of the notebook. It prints the interpreter path and the version of a key package.
import sys
from importlib.metadata import version
print("Interpreter:", sys.executable)
print("pandas:", version("pandas"))If the interpreter path does not point into your project's .venv, the kernel is wrong. Switch kernels and restart.
Conda environments
If your team uses conda, the same idea applies with different commands. Conda environments can also manage non-Python libraries and the Python version itself.
conda create --name my-analysis python=3.12
conda activate my-analysis
conda install pandas matplotlib
conda env export --from-history > environment.ymlThe --from-history flag lists only the packages you asked for, not every dependency. That keeps the file portable across operating systems.
| Aspect | `venv` + pip | conda |
|---|---|---|
| Ships with Python | Yes | No, install separately |
| Chooses the Python version | No, uses the interpreter that created it | Yes, per environment |
| Manages non-Python libraries | No | Yes |
| Recorded file | `requirements.txt` | `environment.yml` |
| Typical location | Inside the project folder | A central conda directory |
Pick one tool per project. Mixing pip and conda install in the same environment can leave it in an inconsistent state, because each tool tracks packages separately. If you must use both, install conda packages first and pip packages last.
The Python version is part of the environment
A virtual environment reuses whichever Python created it. It does not provide a different Python version. If you create .venv with Python 3.9, the project is stuck with 3.9 until you rebuild it.
Record the version you used. A simple option is a .python-version file or a line in the README. Tools such as pyenv or uv can install and select specific versions.
python --version
python -m venv .venv --clearThe --clear flag empties an existing environment before recreating it. Use it when you want a clean start without deleting the folder by hand.
Common errors
ModuleNotFoundErrorin the notebook but the package imports in the terminal. The kernel and the terminal use different interpreters. Comparesys.executablein both.- The environment is not listed in the kernel menu. Run the
ipykernel installcommand from inside the active environment, then reload the page. pipinstalls somewhere unexpected. Call it aspython -m pip install .... This guarantees that pip belongs to the same interpreter aspython.- Activation seems to do nothing. On Windows PowerShell, scripts may be blocked by the execution policy. Use
.venv\Scripts\Activate.ps1after allowing scripts for your user, or use Command Prompt. - Package installed after the notebook started is not found. Restart the kernel. Python caches imports, so a running kernel can miss newly installed packages.
A short checklist
- Create one environment per project, inside the project folder.
- Add
.venv/to.gitignore. - Use
python -m pipfor installs. - Make sure the Jupyter kernel points to that environment.
- Print the interpreter path and key versions in the notebook.
- Record the Python version alongside the requirements file.
Exercise
A colleague clones your repository, runs pip install -r requirements.txt in a fresh .venv, and opens the notebook in JupyterLab started from their system Python. The import import pandas fails even though pandas is installed in .venv. What is the cause, and what are two ways to fix it?
Show answer
The notebook's kernel uses the system Python, not the interpreter in .venv, so it cannot see the packages installed there. Fix 1: activate .venv, run pip install jupyterlab, and start JupyterLab from that shell. Fix 2: with .venv active, install ipykernel, register the environment with python -m ipykernel install --user --name my-analysis, and select that kernel in the notebook. Printing sys.executable in a cell confirms which interpreter is running.
Exercise
Why should .venv be listed in .gitignore while requirements.txt is committed?
Show answer
The .venv folder contains absolute paths and platform-specific binaries, so it breaks when copied to another machine, and it is large. requirements.txt is a small text file that lets anyone rebuild an equivalent environment with pip install -r requirements.txt.