Skip to content

How To Use Pylint To Write Clean Python Code

Pylint is a linting tool used to analyse the Python code and identify the issues. In this post, we will learn how to use Pylint in Python.

What is Linting?

Linting is the process of adhering to coding standards. It helps maintain a consistent code style within the project and makes the codebase more readable and maintainable. Linting is the subset of the static code analysis process. Linters check the code for formatting consistency, naming conventions, and other style-related issues

What is Static Code Analysis?

Static code analysis is a technique used to analyse the codebase without executing it. The purpose of this process is to find potential defects, security vulnerabilities, and coding style issues in the codebase early in the development phase. Static code analysis is performed by tools or scanners specifically designed to scan the source code and check for patterns or issues that may lead to problems in the future.

Common Linting Tools

Linters are generally integrated with the code editors. Some of the famous linting tools are as follows:

  1. ESLint for JavaScript.
  2. The Linter for Java.
  3. PHP_CodeSniffer for PHP.
  4. TSLint for typescript.
  5. Pylint for Python.
  6. HTMLLint for HTML.

How to install Pylint?

Pylint is not available with Python by default. We can either install it using the Python package manager or use the Pylint extension.

1)Install it using the pip module

pip install pylint

check Pylint version

pylint --version

2)How to use Pylint in Visual Studio code

  1. Open Visual Studio Code.
  2. Go to the Extensions in the left sidebar or use the shortcut Ctrl+Shift+X (or Cmd+Shift+X on macOS).
  3. Search for “Python” in the Extensions view search bar.
  4. Install the official Python extension by Microsoft.
  5. Open the Python project.
  6. Go to Extension in the left sidebar again search for ‘Pylint’ and install it.
Pylint

How to run Pylint?

To use Pylint execute the below-mentioned command in the Python environment.

pylint filename.py

If you want to check all the Python files in the directory, execute the command mentioned below.

pylint *.py

How to Use Pylint for Python Code

To write the clean Python code we require below mentioned steps:

  1. Write Python Source code.
  2. Install Pylint
  3. Parse the source code and run through the linting tool.
  4. Review the results
  5. Fix the code.

Step_1: Write Python Source code

For the demo purpose I am using this code which I used to demo how to use the Python requests module for API testing automation.

import requests
import json
import pytest

ENDPOINT = 'https://reqres.in/api/'
USER = 'users/2'

def test_get_endpoint():
    response = requests.get(ENDPOINT+USER)
    assert response.status_code==200
    print(response)

def test_createUser_request():
    payload = { 
    "name": "morpheus01",
    "job": "leader"

}
response = requests.post(ENDPOINT + "users",json=payload,timeout=10)
    assert response.status_code==201
    json_response =json.loads(response.text)
    

Save this code in a Python file named ‘testLintingDemo.py’ and execute the command “testLintingDemo.py” in a Python environment or if you are using the Pylint extension in VSCode then you will see linting issues in the problems section. We can see the list of issues lined up with the issue and the line and column name along with the message category.

Pylint Report

In the above image, we can see all the issues along with the message category. Refer to the below table for the message category.

CategoryNameDescription
CConventionIt is displayed when the program is not following the standard rules.
RRefactorIt is displayed for bad code smell
WWarningIt is displayed for python specific problems
EErrorIt is displayed when that particular line execution results in some error
FFatalIt is displayed when Pylint has no access to further process that line

Fix the Code smells Issues

The first warning I see is related to the unused import package Pytest with the message category ‘WO611’.This warning can be fixed by removing the unused import.

The next issue is related to the “Missing timeout argument for method ‘requests. get’ can cause your program to hang indefinitely”. To resolve this add the timeout in the get and post methods.

response = requests.get(ENDPOINT+USER,timeout=10)
response = requests.post(ENDPOINT + "users",json=payload,timeout=10)

The third issue is of convention category that says “Function name “test_createUser_request” doesn’t conform to snake_case naming stylePylint C0103:invalid-name“. To fix this change the method name following the snake case.

Change test_createUser_request to test_createuser_request

Note: Java Follows the Camel case while Python follows the snake case convention.

Updated code after fixes should look like this:

import requests
import json

ENDPOINT = 'https://reqres.in/api/'
USER = 'users/2'

def test_get_endpoint():
    response = requests.get(ENDPOINT+USER,timeout=10)
    assert response.status_code==200
    print(response)

def test_createuser_request():
    payload = { 
    "name": "morpheus01",
    "job": "leader"
    }
    response = requests.post(ENDPOINT + "users",json=payload,timeout=10)
    assert response.status_code==201
    json_response =json.loads(response.text)

There can be other linting issues related to bad indentation, trailing whitespace, variable usage and many others. By using Pylint we can format our code and write clean code by following coding standard rules and guidelines. This post is intended to guide software testers on how To Use Pylint To Write Clean Python Code. You can dive more into this and improve your codebase.

Tags: