Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
python3
communitycreator

What is a virtual environment in Python?

Omu inetimi

Based on the official documentation, a virtual environment is a Python environment in which the Python interpreter, libraries, and scripts installed are isolated from those installed in other virtual environments, and, by default, any libraries installed in a Python “system”, i.e., one that is installed as part of your operating system.

In this shot, I’ll explain what virtual environments are and why we use them. I’ll also show you a straightforward way to create a virtual environment.

What is a virtual environment?

A virtual environment can be seen as a completely new computer, inside your computer, that is free from any dependencies and made specifically to run Python code.

It can also be thought of as a sandbox or a container created to isolate specific Python dependencies installed into it so that they do not interfere with others that may also be installed on your machine, and vice versa.

Why do we use virtual environments?

At their core, virtual environments were created to provide an isolated Python environment where dependencies of a particular project can be installed.

Python has its own way of storing packages and modules, which isn’t a problem for system packagespackages that are part of the standard Python library, but is of concern when site-packages3rd party Python packages are referenced. This is because all versions of a 3rd party Python package reside in the same site packages directory by default. Hence, Python cannot differentiate between versions when referenced for a project, which is unacceptable in many cases.

A simple way to create a virtual environment

Here is a straightforward way to create a virtual environment.

We’ll be making use of virtualenvwrapper.

To get started, navigate to your terminal and run the following:

pip install virtualenvwrapper

This should download the required package.

Next, create or navigate your project’s folder and run the mkvirtualenv projectname command.

So, if I were to create a virtual environment with the name pythonproject, it would be:

mkvirtualenv pythonproject

Doing so immediately creates a virtual environment for your Python project!

To confirm that the environment has been activated, you’ll see the name of the virtual environment in brackets at the left-hand side of the terminal, as shown below.

RELATED TAGS

python
python3
communitycreator
RELATED COURSES

View all Courses

Keep Exploring