Using Python venv

Preface

Python is renowned for its rich set of modules. However, unlike in Java development where Maven uses group Id, artifact Id, and version to uniquely identify a dependency, in practice, most Python projects differentiate modules solely by their names. Run pip install <module>, and you’ve got the module. But what about the module version? Most project requirements do not specify versions, leading to constant errors for those who run the project later.

Hence, the concept of a weakened version number undoubtedly does more harm than good. How to solve this issue? By using venv (virtual environment).

If you directly use pip install, all Python projects share these modules, leading to potential compatibility issues. Venv copies the original Python environment. The virtual environment runs only on the copied Python, and the installed modules exist only in that virtual environment. Multiple virtual environments are isolated from each other.

Usage

1️⃣Create venv:

1
python -m venv C:\Users\Gustav\Desktop\test\venv

The directory C:\Users\Gustav\Desktop\test\venv is the virtual environment.

2️⃣Activate:

1
venv\Scripts\activate

If (venv) appears in front of the prompt, it means activation is successful, and you can now freely work inside.

1
(venv) C:\Users\Gustav\Desktop\test>pip list

3️⃣Deactivate:

1
2
(venv) C:\Users\Gustav\Desktop\test>deactivate
C:\Users\Gustav\Desktop\test>

Reference

venv — Creation of virtual environments