Overview

A Python environment is a collection of Python packages installed in
specific directories.

Different projects often require different package versions. Installing
everything globally creates conflicts.

Virtual environments solve this by isolating dependencies per
project.

Each environment contains: - Its own Python interpreter - Its own
installed packages - Independent dependency versions

This isolation allows multiple Python projects to coexist on the same
system.

For deeper background, see the Real Python guide on virtual
environments.


Setup

Requirements:

  • Python installed
  • pip installed

Install virtualenv globally:

pip install virtualenv

Install it outside any existing virtual environment.


Creating a Virtual Environment

Navigate to the directory where you want the environment created.

python3 -m venv <env_name>

Python 2

virtualenv <env_name>

Replace <env_name> with the environment name.
Developers commonly use the project name.

Example:

python3 -m venv myproject

Where to Store Virtual Environments

Two common approaches exist.

1. Inside the Project Directory

Create the environment inside the project repository.

Example:

project/
│
├─ myvenv/
├─ src/
└─ README.md

Ensure the environment directory is ignored by Git.

.gitignore:

myvenv/

Store environments in a centralized location such as the home directory.

Example:

~/venvs/
   ├─ project1
   ├─ project2
   └─ project3

Advantages:

  • Cleaner project repositories
  • All environments stored in one location
  • Easier environment management

Activating an Environment

Activate the environment before installing packages.

source ./<env_name>/bin/activate

Example:

source ./myproject/bin/activate

After activation:

  • The shell prompt shows the environment name:
<!-- -->
(myproject) $
  • pip install installs packages only inside this environment.

Deactivating the Environment

Return to the global Python environment:

deactivate

Key Commands Summary

Create environment:

python3 -m venv <env_name>

Activate environment:

source ./<env_name>/bin/activate

Install packages:

pip install <package>

Deactivate environment:

deactivate