Chapter 4, Environment
pip and venv: isolated dependencies per project
Every project should have its own virtual environment. It is the cheapest rule to follow and the one that avoids problems the most.
Code for this chapter: ambiente/cap04_pip_venv.py
Why a virtual environment
If you install everything in the same Python, two projects that need different versions of the same library will clash. A virtual environment is a folder with its own interpreter and a set of packages. Installing there does not affect anything outside of it.
Create and activate
Create the environment inside the project folder, with the name .venv, which is the convention that tools and editors recognize on their own:
python3 -m venv .venv
source .venv/bin/activate
python --version
To exit the environment, run deactivate.
Windows and the PowerShell execution policy
If PowerShell refuses the activation script, allow locally signed scripts, just for your user:
Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy RemoteSigned. Close and reopen the terminal afterwards.
How to know if you are inside a venv
The terminal prompt gains the prefix (.venv). Inside Python, you can check by comparing two paths:
import sys
dentro_de_venv = sys.prefix != sys.base_prefix
print("Dentro de um venv:", dentro_de_venv)
Dentro de um venv: True
Inside the virtual environment, the output is True. Outside of it, it prints False.
The pip
Pip installs packages from PyPI. I always use python -m pip instead of pip plain, because this way pip is necessarily the one from the active interpreter:
python -m pip install requests
python -m pip install "requests>=2.32,<3"
python -m pip list
python -m pip show requests
python -m pip uninstall requests
To register the dependencies and reinstall them on another machine:
python -m pip freeze > requirements.txt
python -m pip install -r requirements.txt
Version specifiers
| Specifier | Meaning |
|---|---|
==2.32.3 | Exactly this version |
>=2.32 | This version or any newer |
>=2.32,<3 | Any 2.x from 2.32 onwards |
~=2.32 | Compatible: >=2.32 and <3 |
!=2.33.0 | Any, except this one |
The problem with pip freeze
The
pip freezelists everything that is installed, direct and indirect dependencies mixed, without distinguishing what you requested from what came along. For true reproducibility, I prefer a lockfile generated by Poetry or uv, which you will see in the next chapters.
The folder .venv will never go to Git. Put .venv/ in the .gitignore. Whoever clones the project recreates the environment from the dependency list.