Image by xkcd: Python Environment

The following section covers Python related setup for development and how to ensure that your code would be deployable.

Install brew

Homebrew is package manager for Macs which makes installing lots of different software like Git, Ruby, and Node simpler. Homebrew lets you avoid possible security problems associated with using the sudo command to install software like Node. Note this is only compatible with MacOS.

ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

You’ll see messages in the Terminal explaining what you need to do to complete the installation process. You can learn more about Homebrew at the Homebrew website.

Install pyenv

For local development never install packages or modify your system Python installation. To be able to install new or updated Python versions, use pyenv. Note this is only compatible with MacOS or Linux.

brew update
brew install pyenv

# Use Homebrew's directories rather than ~/.pyenv
echo 'export PYENV_ROOT="/usr/local/var/pyenv"' >> ~/.bash_profile

# Enable shims and autocompletion
echo -e 'if command -v pyenv 1>/dev/null 2>&1; then\n  eval "$(pyenv init -)"\nfi' >> ~/.bash_profile

source ~/.bash_profile

# Check pyenv has been properly installed and configured
pyenv versions

Python Versions

Using pyenv, install the necessary version for development. For example, we use Python 3.8.5 for development. For legacy projects, use Python 2.7.13

pyenv install 3.8.5
pyenv install 2.7.13

pyenv global 2.7.13 3.8.5

# Check versions have been installed and assigned to global
pyenv versions

Install pipenv

To make development and deployment easier, pipenv is used to manage virtual environments and lock dependencies.

The environment variable ensures that virtual environments are created within each project folder. The main reason is for convenience as Visual Studio Code automatically detects and switches virtual environments if .venv is found within the folder.

brew update
brew install pipenv

echo 'export PIPENV_VENV_IN_PROJECT=1' >> ~/.bash_profile

source ~/.bash_profile

Usage

cd path/to/project
pipenv --python 3.8.5
pipenv install <new_package>

Do remember to check in the generated/updated Pipfile and Pipfile.lock to be able to have reproducible builds in production.