pyenv is rad

This isn't news to anybody, but using pyenv to manage virtual environments for Python is great. The python packaging and module system is really annoying, but pyenv makes it tolerable enough that I felt like writing it down.

Setup is pretty simple. You basically need to:

  1. Install pyenv itself
  2. Install pyenv-virtualenv
  3. Install a specific python version
  4. Create a new virtual environment using that specific version of python

For Mac

# install pyenv (assumes homebrew)
brew install pyenv pyenv-virtualenv

# update ~/.zshrc so commands are available on path
cat >>~/.zshrc <<'EOL'
export PATH="$HOME/.pyenv/bin:$PATH"
eval "$(pyenv init -)"
eval "$(pyenv virtualenv-init -)"

# reload
source ~/.zshrc

And for Ubuntu

# install dependencies
sudo apt install -y build-essential libssl-dev libffi-dev zlib1g-dev libbz2-dev liblzma-dev
sudo apt install -y python3-dev python3-pip

# install pyenv, via
git clone ~/.pyenv
echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.bashrc
echo 'export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.bashrc
echo -e 'if command -v pyenv 1>/dev/null 2>&1; then\n  eval "$(pyenv init -)"\nfi' >> ~/.bashrc
exec "$SHELL"

# install pyenv-virtualenv plugin
git clone $(pyenv root)/plugins/pyenv-virtualenv
echo 'eval "$(pyenv virtualenv-init -)"' >> ~/.bashrc
exec "$SHELL"

Finally, now that pyenv is installed, you can use it to manage virtual environments

For example, to try out the new Python 3.9 features

pyenv install 3.9.0
pyenv virtualenv 3.9.0 threenine
pyenv activate threenine
python --version