Jason Bamford's blog

Python 3 Venv - Local and Central Virtual Environments

Since version 3.3, Python includes the module venv which allows you to create isloated environments, where you can install any packages, libraries etc. that your project may need, without cluttering or affecting other projects on your system - you can have as many separate environments as you like.

Since venv comes as part of Python it is available to use at all times without requiring installation.

Using Venv

First I will show you how to create a virtual environment in your project folder, as most tutorials do. But please then read on as other possibilities abound!

The following assumes you are working on MacOS or Linux using the bash shell.

Starting in the folder for your python project:

If you usually have to call Python with the command `python3`, while the virtual environment is active you are able to use just `python` instead.

You can also run your virtual version of Python without activating the virtual environment, by referencing the binary in the .venv directory directly, eg.

$ .venv/bin/python

Centralised Virtual Environments with Venv

Tutorials I have seen on venv only show you how to create a virtual environment in the project folder you are working on, but this does not need to be the case at all.

You can just as easily create a virtual environment in a centralised location and use it while working on multiple projects. For example, if you have several Django projects you're working on, you don't need to have a virtual environment in each separate project, all with the same version of Django installed; just create one environment in a convenient location.

You might for example choose to keep central virtual environments in a subfolder of your home directory such as ~/.venv/

Following the same instructions as above (and naming our environment django as an example):

So you can see, working with centralised virtual environments only requires a little more typing to prefix your central path (eg. ~/venv/), but otherwise works just the same.