Skip to main content

🐍 How Python venv Works

venv (short for virtual environment) is Python’s built-in tool for creating isolated environments.
It lets you install dependencies on a per-project basis without affecting your system Python or other projects.


βš™οΈ What It Actually Is​

A virtual environment is just a directory that contains:


.venv/
β”œβ”€β”€ bin/ # Executables (Python, pip, etc.)
β”‚ β”œβ”€β”€ activate # Shell script that sets environment vars
β”‚ └── python # Copy/symlink of the Python interpreter
β”œβ”€β”€ lib/ # Site-packages live here
β”‚ └── python3.x/
β”‚ └── site-packages/
└── pyvenv.cfg # Metadata (points to base Python install)

There is no background process or runtime service.
It’s purely a self-contained folder structure.


🧩 Lifecycle​

StepCommandDescription
Createpython3 -m venv .venvCreates a new environment folder with a copy of Python.
Activatesource .venv/bin/activateTemporarily adds .venv/bin to your PATH and sets VIRTUAL_ENV.
DeactivatedeactivateRestores your shell to normal.
Deleterm -rf .venvCompletely removes the environment and its packages.

Activation only modifies the current shell session.
The environment itself persists until you delete it.


πŸ“¦ Installing Packages​

Once activated, installing packages with pip goes into the local environment:

source .venv/bin/activate
pip install requests

The package will be installed in .venv/lib/python3.x/site-packages/, and will not affect your system Python or global pip environment.


πŸ” Quick Sanity Check​

which python
# β†’ /path/to/project/.venv/bin/python

python -m site
# Shows local site-packages path inside .venv

If both point inside .venv, you’re isolated correctly.


πŸ’‘ Pro Tips​

  • Add .venv/ to your .gitignore β€” it’s per-user, not per-repo.

  • If you use requirements.txt, recreate the venv anytime by running:

    python3 -m venv .venv
    source .venv/bin/activate
    pip install -r requirements.txt
  • Each project can have its own interpreter and dependency versions.


βœ… Summary: venv is not a process β€” it’s a directory-based isolation mechanism. It persists until you delete it and only changes your shell’s environment temporarily when activated.