How to install Python with Homebrew and Pyenv

Published : Feb 1, 2024

One of the biggest pain points in my early days of learning to code was version control. Not necessarily just of my own projects, but of the programming languages that I was using. Version control should most definitely be one of (not the first, but one of) the first things you learn when starting to code.

It will increase the chance of your projects being able to run smoothly as time goes on. For example, you may write a piece of code in python 3.6 and then try to run it again on python 3.9 and run into a whole bunch of errors. You will be sat there thinking what is wrong with my code, but the reality is your code is still perfect for python 3.6.

So to avoid this I want to get version control right from the off. To ensure we can safely test upgrading our python version before committing to it, we need to be able to store multiple versions of python.

Think of this as when you are trying to find the right head for a screwdriver. You’ve got one at the moment that works, but its not perfect, and you know you’ve got another 25 screws to go so want to make sure the head fits perfectly as to not ruin the screw heads.

When you don’t have a python version manager, every time you upgrade to a new version of python, you are throwing away that screwdriver head that already worked. If the new screwdriver head doesn’t fit the screw (new python version doesn’t work with your code), then you are screwed. Excuse the pun.

By using a python version manager, we can easily switch in and out of new python versions, we can open up our project on any laptop, computer in the library, Dad’s laptop - you name it, and we can easily load up the needed python version.

How to install homebrew

We are going to be doing this on a mac, to do so, we first need to install homebrew. Homebrew is a software package manager, which allows you to easily install and uninstall software using the brew command.To do this, we simply enter the following into our terminal in mac, then press enter:

We then want to add homebrew to our path by doing the following

Open up our zshrc file by:

Add this line to it:

How to install pyenv

We then need to add some specific OS dependencies, as pyenv builds Python from source. To do this we will use:

Now we are ready to install pyenv by entering the following:

How to install python with pyenv

You are now ready to install python. Simply type pyenv install, followed by the version you’d like, e.g:

You now need to set that version as your global version of python (the one used everywhere)

You can now double check you have the right version of python by running:

Congrats, you’re ready to follow python installation best practices!