Virtual environments are a vital part of modern application development, regardless of the stack you are using. Virtual environments avoid problems related to dependency and version incompatibility. In this guide, I will show you three popular ways to use virtual environments in Python.
Venv
Python Venv is a built-in tool to create and manage lightweight virtual environments.
For more information visit: venv tutorial.
Installation:
Already installed on MacOS and Windows platforms, but needs to be installed on some Linux distros, here is an installation guide for different package managers:
sudo dnf install python3-env # using dnf
sudo pacman -S python3-env # using pacman
Creating a Virtual Environment:
python -m venv <env_name> # windows
Activating the Virtual Environment:
On Unix-like systems (Unix, Linux, or MacOS):
On Windows:
Deactivating the Virtual Environment:
Virtualenv
virtualenv is a simple to use tool to create isolated Python environments.
For more information visit: virtualenv documentation.
Installation:
Creating a Virtual Environment:
Activating the Virtual Environment:
On Unix-like systems (Unix, Linux, or MacOS):
On Windows:
Deactivating the Virtual Environment:
Pyenv (Unix, Linux or MacOS only)
Pyenv is a popular option in Python applications. Pyenv allows you to manage different versions of Python in your application and also on your system.
Pyenv does not officially support Windows but you can use WSL (Windows Subsystem for Linux).
For more information visit: pyenv repository
Installation:
You can install using Homebrew or make a manual installation:
Using Homebrew:
brew install pyenv
Manual Installation:
Download pyenv:
curl https://pyenv.run | bash
Let’s edit your bash profile:
nano .bashrc
Add these lines in the end of the document:
export PYENV_ROOT=“$HOME/.pyenv”
export PATH=“$PYENV_ROOT/bin:$PATH“
eval “$(pyenv init –path)“
Creating a Virtual Environment:
Activating the Virtual Environment:
Deactivating the Virtual Environment:
Managing Python Versions:
Pyenv allows you to manage python versions, here is a simple tutorial that you can use in your application or in your input system:
List available versions:
Install a version:
Defining a version:
pyenv local <version> # set a local version
Conclusion:
The tools are very similar, the biggest difference is in the installation process and in some specific features, such as python version management (pyenv), you can choose according to your taste or personal preference, I recommend that you test each one of them and see that best suits your project.