Q&A library Python

What is a Python virtual environment and why should I use one?

Python Beginner environmentspackagesvenv

Short answer

A virtual environment is an isolated set of packages for one project, so different projects can use different versions without clashing. Create one with the venv module and activate it before installing anything.

The short version

A virtual environment is a self-contained folder holding a Python interpreter and its own set of installed packages, separate from the system and from other projects. It lets each project pin the exact package versions it needs without those choices leaking into anything else. Create one with the built-in venv module, activate it, then install packages into it.

Creating and activating one

python -m venv .venv

This makes a .venv folder in your project. Activate it so that python and pip point inside it:

# macOS and Linux
source .venv/bin/activate

# Windows
.venv\Scripts\activate

Your prompt usually shows the environment name once it is active. Now anything you install goes into .venv, not the system Python.

Why isolation matters

Imagine one project needs an old version of a library and another needs the newest. Installed globally, they overwrite each other, and installing for one breaks the other. Separate environments give each project its own copy, so upgrading one never disturbs the other. Without this, a single pip install can silently break unrelated code on your machine.

Recording what you installed

Freeze the exact versions so a colleague, or your future self, can recreate the environment.

pip freeze > requirements.txt

And recreate it elsewhere with:

pip install -r requirements.txt

This is what makes a project reproducible: the environment is described in a file that travels with the code.

The mistake to avoid

Installing packages into the system Python with sudo pip install is a common trap. It mixes project dependencies into the interpreter your operating system relies on, and version clashes there are painful to untangle. Always work inside a virtual environment instead, and never install project packages globally.

Deactivating and cleaning up

Leave the environment with deactivate. To remove it entirely, just delete the .venv folder, since everything lives inside it. That disposability is a feature: if an environment gets into a mess, delete it and rebuild from requirements.txt.

A note on newer tools

Tools such as uv, poetry and pipenv build on the same idea with extra features like lock files and faster installs. They are worth exploring later, but plain venv plus pip is built in, needs nothing extra, and is the right thing to understand first.

Enjoying these?

Go from piecing together answers to real fluency.

Our courses take you from looking things up to doing the work with confidence, step by step on real data.

Browse the courses