This is an archived version of the course. Please find the latest version of the course on the main webpage.

Chapter 2: Virtual Environments

Venv

face Josiah Wang Ivan Procaccini

Python’s solution for managing package installations is via Venv. The idea is that you create a self-contained environment for each project you have.

For example, you can have an environment called finalproject for your amazing individual project, webapp for your revolutionary web application development code, etc. Each environment will have its own package installations, so the installations do not interfere with one another.

Virtual environment contains separate package installations for distinct projects

In practice, if you have a git repository containing the code for your project, then you might want to have an environment solely for running code in this repo. Most people just name the environment env or venv.

Of course, your main Python installation can still have the main packages that you use frequently, especially if the package versions are not critical for your general use. Having a virtual environment can save you from installing packages on the main Python installation, especially if the package is only used for one specific project.

Creating your virtual environment

Let’s say you need to create a virtual environment for your project. Say you want to name it my_env. Go to your project directory, and do the following (use python3 or python3.10 as appropriate):

user@MACHINE:~/ai_project$ python3 -m venv my_env

You should now see a directory called my_env in your project directory. This is where Python will install the packages for your environment.

If you are using git, you should exclude this virtual environment directory from your repo using .gitignore. There is no point committing all these files or worse pushing them to a remote repo (you should not usually push executables to git repos). It is easier to just recreate the virtual environment locally (we will discuss that shortly)!