Virtual Environments (venv)
What is a virtual environment
Let's say we have 2 Projects that use different versions of FastAPI
Let's say Project 2 uses a newer version of FastAPI than Project 1 and there are breaking changes between the 2 versions
You have a problem now where you need 2 different versions of the FastAPI framework and you are not able to upgrade

This is where VENVs come into play
This is an isolated environment that will not be affected by any other changes
It is completely isolated to this project

Creating a Virtual Environment
Navigate to the folder where you want to create the VENV
Use the following command to set up the VENV
# For Windows:
py -3 -m venv <venv_name>
# Example:
py -3 -m venv venv
# For Unix/Linux:
python3 -m venv <name>
# Example:
python3 -m venv venv
Setting up VENV
Now that you have created the VENV you will need to select the interpreter located in:
/path/to/project/venv_name/Scripts/python.exe
In our case we will be using VSCode
Go to View --> Command Palette

Go to Select interpreter

Enter the path to the interpreter
# For Windows:
/path/to/project/venv_name/Scripts/python.exe
# For Unix/Linux:
/path/to/project/venv_name/bin/python
# or
/path/to/project/venv_name/bin/python3
Set up VENV to be used in Terminal
Go to the project folder
Enter the following line:
# For Windows CMD:
venv/Scripts/activate.bat
# For Windows Powershell:
venv/Scripts/Activate.ps1
# For Linux
source venv/bin/activate
# Note that you need to run this command every time
# you open the terminal
This will not work if you are using Git Bash for Windows
Set up requirements.txt
Once you have installed everything that you need to get started within your VENV use the following command
pip freeze > requirements.txt
If you are on another machine and require the installation of all dependencies use:
pip install -r requirements.txt
Last updated