Independent programming publicationLearn · Build · Understand
Python · PRACTICAL GUIDE

Python Virtual Environments: Why and How to Use Them

Understand isolated Python environments, package management, activation commands, and reproducible project setup.

Python Virtual Environments: Why and How to Use Them
In brief: Understand isolated Python environments, package management, activation commands, and reproducible project setup. This guide explains the key ideas, common uses, and practical considerations.

The core idea

A Python virtual environment is an isolated directory containing an interpreter reference and package installation location for a project. It helps one project use a different dependency version from another.

How it works

Create an environment from the project directory with python -m venv .venv. On Windows, activate it with .venv\Scripts\activate. On macOS or Linux, use source .venv/bin/activate.

Practical considerations

Once activated, install packages with python -m pip install package-name. Using python -m pip helps ensure pip belongs to the interpreter currently selected in the environment.

A useful way to apply it

Capture installed dependencies with python -m pip freeze > requirements.txt. Another developer can install the listed packages with python -m pip install -r requirements.txt.

Keep learning

Do not commit the .venv directory to source control. Add it to .gitignore, and keep the dependency file and setup instructions in the repository.

Frequently asked questions

Do virtual environments come with Python?

The venv module is included with standard Python installations, although some Linux distributions package it separately.

Can I use one virtual environment for multiple projects?

You can, but separate environments are usually easier to maintain because projects may require different package versions.

How do I leave an environment?

Run deactivate in the terminal where the environment is active.

Continue learning

Explore more topics in the MicroProgrammer library, or browse the Python collection for related guides.