3 min read
Python Virtual Environments

In this guide, we will look at different ways of creating virtual environments in Python. Virtual environments are used to manage dependencies and isolate projects from one another. This helps avoid conflicts between different versions of packages and ensures that each project has its own set of dependencies.

1. Using venv

The venv module is included in the Python standard library and is the most straightforward way to create a virtual environment. It is lightweight and easy to use. To create a virtual environment using venv, run the following command:

Open your terminal or command prompt and navigate to your project directory, then run:

# python -m venv <Name-of-the-virtual-environment>
python -m venv .venv 

Activate the virtual environment:

# For Windows
.venv\Scripts\activate
# For Linux
source .venv/bin/activate

Once activated, your terminal prompt will change to show the active environment (e.g., (.venv)), indicating that the virtual environment is active.

2. Using “virtualenv”

Virtualenv is an older tool that is still widely used and can create virtual environments for both Python 2 and Python 3. Unlike venv, virtualenv offers additional flexibility and compatibility with older versions of Python.

Before using it, you need to install virtualenv. Use pip to install:

pip install virtualenv

Steps to Create and Activate a Virtual Environment using virtualenv: Create a virtual environment: You can create a virtual environment similarly to venv:

virtualenv .venv 

Activate the virtual environment:

# For Windows:
.venv\Scripts\activate
# For Linux:
source .venv/bin/activate

3. Using “Conda”

Conda is another popular tool for creating virtual environments, especially in the data science community. Unlike venv and virtualenv, conda manages both Python packages and dependencies from other ecosystems, such as R, C++, and Fortran. conda environments are ideal for projects that require more than just Python libraries.

Installing conda: conda comes with the Anaconda or Miniconda distribution. If you haven’t already, you can download and install Miniconda, which provides a minimal setup to get started.

Steps to Create and Activate a Virtual Environment using conda:

  • Create a virtual environment:
  • Specify the version of Python you want:
conda create .venv python=3.8

Activate the virtual environment:

# for activation.
conda activate .venv 
# for deactivation.
conda deactivate