Virtual Environments¶
Python Virtual Environments are a way to have a directory with all the Python packages you need for a specific project.
It's normally just a directory with some files in it. When you install new Python packages in a specific way, they are downloaded and configured in that directory.
Having virtual environments for each project is very useful because this way you can have exactly the dependencies you need for that project, and you can even have different versions of the same package in different projects.
Now let's see how to create and use a virtual environment.
Make sure you have Python¶
Before creating a virtual environment, make sure you have an officially supported version of Python.
Currently it is Python 3.7 and above (Python 3.6 was already deprecated).
You can check which version you have with:
There's a chance that you have multiple Python versions installed.
You might want to try with the specific versions, for example with:
python3.10
python3.9
python3.8
python3.7
The commands would look like this:
If you have different versions and python
is not the latest, make sure you use the latest version you have available. For example python3.9
.
If you don't have a valid Python version installed, go and install that first.
Create a Project¶
The first step is to have a directory for your project. Go ahead and create a one.
What I normally do is that I create a directory named code
inside my home/user directory.
And inside of that I create one directory per project.
So, for example:
Create a Python Virtual Environment¶
When writing Python code, you should always use virtual environments in one way or another.
If you want to learn more about them, you can read the official tutorial for virtual environments, it's quite simple.
When you "activate" a virtual environment, any package that you install, for example with pip
, will be installed in that virtual environment.
Tip
There are other tools to manage virtual environments, like Poetry.
And there are alternatives that are particularly useful for deployment like Docker and other types of containers. In this case, the "virtual environment" is not just the Python standard files and the installed packages, but the whole system.
Go ahead and create a Python virtual environment for this project. And make sure to also upgrade pip
.
Here are the commands you could use:
----------- ---- ------- ------
Application python 0.0.0.0 C:\Users\leela\code\mysuperapp\env\python.exe💬 Use the module "pip" to install and upgrade the package "pip" 🤯python -m pip install --upgrade pip███████████████ 38%
Install Packages¶
Now, after making sure we are inside of a virtual environment in some way, we can install Python packages, for example FastAPI:
In this case, as FastAPI is built on top of Starlette and Pydantic, when you install fastapi
they will also be automatically installed.