0%

76- Virtual Environments (venv)

Isolate project dependencies. Avoid version conflicts. Create reproducible environments. Essential for professional Python development.

You have installed packages with pip. They go into your global Python installation. This works when you have one project. But what about multiple projects? One project needs requests version 2.28. Another needs version 2.30. A third needs an old version of a library that is no longer compatible.
Global packages cannot satisfy conflicting requirements. Virtual environments solve this problem.
A virtual environment is an isolated Python installation for a single project. It has its own site-packages directory. Packages installed in one environment do not affect others. You can have different versions of the same package in different environments.
This lesson covers creating and managing virtual environments with venv (built into Python 3.3+). You will learn to create environments, activate them, install packages, freeze requirements, and replicate environments on other machines.

🕯️ Magic Note

Virtual environments do not create full Python copies. They use symlinks or copies of the Python binary and create a separate site-packages directory. This makes them lightweight while providing full isolation.

Why Virtual Environments?
The problems virtual environments solve and the benefits they provide.
  • Isolate dependencies per project
  • Avoid version conflicts between projects
  • Test upgrades without breaking existing code
  • Reproduce environments on different machines
  • List project dependencies in requirements.txt
  • Avoid permission issues (no sudo needed)
Creating a Virtual Environment
Use python -m venv to create a new virtual environment.

Bash

# Create a virtual environment named “venv” (common name)

python -m venv venv

# Create with a different name

python -m venv my_project_env

# Specify Python version (if multiple installed)

python3.11 -m venv venv

💡 The name venv is a convention. Many tools and editors automatically recognize it. Use .venv (with a dot) to hide the directory on Unix-like systems.
Activating a Virtual Environment
Activation adds the environment’s bin directory to your PATH.

Bash (Linux / macOS)

# Activate

source venv/bin/activate

# Deactivate

deactivate

Command Prompt (Windows)

# Activate

venv\Scripts\activate

# Deactivate

deactivate

PowerShell (Windows)

# Activate

.\venv\Scripts\Activate.ps1

# Deactivate

deactivate

🕯️ Magic Note

When activated, your command prompt usually shows the environment name in parentheses, like (venv) user@host:~/project$. This indicates the environment is active.

Installing Packages in a Virtual Environment
With the environment activated, use pip as usual. Packages install into the environment, not globally.

Bash

# Activate environment first

source venv/bin/activate

# Install packages (installs into venv)

pip install requests

pip install flask==2.3.0

pip install “numpy>=1.20”

# See what’s installed

pip list

Requirements Files: Freezing Dependencies
Create a requirements.txt file to list all packages and versions.

Bash

# After installing packages, freeze the environment

pip freeze > requirements.txt

# View the requirements file

cat requirements.txt

# requests==2.31.0

# flask==2.3.0

# …

🕯️ Magic Note

The requirements.txt file locks exact versions, ensuring everyone gets the same dependencies. This is critical for reproducibility.

Installing from requirements.txt
Recreate an environment from a requirements.txt file.

Bash

# Create new environment

python -m venv venv

# Activate it

source venv/bin/activate

# Install from requirements file

pip install -r requirements.txt

Managing Different Environments
Best practices for organizing multiple projects with virtual environments.

Directory Structure Example

projects/

├── web_app/

│ ├── venv/ # Virtual environment for web app

│ ├── requirements.txt # Dependencies for web app

│ └── app.py

├── data_science/

│ ├── venv/ # Separate environment

│ ├── requirements.txt # numpy, pandas, etc.

│ └── analysis.ipynb

└── legacy_project/

├── venv/ # Old dependencies

├── requirements.txt # requests==2.25.0, etc.

└── main.py

Ignoring Virtual Environments in Git
Never commit virtual environments to version control.

.gitignore

# Virtual environments

venv/

.venv/

env/

.env/

ENV/

# Python cache

__pycache__/

*.pyc

# But DO commit requirements.txt

# requirements.txt

💡 Always commit requirements.txt but ignore the virtual environment directory itself. Anyone cloning the repository can create their own environment from the requirements file.
Deleting a Virtual Environment
Simply delete the virtual environment directory.

Bash

# Make sure it’s deactivated first

deactivate

# Delete the directory

rm -rf venv

Command Prompt (Windows)

# Deactivate first, then delete

rmdir /s venv

Using venv with IDEs
Most IDEs automatically detect virtual environments.
  • VS Code: Ctrl+Shift+P → “Python: Select Interpreter” → Choose your venv
  • PyCharm: Automatically detects venv when you open a project
  • Jupyter: ipython kernel install –user –name=myenv
Alternatives to venv
Other tools offer additional features.
ToolDescriptionWhen to Use
venvBuilt-in, simpleMost projects (default choice)
virtualenvOlder, more featuresPython 2 compatibility (rare)
pipenvPipfile + Pipfile.lockWhen you need deterministic builds
poetryDependency management + packagingProfessional libraries, complex dependencies
condaCross-language environmentsData science, scientific computing
Practical Example: Setting Up a New Project
Step-by-step workflow for a new Python project.

Bash

# 1. Create project directory

mkdir my_project

cd my_project

# 2. Create virtual environment

python -m venv venv

# 3. Activate it

source venv/bin/activate # On Windows: venv\Scripts\activate

# 4. Upgrade pip (optional but recommended)

pip install –upgrade pip

# 5. Install packages as needed

pip install requests

pip install flask

# 6. Freeze requirements when ready to share

pip freeze > requirements.txt

# 7. Write your code…

# 8. Deactivate when done

deactivate

Common venv Mistakes
  • Forgetting to activate the environment (packages install globally)
  • Committing the venv directory to Git
  • Using different Python versions across team without specifying
  • Not creating requirements.txt (others cannot reproduce)
  • Running pip freeze without activating the environment (freezes wrong packages)
Check Your Understanding
  • How do you create a virtual environment named “myenv”?
  • What command activates a virtual environment on Linux/macOS? On Windows?
  • Why should you not commit the virtual environment to Git?
  • How do you create a requirements.txt file from an active environment?
  • How do you install packages from a requirements.txt file?
  • What is the difference between venv and virtualenv?

⚡ Whisper

A virtual environment is your project’s private Python world. It has its own packages. Its own versions. Its own rules. Global Python stays untouched. Other projects stay untouched. Conflicts vanish. Reproducibility arrives. venv is built into Python. Use it for every project. Activate it. Install packages. Freeze requirements. Share with teammates. Deactivate when done. This is not optional. It is professional practice. A project without a virtual environment is a project waiting for a conflict. A requirements.txt file is documentation of what your code needs. Commit it. Share it. Recreate it. Your future self will thank you. Your teammates will thank you. The Python ecosystem is vast. Virtual environments make it manageable.

Related posts