A virtual environment is a way to package up all of your Python bits and pieces into a single container.

But why?

Sometimes you have a project that needs Python 2.

Sometimes you need a project that needs Python 3.

Sometimes you need a Python 3 project that needs BeautifulSoup version three. But sometimes you need a Python 3 project that needs BeautifulSoup version FOUR.

How the hell do you keep all of that nonsense organized? Virtual environments! You give them each a name, and they act like completely different computers - one will only know about Python 2, one will only know about BeautifulSoup version 3, etc etc etc.

But how?

Some people create and use virtual environments on a per project basis, but if you’re working with data you wind up installing the same things again and again and again. 99% of the time, it probably actually doesn’t matter what version of pandas or requests you’re using!

If you keep a virtual enviroment for Python 2 and a virtual environment for Python 3 you’re probably doing fine.

Why would I make you install virtualenv and then be so flippant? Virtual environments are very important if you’re building programs or sites that are deployed on servers, or code that you’re going to be distributing to other people. In those cases the exact versions of all of your libraries become very very important.

But how, technically?

Okay, good question!

Creating a virtual environment

If you want to create a new virtual environment, you use mkvirtualenv.

If you want to create a virtual environment for data work, it’s super simple:

mkvirtualenv datawork

You can also specify the version of Python.

mkvirtualenv -p python2.7 marksclass

Using an existing virtual environment

If you’ve already created a virtual environment, you use workon to activate it. If I want to activate the datawork virtual environment from the previous example:

workon datawork

Leaving a virtual environment

To hop out of the virtual environment, you use deactivate.

deactivate

And tada! You’re out.

Installing packages in a virtual environment

Outside of a virtual environment, you usually have pip to install packages for Python 2 and pip3 to install packages for Python 3 (…but not always!).

When you’re inside of a virtual environment, you can always use pip. virtualenv will automatically pick the right version of pip for you.

Note: Installing a package in one virtual environment does not also install it in other virtual environments! If you’re creating a different environment for each project, you’re going to find yourself using pip install a lot.