Installing Python

You want to run a script handed over by a colleague, to install this CLI tool, to create a new project. What is the proper way to install python once and for all.

tldr:

Use pyenv, and for your own sake, please use virtualenv.

Understanding the PATH

The PATH is the environment variable your operating system uses to determine where executable files exists on your computer.

echo $PATH
# Each full path are separated by semi colons.
/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin

To add a script to your PATH you can :

export PATH=$PATH:/i/am/a/folder/with/a/script

Python has to be in your PATH to run python in your terminal. Installing python, or a specific version of python is effectively, installing the python binary and telling your computer where to look for this binary.

# Use which to know the location of the binary you are using.
which python
/Users/gaetan.pierrejustin/.pyenv/shims/python

Historically python moved from version 2 to version 3. That’s why for macOS, python is bound to python version 2 and python3 to python version 3.

Python via pyenv

Python changes a minor version every year or so, and some packages have hard requirement around python version. Pinning your python version is standard practice when creating a long-lived project. Resulting in dependencies to different version of python in depending on the project.

To make sure you don’t have other versions of python in your PATH, I recommend to first uninstall any python version not packaged by your operating system. They can be coming from brew, any package manager, the manual installer

pyenv is a tool that helps you manage versions of python by intercepting a python command and choosing the right python version to execute (depends on your configuration).

Install pyenv

Installation steps in the pyenv repository. With brew, you can simply do.

brew update
brew install pyenv
Install & choose python version

Python version can be installed with a single command.

pyenv install 3.10

Versions can be set at three scopes :

pyenv local 3.10
cat .python-version
3.10

Virtual Environment

If you’ve worked with python long enough, you already now that it can be a pain to work with dependencies. If not, I already feel for future you.

Make your life easy by following a few concepts :

pip install pipx
pipx install tox
virtualenv env
source env/bin/activate
pip install --user -r requirements.txt