Updating Python on MacOS Sierra

I started getting this error while pip installing a package from PyPi today:

ssl.SSLError: [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version

It looks like python is having trouble talking to PyPi, which has started requiring modern TLS 1.2. In case you missed the news, TLS 1.0 and 1.1 are being phased out internet-wide this year. Here’s the Python Software Foundation’s blog post about it.

MacOS currently ships with an ancient python: version 2.7.10, from 2015-05-23. Here’s how you can install a newer python 2 without waiting for Apple to update MacOS.

1. Install a newer python 2 with Homebrew

brew update && brew install python@2

2. Put it in front of the system python in your PATH

export PATH="/usr/local/opt/python@2/libexec/bin:$PATH"

3. Restart your Mac

I don’t know why, but opening a new terminal or logging out and in again isn’t enough to clear the module cache, and the new python will try and load modules from the old python. Do a full restart.

4. Update pip

pip install --upgrade pip

5. Check if everything is all right

$ which python
$ python --version
Python 2.7.14
$ python -c "import ssl; print(ssl.OPENSSL_VERSION)"
OpenSSL 1.0.2o  27 Mar 2018
$ pip --version
pip 10.0.1 from /usr/local/lib/python2.7/site-packages/pip (python 2.7)