virtual environment

In Python, a virtual environment (or “venv”) is a directory containing all the files and executables needed to support a functional Python environment. It allows you to maintain project-specific dependencies isolated from the system-wide Python packages, which helps avoid conflicts between projects with different requirements.

By using virtual environments, you ensure that each of your Python projects has a dedicated and independent setup, which facilitates dependency management and helps you maintain your codebase.

Virtual environments are incredibly useful when working with multiple projects that require different versions of the same package or library. They also provide a convenient way to package and distribute your application without affecting the global Python environment on your system.

Example

You can create and activate a virtual environment using the venv module, which is included in the Python standard library. Here’s a quick example:

Windows PowerShell
PS> python -m venv venv\
PS> venv\Scripts\activate.bat
(venv) PS>

Here, you create a new virtual environment in a venv\ folder by using the venv module. Then, you activate the virtual environment by executing venv\Scripts\activate.bat. The new prompt, (venv) PS>, indicates that you successfully activated the virtual environment.

Shell
$ python -m venv venv/
$ source venv/bin/activate
(venv) $

Here, you create a new virtual environment in a venv/ folder by using the venv module. Then, you activate the virtual environment with the source command. The new prompt, (venv) $, indicates that you successfully activated the virtual environment.

Tutorial

Python Virtual Environments: A Primer

In this tutorial, you'll learn how to use a Python virtual environment to manage your Python projects. You'll also gain a deep understanding of the structure of virtual environments created with the venv module, as well as the rationale behind using virtual environments.

intermediate devops tools

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated Jan. 8, 2025 • Reviewed by Dan Bader