KAHIBARO
Discord Login Register

5.3. Virtual Environments

Why Virtual Environments Matter

When you build Python backend applications, you almost never work with "plain Python" only. You install many external packages: FastAPI, SQLAlchemy, pytest, etc.

If you install everything globally on your system, you quickly get into trouble:

A virtual environment is an isolated Python environment for one project.
Each project gets its own Python, its own pip, and its own installed packages.

A virtual environment is an isolated directory that contains:

  • Its own Python interpreter
  • Its own pip command
  • Its own copy of installed packages
    It does not change, replace, or "break" your system Python.

Using virtual environments is considered a must for modern Python development, especially for backend work.


Key Concepts

Global Python vs Virtual Environment

You usually have one or more global Python installations:

Global Python lives in system locations, for example:

A virtual environment is simply a directory inside your project, for example:

This directory contains:

Why Isolation Is Important

Isolation solves several common problems:


ProblemWithout venvWith venv
Different project dependenciesConflicting versionsEach project has its own versions
Upgrading a packageMight break other projectsAffects only that project
Reproducing environment elsewhereHard to remember everythingUse requirements.txt with that venv
Cleaning up unused packagesRisky to remove globallyJust remove the project or its venv

Creating Virtual Environments

Python includes a built-in module for this: venv.
There are other tools, but venv is standard and enough for now.

Basic Creation Command

From your terminal or command prompt, go to your project directory:

bash
cd /path/to/your/project

Then run:

bash
python -m venv venv

This:

You can use another name instead of venv, for example .venv:

bash
python -m venv .venv

Both are common. .venv is popular because the leading dot often hides it from file explorers, and many tools detect it automatically.

What Gets Created

On Linux / macOS (with python -m venv venv):

text
myproject/
  venv/
    bin/
      python
      pip
      activate
    lib/
      python3.x/
        site-packages/
    pyvenv.cfg
  your_code.py

On Windows:

text
myproject/
  venv/
    Scripts/
      python.exe
      pip.exe
      activate.bat
    Lib/
      site-packages/
    pyvenv.cfg
  your_code.py

You never need to touch most of these files manually.
You mostly care about:

Activating and Deactivating

You can work with a virtual environment with or without activation, but activation makes things much more convenient.

Activating on Linux / macOS

From your project directory:

bash
source venv/bin/activate

or if you used .venv:

bash
source .venv/bin/activate

After activation, your prompt usually changes, for example:

bash
(venv) user@machine:~/myproject$

Now when you type:

bash
python

or:

bash
pip

you are using the versions inside the virtual environment, not the global ones.

Activating on Windows (Command Prompt)

From your project directory:

bat
venv\Scripts\activate

or if you used .venv:

bat
.venv\Scripts\activate

You should see:

text
(venv) C:\path\to\myproject>

Now python and pip will point to the virtual environment.

Activating on Windows (PowerShell)

From your project directory:

powershell
.\venv\Scripts\Activate.ps1

or:

powershell
.\.venv\Scripts\Activate.ps1

If you get an execution policy error, you may need to allow running local scripts, for example:

powershell
Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy RemoteSigned

Then try activating again.

Deactivating

To leave the virtual environment on any platform:

bash
deactivate

Your prompt will return to normal, and python / pip will again be the global ones.

Rule
Always check your prompt for (venv) or (.venv) before:

  • Installing packages with pip install
  • Running your Python application
  • Running tests
    If you forget to activate, you may install packages globally by mistake.

Using `pip` Inside a Virtual Environment

Once the virtual environment is activated, the pip command uses the venv by default.

Example on any platform:

bash
(venv) pip install fastapi uvicorn

This will install fastapi and uvicorn only inside venv.

You can check where pip is installing packages:

bash
(venv) which pip       # Linux / macOS
(venv) where pip       # Windows

You can also check installed packages:

bash
(venv) pip list

Installing Specific Versions

To control versions clearly:

bash
(venv) pip install fastapi==0.111.0
(venv) pip install "uvicorn[standard]==0.27.0.post1"

This version pinning is critical when building backend APIs that must behave the same in development and production.


Checking Which Python You Are Using

It is useful to verify that you are using the venv Python:

On Linux / macOS:

bash
(venv) which python

Output will be something like:

text
/home/user/myproject/venv/bin/python

On Windows:

bash
(venv) where python

Output will be something like:

text
C:\path\to\myproject\venv\Scripts\python.exe

If it points to a system path like /usr/bin/python3 or C:\Python311\python.exe while you expect the venv, you are either not activated or something is misconfigured.


Virtual Environments and Project Structure

A common and practical structure for backend projects is:

text
myproject/
  .venv/           # or venv/
  app/
    __init__.py
    main.py
    ...
  tests/
  requirements.txt
  README.md

Why keep `venv` inside the project?

Pros:

Cons:

Ignore Virtual Environment in Git

Create a .gitignore file in your project and add:

text
venv/
.venv/

So Git does not track the virtual environment.
You never commit the venv to your repository.


Recreating Environments with `requirements.txt`

To share dependencies between machines, you do not share the venv itself.
You share a list of packages instead.

Common pattern:

  1. Install packages inside your venv:
bash
   (venv) pip install fastapi uvicorn
   (venv) pip install sqlalchemy psycopg2-binary
  1. Freeze current dependencies to a file:
bash
   (venv) pip freeze > requirements.txt

Now requirements.txt might contain:

text
   fastapi==0.111.0
   uvicorn==0.27.0.post1
   SQLAlchemy==2.0.30
   psycopg2-binary==2.9.9
  1. On another machine (or after deleting the venv), you can recreate it:
bash
   python -m venv venv
   source venv/bin/activate      # or venv\Scripts\activate on Windows
   pip install -r requirements.txt
bash
   pip install -r requirements.txt

Rule
To reproduce a Python environment:

  1. Create a new virtual environment.
  2. Activate it.
  3. Install packages using:

Common Mistakes and How to Avoid Them

1. Installing Packages Globally by Accident

Symptom:

Cause: You installed the package without activating the venv.

How to fix:

  1. Activate the virtual environment.
  2. Run pip install again.

2. Running the Wrong Python

Symptom:

Cause: Virtual environment not activated, or you are in another shell.

Fix:

  1. Activate the virtual environment in that terminal.
  2. Always run python from an activated venv, or call it explicitly:
bash
   venv/bin/python app/main.py           # Linux / macOS
   venv\Scripts\python.exe app\main.py   # Windows

3. Committing the venv Folder to Git

Symptom:

Cause: venv/ or .venv/ not in .gitignore.

Fix:

  1. Add venv/ and .venv/ to .gitignore.
  2. Remove them from Git history if already committed.

Examples: Step by Step on Each Platform

Example on Linux / macOS

bash
# 1. Create project folder
mkdir backend-example
cd backend-example
# 2. Create virtual environment
python -m venv .venv
# 3. Activate it
source .venv/bin/activate
# 4. Check Python and pip
which python
which pip
# 5. Install dependencies
pip install fastapi uvicorn
# 6. Save dependencies
pip freeze > requirements.txt
# 7. Run Python using this environment
python -c "import fastapi; print(fastapi.__version__)"
# 8. When done
deactivate

Example on Windows (Command Prompt)

bat
REM 1. Create project folder
mkdir backend-example
cd backend-example
REM 2. Create virtual environment
python -m venv venv
REM 3. Activate it
venv\Scripts\activate
REM 4. Check Python and pip
where python
where pip
REM 5. Install dependencies
pip install fastapi uvicorn
REM 6. Save dependencies
pip freeze > requirements.txt
REM 7. Run Python using this environment
python -c "import fastapi; print(fastapi.__version__)"
REM 8. When done
deactivate

Virtual Environments in Editors and IDEs

Modern editors and IDEs can detect and use your virtual environment automatically.

VS Code

Typical steps:

  1. Create a venv, for example .venv.
  2. Open the project folder in VS Code.
  3. In the bottom status bar, click on the Python version.
  4. Choose the interpreter inside .venv, for example:
    • .venv/bin/python on Linux / macOS
    • .venv\Scripts\python.exe on Windows

VS Code will then:

PyCharm

When creating or importing a project, PyCharm can:

You usually set this in "Project Interpreter" settings.


When to Create a New Virtual Environment

A good rule:

Create a new virtual environment for every new Python project.

You typically create a venv when:

You usually do not create a new venv:

Summary

In this chapter you learned:

You will use virtual environments in almost every Python backend chapter that follows, including FastAPI, databases, testing, and deployment, so practice these steps until they feel natural.

Views: 9

Comments

Please login to add a comment.

Don't have an account? Register now!