Python Development on macOS with pyenv

John asked me if I had written a blog post on getting my Mac setup with pyenv. I hadn’t… So here it goes!

MacOS comes with Python 2.7 out-of-the-box. It’s great for first-timers and basic development, but as soon as you start working on more than one project you quickly realize that your projects may (will) have conflicting dependencies. One of those conflicting dependencies may be Python itself. How do you develop one project in Python 2.7 and another in Python 3.6? Enter pyenv.

From the docs:

pyenv lets you easily switch between multiple versions of Python. It’s simple, unobtrusive, and follows the UNIX tradition of single-purpose tools that do one thing well.

Installation Guide

Follow these steps to install pyenv on macOS. We’ll be installing pyenv via Homebrew so make sure you have it installed.

# Install Homebrew
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
# Install pyenv
brew install pyenv
# Add pyenv initializer to shell startup script
# ZSH USERS: use ~/.zshrc instead of ~/.bash_profile
# LINUX USERS: use ~/.bashrc instead of ~/.bash_profile
echo 'eval "$(pyenv init -)"' >> ~/.bash_profile
# Restart your shell for changes to take effect
exec $SHELL

Usage Guide

Yay! pyenv is installed and functioning. Now we can install multiple versions of Python and switch between them seamlessly.

Install Python

pyenv install <python-version>

You can view a full list of available versions with pyenv install --list. Go ahead and install Python 3.6.1:

pyenv install 3.6.1

View Installed Versions

Now that we’ve installed Python 3.6.1 let’s take a look at all the installed versions available on our system:

pyenv versions

You should see system and 3.6.1.

Set Global Python

pyenv global 3.6.1

Now whenever you call python you’ll be using Python 3.6.1. Check it with python --version.

Set Local Python

To set a Python version for a specific project, cd into your project and then run:

pyenv local <python-version>

That will create a .python-version file in the current directory which pyenv will see and use to set the appropriate version.


Conclusion

pyenv is a great tool for managing projects that depend on different versions of Python, but it doesn’t help us if we have two projects that use the same version of Python with different versions of pip packages. Check out Part 2: Python Development on macOS with pyenv-virtualenv.