Skip to content

Setting up Virtual Environment

A virtual environment (venv) isolates project dependencies.

This prevents situations like:

  • Project A needs Flask 2.x
  • Project B needs Flask 3.x
  • both break if you install packages globally

Pick a project folder (example: my-flask-app/), then create a venv:

bash
python3 -m venv .venv

Activate it:

  • Linux/macOS:
bash
source .venv/bin/activate

You’ll usually see your shell prompt change.

bash
python -m pip install --upgrade pip

When the venv is activated, pip install ... installs inside that environment.

bash
pip freeze > requirements.txt

Later, someone can reproduce your env:

bash
pip install -r requirements.txt
  • You forgot to activate the venvpip installs globally.
  • You activated a different venv in another terminal.
  • Your editor uses a different interpreter than the terminal.

If you’re using VS Code, select the Python interpreter pointing to .venv.

What a virtual environment actually changes

Section titled “What a virtual environment actually changes”

A virtual environment is not a sandbox and not a container. It is a directory plus one redirected value: sys.prefix. Everything else follows from that.

diagram Diagram mermaid
am_i_in_a_venv.py
import sys
 
sys.prefix        # ...\scratch\flaskenv          <- the venv
sys.base_prefix   # ...\Python\pythoncore-3.14-64 <- the real install
sys.prefix != sys.base_prefix     # True  -> you are in a venv

That comparison is the reliable test. Checking the VIRTUAL_ENV environment variable is not reliable: it is set by the activate script, so running venv/Scripts/python.exe directly puts you in the venv with VIRTUAL_ENV unset — measured exactly that way here.

sketch Where does import look? p5.js
A virtual environment changes sys.prefix, and every import and pip install follows from that single value.
pch.quizTag pch.quizDefaultTitle
  1. What is the reliable way to tell, from inside Python, whether you are in a virtual environment?

    pch.quizShowAnswer

    B — compare sys.prefix with sys.base_prefix; they differ inside a venv — VIRTUAL_ENV is set by the activate script only. Running venv/Scripts/python.exe directly puts you in the venv with that variable unset — measured exactly that way. sys.prefix != sys.base_prefix is the real test.

  2. What does the activate script actually do?

    pch.quizShowAnswer

    B — it edits PATH and the shell prompt, so that 'python' resolves to the venv binary — Activation is convenience only. Isolation comes from which interpreter runs, which is why venv/bin/python -m pip install works with no activation and CI scripts rarely activate.

pch.coffeeTagline

pch.coffeeCta

pch.feedbackHeading

pch.feedbackSubheading