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.
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.
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.
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.
There are other options to isolate your project from others.
And that’s where virtual environments comes in!
If you liked this page, please share it with a fellow learner: