Virtual Environments (venv) and How to Create One

Aug. 19, 2024, 10:25 p.m.

As a Python developer, managing project dependencies and isolating environments is crucial for maintaining clean and manageable codebases. One of the most effective ways to achieve this is by using Python virtual environments. In this blog post, we’ll explore what a virtual environment (venv) is, why it’s important, and how to create and use one.

What is a Virtual Environment?

A virtual environment is a self-contained directory that contains a Python interpreter and a set of libraries specific to a project. It allows you to create isolated environments for each of your Python projects, ensuring that dependencies are managed separately and do not interfere with each other

Why Use Virtual Environments?

  • Dependency Management: Keep project dependencies isolated.
  • Environment Consistency: Ensure your project runs the same way on different machines.
  • Package Version Control: Manage different package versions for different projects.
  • System-Wide Package Pollution Avoidance: Prevent conflicts between global and project-specific packages.
How to Create a Virtual Environment with venv

Python’s standard library includes a module named venv specifically for creating virtual environments. Here’s a step-by-step guide on how to use it

Create a Virtual Environment

To create a virtual environment, navigate to your project directory in the terminal and use the venv module. The following command will create a virtual environment in a directory named venv:

python3 -m venv venv

python -m venv venv: Creates a new virtual environment in the venv directory.

You can name it anything you like, such as env, myenv, or project-env.

python3 -m venv project-env


Activate the Virtual Environment

  • Windows:
.\venv\Scripts\activate
  • macOS and Linux:
source venv/bin/activate

When activated, your terminal prompt will typically change to indicate that you’re working inside the virtual environment.

With the virtual environment activated, you can now install packages using pip. For example:

pip install requests

Deactivate the Virtual Environment

deactivate
Conclusion

Using virtual environments with venv is a best practice in Python development. They provide an isolated space for your project dependencies, ensuring that each project remains independent and manageable

Back