Virtual Environments

Python virtual environments allow you to isolate your project from globally installed packages and Python versions. They allow you to define and install Python packages and a Python interpreter in an isolated location from the rest of your system, instead of installing them globally. This has a few advantages that we'll go over first.

Why you need virtual environments

Preventing version conflicts

If you install third-party packages system-wide, you could argue that you’re being very efficient. After all, you only need to install it once, saving you precious time and disk space. There’s a problem with this approach that may start to unfold weeks or months later, however.

Suppose your project, Project A, is written against a specific version of library X. In the future, you might need to upgrade library X. Say, for example, you need the latest version for another project you started, called Project B. You upgrade library X to the latest version, and project B starts working fine. Great! But once you did this, it turns out your Project A code breaked badly. After all, APIs can be completely different between major version upgrades.

A virtual environment fixes this problem, by isolating your project from other projects and system-wide packages.

Easy to reproduce and install

Virtual environments make it easy to define and install the packages specific to your project. Additionally, you can define exact version numbers for the required packages, to make sure your project will work with a version that has been tested with your code. This also helps other users of your software, since a virtual environment will help others to reproduce the exact environment for which your software was built.

Works everywhere, even when not root

If you’re working on a shared host, like those at a university or a web hosting provider, you won’t be able to install packages globally since you don’t have the administrator rights to do so. In these places, a virtual environment allows you to install anything you want locally.

Python Virtual Environments vs. other options

There are other options to isolate your project from others.

  1. In the most extreme case, you could buy a second PC and run your code there. Problem fixed! It’s a bit expensive though!
  2. A virtual machine is a much cheaper option but still requires you to install a complete operating system. A bit of a waste as well, right?
  3. Next in line is containerization, with the likes of Docker and Kubernetes. These can be very powerful, but for a small Python project still a bit too much and too complicated.

And that’s where virtual environments comes in!

If you liked this page, please share it with a fellow learner: