Installing Python3 on macOS

 Mar 21, 2020

A new role meant a change of language. After 3 years working with Ruby on Rails, and prior to that with PHP, I find myself working with a Python/Django stack. As I start this journey I feel that renewing the old blog and sharing my learning would be a great way to cement the new tools. To start this off again I figured to start at the beginning. How do you get Python!

I’ll cover setting this up on macOS (I’m afraid my experience on Windows stopped with XP, and my use of Linux on the desktop was around Warty Warthog).

By default macOS comes with Python 2.x pre-installed, but as of January 2020 the community has end-of-life’d 2.x and is focusing on getting everyone onto version 3. Although 3 has been out since 2008, people have been slow to migrate. As many things still run on Python 2, the best practice is to have both versions installed and set up virtual environments using the relevant version for each project you work on. Please use 3.x for any new projects unless you have a really compelling reason not to.

As a Rubyist I became a big fan of Rbenv to manage Ruby versions, so the first thing I did was search for a Python equivalent and found Pyenv.

You can install Pyenv via Homebrew (full instructions are in the README using the link above).

brew install pyenv

Once the Homebrew install finishes, you will need to follow the instructions to add the initializer to your shell config (~/.bashrc or ~/.zshrc for example).

# Add the following to your shell config file
export PATH="$HOME/.pyenv/bin:$PATH"
eval "$(pyenv init -)"

Then restart your terminal, or run exec "$SHELL" to re-initialize your current session.

With Pyenv now installed and configured, you can install any Python version and even run different versions for different projects.

You can see which versions are available to install with the following command:

pyenv install --list

Then install the version you want to use with:

pyenv install <VERSION>

Once you’ve gotten this far I highly recommend installing the Pyenv-virtualenv plugin. This made various things much easier for me later on. Python 3 ships with venv now, which is it’s own virtual environment manager. Pyenv-virtualenv defers to venv when using Python 3. Follow the install instructions on the repository README to add this plugin to your Pyenv installation.

You can use the virtual environments to configure a work environment with a specific Python version and only the dependencies needed for that project.

Create the environment with:

pyenv virtualenv <VERSION> <ENV_NAME>

E.g.

pyenv virtualenv 3.8.1 my_new_app

Then activate it with:

pyenv activate my_new_app

Once the virtual environment is activated you can use the default package manager pip to install any libraries or dependencies you want to use without them polluting the system Python or other projects.

I hope this helps. I’ll be sharing more Python related content in the weeks to come as I learn more myself.