Automatic Python Code Format with GitHub Actions

Introduction

To begin with – let’s discuss first what are GitHub Actions and what magic they bring 😃?

GitHub Actions

GitHub Actions is that piece of magic which enables you to automate, customize, and execute your software development workflows right in your repository.

But hey? What are words without actions? And so what are actions without workflows? Yes, you got it right! For GitHub Actions to work you need to use Workflows but what are Workflows?
A workflow is a configurable automated process made up of one or more jobs. Now, these jobs can be like the accounting of the trigger for the GitHub action to work – like push on the main branch.

Workflow files use YAML syntax and must have either a .yml or .yaml file extension.
This post introduces a method for beautifying Python Code with GitHub Actions. The method utilizes three tools: autopep8, Black, isort. In addition, a Pull Request, which contains formatted codes is created by GitHub Actions.

The YAML file shows the configuration of the automatic code formatter.

name: Format Python Code
on: push
jobs:
  python-code-format:
    runs-on: ubuntu-20.04
    steps:
      - uses: actions/checkout@v2
      - uses: actions/setup-python@v4
        with:
          python-version: "3.10"
          architecture: "x64"
      - name: Display Python version
        run: python --version
      - name: Install packages
        run: pip install black autopep8 isort
      - name: Formatter
        run: |
          black .
          autopep8 --recursive --in-place --aggressive --aggressive .
          isort .
      - name: Create Pull Request
        uses: peter-evans/create-pull-request@v3
        with:
          commit-message: Auto code format
          title: Fixes by format action
          body: This is an auto-generated PR with fixes.
          labels: automated pr
          branch: python-code-format-patches

The summary of this configuration file is shown as follows:

The CI works as follows:

Image description

Exit mobile version