1.1. Automation#

1.1.1. Automate Bash Commands with Makefile#

Do you struggle to remember the exact series of commands needed to build and package a Python project?

Or manually running tests and installing dependencies?

Makefile to the rescue!

A Makefile can be used to automate bash commands and have a standardized way to execute those.

See below for how we define commands for testing, install our dependencies, and format our code with black.

# Create a file named Makefile
# Makefile

install:
    @echo "Installing requirements ..."
    pip install -r requirements.txt --quiet

test:
    @echo "Testing ..."
    pytest

format:
    @echo "Formatting ..."
    black .

1.1.2. Automate Testing with Nox#

Testing your code against multiple Python Versions is hard.

With Nox, you can automate this step!

Nox is a command-line tool to automate testing in multiple Python Environments locally.

You can customize the sessions with a Python script.

See the example below, where we define a session (𝐭𝐞𝐬𝐭𝐬) in our 𝐧𝐨𝐱𝐟𝐒π₯𝐞.𝐩𝐲 and define the Python versions we want to test against. Moreover we set up another session (π₯𝐒𝐧𝐭) to run flake8 against our code.

Nox is highly customizable, so check out their documentation.

# noxfile.py

import nox

@nox.session(python=["3.6", "3.7", "3.8", "3.9"])
def tests(session):
    # Install testing dependency
    session.install('pytest')
    # Run tests
    session.run('pytest')
    
@nox.session
def lint(session):
    session.install("flake8")
    session.run("flake8", "example.py")
!pip install nox
!nox

1.1.3. Update Your Dependencies Automatically with pyup#

Do you need an easy way to update your project’s dependencies?

Try pyup.

pyup goes through your dependency files and searches for new package versions.

It will then create a new branch in your repository, a new commit for every update and a pull request containing all commits.

You only need to provide an access token (from GitHub or GitLab) and the repository name.

!pip install pyupio
!pyup --repo=username/repo --user-token=<YOUR_TOKEN> --initial # After running the first time, you can remove the --initial flag
# gitlab.com:
!pyup --provider gitlab --repo=username/repo --user-token=<YOUR_TOKEN>