Virtual environments stop your Python projects from fighting over package versions. Learn what they are, how to create one, and how to share your setup with a teammate.
You install a package for one project and everything works. A week later you start a second project that needs a different version of the same package. You upgrade it, and the first project quietly breaks.
That is the exact problem virtual environments solve. Each project gets its own private set of packages, so nothing can clash.
By the end you will be able to:
- Explain what a virtual environment is in one sentence.
- Create, activate and leave one on macOS, Linux or Windows.
- Install packages with
pipand save them to arequirements.txtfile. - Recreate the same setup on another machine.
What goes wrong without one
When you run pip install requests without a virtual environment, the package goes into one shared place for your whole Python installation. Every project on the machine sees the same copy.
What a virtual environment is
A virtual environment is just a folder. Inside it are a copy of (or link to) the Python interpreter and an empty place for packages. When you “activate” it, your terminal is told to use that folder first, so python and pip now refer to the project’s own versions.
It is not a virtual machine or a container. It is lightweight, takes a second to create, and you can delete it any time without touching your real Python.
Create, activate, install
These steps use venv, which ships with Python, so there is nothing extra to install. Run them from your project folder.
- Create the environment. The name
.venvis a common convention. - Activate it. Your prompt will change to show
(.venv). - Install what you need with
pip. - Run your code as normal.
- When you are done, type
deactivate.
python3 -m venv .venv
source .venv/bin/activate
pip install requests
python app.py
deactivatepy -m venv .venv
.venv\Scripts\Activate.ps1
pip install requests
python app.py
deactivateHandy pip commands
| Command | What it does |
|---|---|
pip install package | Installs the latest version |
pip install package==1.2.3 | Installs one exact version |
pip install --upgrade package | Updates to the newest version |
pip uninstall package | Removes it |
pip list | Shows what is installed in this environment |
pip show package | Shows version and where it lives |
Common problems
- “pip installs into the wrong place”. You probably forgot to activate. Check
which pip. - “ModuleNotFoundError” after installing. The package went into a different environment than the one running your code. Use
python -m pip install ...so they always match. - Your editor cannot find the package. Tell it to use the interpreter inside
.venv. In most editors this is a “Select interpreter” option. - Moved or renamed the project folder. Environments store absolute paths, so delete
.venvand recreate it.