How To Quality-Check Python Code Using Pylint On CI?

Reading Time: 2 minutes

In this article, we will talk about how to quality-check Python code using Pylint on CI.

Code Quality Through CI

As we know, code quality is an important aspect of any project. It is the responsibility of every developer to quality-check the code before pushing it to the repository.

However, to enforce this and implement the concepts of Continuous Integration (CI), we need to have a step in our CI pipeline that takes care of this and gives feedback to the developer,

Now, there are different ways of doing this and one such popular approach is to create a custom script that runs on our CI each time the code is pushed to the repository.

However, that is not considered the best practice since we should be keeping our CI decoupled from misc files and code as much as possible.

How To Quality-Check Python Code Using Pylint On CI?

For this tutorial, we will be using Pylint, a popular linting tool for Python, alongside GitHub Actions. However, you can implement the same logic on any CI platform of your choice.

There is a community provided, GitHub Action for Pylint: https://github.com/marketplace/actions/github-action-for-pylint

You can use it someway like this:

- uses: cclauss/GitHub-Action-for-pylint@0.7.0
- run: pylint **/*.py

However, if you are using some other CI tool apart from GitHub Actions where you don’t have an inbuilt option to use Pylint then you can have a custom implementation as well:

  check_unused_imports:
    name: Check for unused imports
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - name: Count unused imports
        run: |
          sudo apt install pylint -y
          echo "::set-output name=UNUSED_COUNT::$(pylint * | grep "unused-import" | wc -l)"
        id: unused_check
      - name: Print files with unused imports
        if: ${{ steps.unused_check.outputs.UNUSED_COUNT > 0 }}
        run: |
          pylint * | grep "unused-import"
      - name: Fail job is any unused imports are there
        if: ${{ steps.unused_check.outputs.UNUSED_COUNT > 0 }}
        uses: actions/github-script@v3
        with:
          script: |
            core.setFailed('Code has unused imports! Please `run pylint * | grep "unused-import"`')

Again, the above example was created using GitHub Actions. However, due to YAML, it will be pretty easy to convert it for any other popular CI tool out there.

The example is flexible so you can change the commands and the output. It also lets you fail the pipeline if any of your custom checks fail.

Written by 

Mohit Saxena is a Software Consultant having experience of more than 2 years. He is always up for new challenges and loves to aggressively move towards completing the software requirements. On a personal front, he loves to climb mountains and is a big foodie.

Leave a Reply