Creating a Virtual Environment with Python3

ABHISHEK GUPTA
3 min readSep 11, 2020

What is a Virtual Environment?

A virtual environment is a tool that helps to keep dependencies required by different projects separate by creating isolated Python virtual environments for them

Why is it important?

Python “Virtual Environments” allow Python packages to be installed in an isolated location for a particular application, rather than being installed globally.

When do we need a Virtual Environment?

Imagine you have an application that needs version 1 of LibFoo, but another application requires version 2. How can you use both these applications? If you install everything into /usr/lib/python3.6/site-packages (or whatever your platform’s standard location is), it’s easy to end up in a situation where you unintentionally upgrade an application that shouldn’t be upgraded.

Or more generally, what if you want to install an application and leave it be? If an application works, any change in its libraries or the versions of those libraries can break the application.

Also, what if you can’t install packages into the global site-packages directory? For instance, on a shared host.

In all these cases, virtual environments can help you. They have their own installation directories and they don’t share libraries with other virtual environments.

How to Install Virtual Environment with Python3?

First of all, we are going to check where our ‘global’ environment currently lives through the terminal (zsh):

which pip3

which tells us that our python install lives in /usr/bin/pip3

Now, we need to create a directory:

mkdir my_python_project

Next, we change the directory to the newly created one:

cd my_python_project

Now, we are going to create a virtual environment inside a subdirectory of the current directory:

python3 -m venv ./venv

The venv module provides support for creating lightweight “virtual environments” with their own site directories, optionally isolated from system site directories. venvis available by default in Python 3.3 and later

Bonus:

In order to view all the different files of a folder in a structured format, you can use a package calledtree

Install: brew install tree

You can notice the changes by checking it (e.g. tree venv/)

How to use Virtual Environment?

After creating the virtual environment, to use it, we need to activate the virtual environment:

source venv/bin/activate

(here venv is the name of the subfolder)

Once the virtual environment is activated, the name of your virtual environment will appear on the left side of the terminal. This will let you know that the virtual environment is currently active.

Now you can install dependencies related to the project in this virtual environment.

Good Luck!

Reference:

  1. https://packaging.python.org/tutorials/installing-packages/#creating-virtual-environments
  2. https://realpython.com/lessons/creating-virtual-environment/

--

--