Python Virtualenvs

Menno Finlay-Smits

The Problem

  1. Projects need different Python dependencies to the operating system's pacakges
    • Operating system provided packages are usually out of date
  2. Different project require different dependencies
    • Project X needs Django 1.11 but Project Y needs Django 2.2

The Solution

  • Virtual environments (aka "virtualenvs")
  • Isolated place to install packages for a project
  • When activated, Python will look in the virtualenv for packages
  • Tied to a particular Python version

More

  • Created by Ian Bicking (pre-cursor was workingenv)
  • They're a bit of a clever hack
  • Not portable!
    • You can't move them to another location

"Classic" virtualenv demo

  • Creating: virtualenv [--python=<python_executable>] <name>
  • Enabling and disabling: activate and deactivate
  • Isolation
  • Removing

venv

  • Similar idea but ships with Python (since 3.3)
  • Will only create venv for Python version it's run with
  • python3 -m venv /some/directory

virtualenvwrapper

  • virtualenv workflow commands:
    • mkvirtualenv: create
    • workon: select/activate
    • lsvirtualenv: list
    • rmvirtualenv: remove
    • and more…
  • shell completion
  • targets Linux and OS X
    • see virtualenvwrapper-win for Windows
  • demo!

pew

  • similar to virtualenvwrapper but more cohesive UI
    • pew new <name>
    • pew workon <name>
    • pew in <name> <command>
    • pew ls
    • pew rm <name>
  • Written in Python instead of shell scripts
  • demo!

Other related tools

  • pipx and pipsi
    • install individual Python apps in their own virtualenv
  • pipenv
    • "Python dev workflow for humans"
    • composer/cargo/yarn for Python
    • combines pip+virtualenv+more into a single tool
  • poetry
    • similar goals to pipenv
    • looks promising

More tools

  • pyenv
    • switch between Python versions and virtualenvs
  • tox
    • testing across Python versions,
    • uses virtualenvs under the hood