Skip to content

Module 14 · Python Modules and Packages — topic 11 of 13

Virtual environments

Isolated per-project Python environments with venv: why they exist, creating and activating them on Windows, macOS and Linux, installing packages into them, and checking which environment is active.

Beginner 10 min read·Lesson 219 of 306 in Python Programming

Learning objectives

  • Explain why virtual environments are used
  • Create, activate and deactivate a venv
  • Check whether code runs inside a virtual environment

Definition

A virtual environment is a folder containing its own Python executable link and its own site-packages. Packages installed while it is active go into that folder, isolating each project's dependencies from others and from the system Python.

Introduction

Project A needs Django 4, project B needs Django 5. Installed globally, one would break the other. Virtual environments give each project its own set of packages.

Why it matters

Virtual environments make projects reproducible and prevent version conflicts — they are standard practice for every Python project.

Detailed explanation

Create one with python -m venv .venv inside the project folder. .venv is the common name; it is not committed to version control.

Activate it: .venv\Scripts\activate on Windows (PowerShell: .venv\Scripts\Activate.ps1), source .venv/bin/activate on macOS and Linux. The prompt shows (.venv).

While active, python and pip refer to the environment's copies, so installs go into .venv.

deactivate returns to the system Python. You can also run the environment's interpreter directly without activating (.venv/bin/python).

Inside a venv, sys.prefix points to the environment while sys.base_prefix points to the base installation.

The pyvenv.cfg file records which Python created the environment and whether system packages are visible.

Environments are disposable: delete the folder and recreate it from requirements.txt whenever needed.

Syntax

Terminal
python -m venv .venv
# Windows
.venv\Scripts\activate
# macOS / Linux
source .venv/bin/activate
python -m pip install requests
deactivate
  • One environment per project.
  • Activate before installing.
  • Don't commit .venv.

Code examples

Creating and activating

Terminal
python -m venv .venv
source .venv/bin/activate # macOS / Linux
.venv\Scripts\activate # Windows
python -m pip install requests
deactivate

Am I in a virtual environment?

Python
import sys
in_venv = sys.prefix != sys.base_prefix
print("inside a virtual environment:", in_venv)
print("interpreter:", sys.executable)

The result depends on how you run it: True inside an activated environment, False with the system Python.

More examples

Creating an environment from Python

Python
import os
import venv
from pathlib import Path
venv.create("demo-env", with_pip=False)
cfg = Path("demo-env/pyvenv.cfg").read_text(encoding="utf-8")
settings = dict(line.split(" = ", 1) for line in cfg.splitlines() if " = " in line)
print(settings["include-system-site-packages"])
print((Path("demo-env") / ("Scripts" if os.name == "nt" else "bin")).is_dir())
Output
false
True

Step-by-step explanation

  • The venv module is what python -m venv uses behind the scenes.
  • pyvenv.cfg is a small text file of key = value settings; system packages are hidden by default.
  • Executables live in Scripts on Windows and bin elsewhere.

Expected output

Running “Creating an environment from Python” prints exactly:

TextOutput
false
True

Practical applications

  • Every professional Python project uses an isolated environment.
  • CI pipelines create a fresh environment for each test run.

Best practices

  • Create a .venv for each project.
  • Ignore it in version control.
  • Recreate it from requirements files.

Common mistakes

Installing before activating

Avoid

python -m venv .venv
pip install flask # installs globally

Prefer

python -m venv .venv
.venv\Scripts\activate
python -m pip install flask

Without activation, pip targets the system Python.

Committing the environment

Avoid

git add .venv

Prefer

Add .venv to .gitignore and commit requirements.txt.

Environments are large and machine-specific.

Important notes

  • Editors such as VS Code detect .venv automatically and use it for running and debugging.

Key takeaways

  • Virtual environments isolate project packages.
  • Create with python -m venv; activate before installing.
  • sys.prefix differs from sys.base_prefix inside one.

Try it yourself

  1. 1
    Create a virtual environment, install one package and list the packages inside it.
  2. 2
    Write a script that warns when it is not run inside a virtual environment.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • ModerateWhat is the main purpose of a virtual environment?
Practise this topic