Managing Python versions and environments in macOS

I have been using Python for a while now, and managing dependencies and versions always has been a pain. macOS still comes with Python2.7, but most dev works have moved to Python3.

This time around, I saw myself using Python more and more and decided to stop kicking the can down the road and “properly” set up Python (at least for my use cases). This is a quick setup summary on how I set up and manage my Python versions and environments using pyenv and pyenv-virtualenv. These tools are also compatible with various Linux distributions such as Debian, Ubuntu, Mint.

Prerequisite: Homebrew

1. Install Dependencies

brew install openssl readline sqlite3 xz zlib
brew install pyenv
brew install pyenv-virtualenv

2. Update your shell file (.zshrc or .bash_profile)

echo -e 'if command -v pyenv 1>/dev/null 2>&1; then\n  eval "$(pyenv init -)"\n eval $(pyenv virtualenv-init -)"\n  fi' >> ~/.zshrc

echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.zshrc
echo 'export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.zshrc
echo 'export PATH="$PYENV_ROOT/shims:$PATH"' >> ~/.zshrc

These should add the following lines to your shell file (use cat ~/.zshrc for a quick check)

# ...
if command -v pyenv 1>/dev/null 2>&1; then
  eval "$(pyenv init -)"
  eval "$(pyenv virtualenv-init -)"
fi
export PYENV_ROOT="$HOME/.pyenv"
export PATH="$PYENV_ROOT/bin:$PATH"
export PATH="$PYENV_ROOT/shims:$PATH"
# ...

3. Install and configure Python version using Pyenv

# List available versions
pyenv versions

# Install desired version
pyenv install 3.9.1 

# Set Global Python version
pyenv global 3.9.1

4. Create and configure a virtual environment

# Change directory to the desired location where you will work from your virtual environment

# Create a virtualenv
pyenv virtualenv 3.9.1 my_sandbox

# Set the Python version to the virtualenv you created 
pyenv local my_sandbox

5. Happy Coding!

Now you should have an active virtual environment to install dependencies isolated from the global Python installation. If you move in/out of a configured directory, the virtual environment should activate/deactivate automatically. If not, you can run pyenv activate/deactivate.

Here are a few references for more details on hoy pyenv and pyenv-virtualenv work.

  1. pyenv repositry
  2. Pyenv-virtualenv repository
  3. Python: Creating a clean learning environment with pyenv, pyenv-virtualenv & pipX
  4. The right and wrong way to set Python 3 as default on a Mac