Creating a Python virtual environment
As for many programming languages of today, the power of Python comes from the vast ecosystem of third-party libraries, including FastAPI, of course, that help you build complex and high-quality software very quickly. The Python Package Index (PyPi) (https://pypi.org) is the public repository that hosts all those packages. This is the default repository that will be used by the built-in Python package manager, pip
.
By default, when you install a third-party package with pip
, it will install it for the whole system. This is different from some other languages, such as Node.js’ npm
, which by default creates a local directory for the current project to install those dependencies. Obviously, this may cause issues when you work on several Python projects with dependencies having conflicting versions. It also makes it difficult to retrieve only the dependencies necessary to deploy a project properly on a server.
This is why Python developers generally use virtual environments. Basically, a virtual environment is just a directory in your project containing a copy of your Python installation and the dependencies of your project. This pattern is so common that the tool to create them is bundled with Python:
- Create a directory that will contain your project:
$ mkdir fastapi-data-science$ cd fastapi-data-science
Tip for Windows with WSL users
If you are on Windows with WSL, we recommend that you create your working folder on the Windows drive rather than the virtual filesystem of the Linux distribution. It’ll allow you to edit your source code files in Windows with your favorite text editor or integrated development environment (IDE) while running them in Linux.
To do this, you can access your C:
drive in the Linux command line through /mnt/c
. You can thus access your personal documents using the usual Windows path, for example, cd /mnt/c/Users/YourUsername/Documents
.
- You can now create a virtual environment:
$ python -m venv venv
Basically, this command tells Python to run the venv
package of the standard library to create a virtual environment in the venv
directory. The name of this directory is a convention, but you can choose another name if you wish.
- Once this is done, you have to activate this virtual environment. It’ll tell your shell session to use the Python interpreter and the dependencies in the local directory instead of the global ones. Run the following command:
$ source venv/bin/activatee
After doing this, you may notice the prompt adds the name of the virtual environment:
(venv) $
Remember that the activation of this virtual environment is only available for the current session. If you close it or open other command prompts, you’ll have to activate it again. This is quite easy to forget, but it will become natural after some practice with Python.
You are now ready to install Python packages safely in your project!