Sub topic 2
Create a virtual environment for the project
This chapter creates the isolated Python environment that the rest of the tutorial builds on. It assumes you have Python 3.9 or newer installed, can run commands in a terminal, and know that pip installs Python packages. You do not need to know how venv works internally.
What a virtual environment contains
A virtual environment is a directory holding a small Python setup of its own. It has three parts:
- A link to, or copy of, the Python interpreter that created it.
- An empty
site-packagesdirectory where packages you install for this project will go. - A
pyvenv.cfgfile that records which base interpreter it came from.
It does not copy the standard library. The environment borrows that from the base interpreter. This is why creating one takes a second or two and uses little disk space.
When you run python from inside the environment, the interpreter reads pyvenv.cfg, notices it lives in an environment, and puts the environment's site-packages on its import path. Packages installed globally are not visible unless you ask for them explicitly.
Create the environment
Run this from your project's root directory:
python -m venv .venvThe command has three parts:
python -m venvruns the standard-libraryvenvmodule as a script..venvis the directory to create.- The leading dot hides the directory in most file listings. Many editors and tools also look for
.venvby name.
The environment uses whichever interpreter ran the command. To pin a specific Python version, call that interpreter directly:
python3.12 -m venv .venvOn Windows, the py launcher selects a version for you:
py -3.12 -m venv .venvOn some Linux and macOS systems, python is missing or points to Python 2. Use python3 in the first command instead. After activation, python always works.
What gets created
| Path (Linux/macOS) | Path (Windows) | Purpose |
|---|---|---|
| `.venv/bin/` | `.venv\Scripts\` | The interpreter link, `pip`, and activation scripts |
| `.venv/lib/python3.12/site-packages/` | `.venv\Lib\site-packages\` | Where installed packages go |
| `.venv/pyvenv.cfg` | `.venv\pyvenv.cfg` | Records the base interpreter and version |
| `.venv/include/` | `.venv\Include\` | Header files for building C extensions |
You rarely edit anything in here. Treat the directory as disposable output, not as source code.
Activate the environment
Creating the environment does not switch you into it. You do that by activating it:
source .venv/bin/activate # Windows: .venv\Scripts\activateThe right command depends on your shell:
| Shell | Activation command |
|---|---|
| bash, zsh | `source .venv/bin/activate` |
| fish | `source .venv/bin/activate.fish` |
| PowerShell | `.venv\Scripts\Activate.ps1` |
| Windows cmd | `.venv\Scripts\activate.bat` |
After activation, your prompt usually gains a (.venv) prefix. That prefix is only a visual hint, so verify the switch yourself, as shown below.
What activation does
Activation is less magical than it looks. It does two main things:
- It prepends the environment's
bin(orScripts) directory to your shell'sPATH. - It sets a
VIRTUAL_ENVvariable that tools can read.
Because that directory is now first on PATH, typing python or pip finds the environment's copy before any global one.
You can also skip activation and call the environment's interpreter by its full path, for example .venv/bin/python script.py. This is useful in scheduled jobs and scripts, where nothing activates the environment for you.
Verify that you are inside it
Run this short script after activating:
import sys
print("Interpreter:", sys.executable)
print("Environment prefix:", sys.prefix)
print("Inside a venv:", sys.prefix != sys.base_prefix)Run it with python. Inside an active environment, sys.executable points into your .venv directory and the last line prints True. If it prints False, you are still using the global interpreter.
A quicker shell check is which python on Linux and macOS, or where python on Windows. The first result should be inside .venv.
Upgrade pip
Python bundles a copy of pip when it creates an environment, and that copy can be older than the latest release. Upgrade it before installing anything:
python -m pip install --upgrade pipUse python -m pip rather than plain pip. The first form guarantees that pip belongs to the interpreter you are running. Plain pip could resolve to a different installation if your PATH is not what you expect. This is a common cause of "I installed it but cannot import it" errors.
Keep it out of version control
The .venv directory is machine-specific and can be hundreds of megabytes. Do not commit it. If the project is a Git repository, add this line to .gitignore:
.venv/Other people recreate the environment from a list of dependencies, not from your directory. The chapter on recording dependencies covers that list.
Where to put the environment
There are two common layouts, and the trade-offs matter.
| Layout | Advantage | Drawback |
|---|---|---|
| Project-local `.venv` | Editors detect it automatically. Deleting the project deletes the environment. | Each project stores its own copy of packages. |
| Central directory (for example `~/.venvs/project`) | Keeps project folders clean. | You must remember which environment goes with which project. |
This tutorial uses a project-local .venv. It is the simplest layout to explain to a teammate, and Jupyter-related tools find it easily.
Deactivate, delete, and recreate
To leave the environment, run:
deactivateThis restores your original PATH. The environment still exists on disk and you can activate it again later.
If an environment gets damaged, or you want to change Python versions, the safest fix is to delete it and build it again. Run the delete command only from your project root, since it removes the directory permanently:
rm -rf .venv # Windows PowerShell: Remove-Item -Recurse -Force .venv
python -m venv .venvThis works well because the environment holds no data of its own. As long as you record your dependencies, rebuilding costs a few minutes.
If you want a clean start with the same Python, python -m venv --clear .venv empties and rebuilds the directory in one step.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `ensurepip is not available` when creating | Debian or Ubuntu ships `venv` as a separate package | Install it, for example `sudo apt install python3-venv` |
| `python: command not found` | Only `python3` exists on your system | Use `python3 -m venv .venv` |
| PowerShell says running scripts is disabled | Execution policy blocks `Activate.ps1` | Run `Set-ExecutionPolicy -Scope CurrentUser RemoteSigned`, then activate again |
| Prompt shows `(.venv)` but `which python` points elsewhere | A shell alias or another tool altered `PATH` after activation | Open a new terminal, activate again, and check with `which python` |
| Packages install but cannot be imported | `pip` belongs to a different Python | Always use `python -m pip` |
| Activation works in one terminal but not a new one | Activation only affects the current shell session | Activate in each new terminal |
The last row catches many beginners. Each terminal window has its own PATH, so activation never carries over to a new window.
Summary of the workflow
For a new project, the sequence is always the same:
- Change into the project directory.
- Run
python -m venv .venv. - Activate with the command for your shell.
- Confirm with
which pythonor the verification script. - Run
python -m pip install --upgrade pip. - Add
.venv/to.gitignore.
The next chapter installs JupyterLab, pandas, and matplotlib into this environment.
Exercise
You activated your environment, then ran pip install pandas. Importing pandas in python still fails with ModuleNotFoundError. Name two checks you would run to find the cause, and the habit that prevents the problem.
Show answer
First, run which python (or where python on Windows) and the sys.executable check to see whether the interpreter is inside .venv. Second, run pip --version to see which Python the pip command belongs to. If they point to different installations, the package went into the wrong one. The preventive habit is to install with python -m pip install pandas, which ties pip to the interpreter you are running.
Exercise
A colleague zips your whole project folder, including .venv, and sends it to you on another computer. The environment fails to activate correctly. Why, and what should they have shared instead?
Show answer
The environment contains absolute paths and compiled files specific to the original machine and operating system, so it cannot be moved. They should have left .venv out and shared the project files plus a list of dependencies, such as a requirements.txt. You then create a fresh environment locally and install from that list.