Python: Virtual Environments

Python Virtual Environments (venv) is a python module that limits dependency and version conflict by:

  • Isolating the python environment
  • Separating dependencies on a project basis

Usage

# Create a venv:
python3 -m venv .venv

# Active venv:
source env/bin/activate

# On windows
.\env\Scripts\activate

# deactivate
deactivate

Workflow

  1. Create a venv using the mod (-m) argument or via IDE (VSCode -> ctrl + shift + p -> Python: Create env)
  2. Activate it using your OS specific way
  3. Add .venv (venv name in the example above) to .gitignore
  4. Develop python code, install packages: pip install <package>
  5. Once done, freeze requirements: pip freeze > requirements.txt
  6. Recreate exact environment on another host: pip install -r requirements.txt

Mucho Importante

  1. Always activate the venv when working on the project
  2. .gitignore the venv name, the users will build it locally
  3. Use pip freeze after installing new dependencies to update the requirements.txt

Always look on the bright side of isolation ✅

Happy coding