Tips

Create a Python virtual environment


What a virtual environment is

When you work on a project that uses a certain version of Python, for example, new Python updates may come out that are incompatible with your project.
If you have several projects that don’t use the same versions, it can become a nightmare.
The role of a virtual environment is to have a Python installation with all the dependencies for each project. This way, you can easily work on different projects using different Python versions on the same computer.

Venv and Virtualenv

Venv is built into Python since version 3.3, it’s native, which means that as soon as you have Python installed on your machine, you have venv.
Virtualenv, on the other hand, is a third-party tool that you have to download separately. It has more features than Venv, for example you can create an environment for a specific Python version.

pip install virtualenv

Creating the environment with Venv

You can replace “env” with whatever folder name you want for your environment.

python -m venv env

Creating the environment with Virtualenv

You can replace “env” with whatever folder name you want for your environment.

virtualenv env

To create the virtual environment with a specific Python version.**
Note that to choose that version, you have to install it on your PC beforehand.**

virtualenv -p python3.10 env

Activating the virtual environment (Windows):

Don’t forget to replace “env” with the name of your environment’s folder.

env/Scripts/activate

Activating the virtual environment (Linux):

Don’t forget to replace “env” with the name of your environment’s folder.

source env/bin/activate

If that doesn’t work (I don’t know if it’s due to an update), just replace “bin” with “Scripts”.

source env/Scripts/activate

Leaving the virtual environment:

deactivate