DEV Community

Emmanuel Kariithi
Emmanuel Kariithi

Posted on

Improve Python Code Quality With Pylint

Introduction

In this article, we shall look at Pylint and how it's used to ensure that your python code conforms to PEP8 guidelines.

What is PEP8?

PEP8 is a document that provides guidelines and best practices on how to write python code, thus making the code readable and consistent.

Content

  1. What is Pylint
  2. Install Pylint
  3. Create a simple quiz app
  4. Run Pylint on our Quiz app
  5. Make recommended changes.
  6. Conclusion

What is Pylint

Pylint is a python tool that checks for errors and tries to enforce a coding standard.

Install Pylint

Install Pylint via terminal pip install pylint or pip3 install pylint.

Create a simple quiz app

Build a simple python quiz app which will include five quizzes from the renowned show "The Big Bang Theory", then run Pylint on it and make the recommended changes.

Procedure:

  1. Make a directory of the project. I named mine quiz_app. Run mkdir quiz_app in your terminal
  2. Change into your quiz_app directory. Run cd quiz_app
  3. You can create the file at this point. Runtouch app.py
  4. Open Vs Code Code .
  5. Open the created file and input the code below. Alternatively, you can copy the code directly from this repository.
import random
from string import ascii_lowercase
NUM_QUESTIONS_PER_QUIZ = 5
QUESTIONS = {
    "How old was Sheldon when he got his first P.h.d?": [
        "16",
        "18",
        "20",
        "22",
    ],
    "What’s Amy’s job": [
        "Neurobiologist",
        "Marine biologist",
        "Forensic biologist",
        "Microbiologist",
    ],
    "Which couple gets married first?": [
        "Bernadette and Howard",
        "Penny and Leonard",
        "Amy and Sheldon",
        "Emily and raj",
    ],
    "What is Leonard primary health concern?": [
        "He is lactose intolerant",
        "He is allergic to peanuts",
        "He has to eat gluten free",
        "He has diabetes",
    ],
    "Who does Howard meet while serving Thanksgiving dinner at a shelter?": [
        "Elon Musk",
        "Jeff Bezos",
        "Bill Gates",
        "Steve Jobs",
    ]
}

num_questions = min(NUM_QUESTIONS_PER_QUIZ, len(QUESTIONS))
questions = random.sample(list(QUESTIONS.items()), k=num_questions)

num_correct = 0
for num, (question, alternatives) in enumerate(questions, start=1):
    print(f"\nQuestion {num}:")
    print(f"{question}?")
    correct_answer = alternatives[0]
    labeled_alternatives = dict(
        zip(ascii_lowercase, random.sample(alternatives, k=len(alternatives)))
    )
    for label, alternative in labeled_alternatives.items():
        print(f"  {label}) {alternative}")

    while (answer_label := input("\nChoice? ")) not in labeled_alternatives:
        print(f"Please answer one of {', '.join(labeled_alternatives)}")

    answer = labeled_alternatives[answer_label]
    if answer == correct_answer:
        num_correct += 1
        print("⭐ Correct! ⭐")
    else:
        print(f"The answer is {correct_answer!r}, not {answer!r}")

print(f"\nYou got {num_correct} correct out of {num} questions")
Enter fullscreen mode Exit fullscreen mode

Run Pylit on our quiz_app

Now, run pylint on the above code. If you are using Vs Code, launch bash and run pylint app.py. You have to specify the python file after pylint.
Alternatively, you can run pylint on your terminal by changing into your quiz_app directory and run pylint app.py.
After running pylint, the command window will display the Pylint results. The result is as shown below:

************* Module app
app.py:62:0: C0304: Final newline missing (missing-final-newline)
app.py:1:0: C0114: Missing module docstring (missing-module-docstring)
app.py:41:0: C0103: Constant name "num_correct" doesn't conform to UPPER_CASE naming style (invalid-name)
app.py:62:48: W0631: Using possibly undefined loop variable 'num' (undefined-loop-variable)

------------------------------------------------------------------
Your code has been rated at 8.18/10  
Enter fullscreen mode Exit fullscreen mode

Note that app.py:62:0, indicates what line is affected while C0304:, is a message code. In this case, the first line refers to a coding standard violation in line 62, column 0.
There are other message codes that you can get apart from the above shown. Below is a list of prefixes and their meanings.

  • [R] Refactor for a "good practice" metric violation
  • [C] Convention for coding standard violation
  • [W] Warning for stylistic problems, or minor programming issues
  • [E] Error for important programming issues (i.e. most probably bug)
  • [F] Fatal for errors which prevented further processing

At the end of the result shown, there is a grading that Pylit does. This grading shows how your code conforms to PEP 8. This code received an 8.18 out of 10. Try to get it to a 10 out of 10.

Make Recommended changes

Create a new file and name it app_modified.py. Copy the code from app.py,which will be used to make the recommended changes.
Start with C0103: Constant name "num_correct" doesn't conform to UPPER_CASE naming style (invalid-name) As you can see, pylint lets us know that we have to change num_correct to uppercase. Find and replace num_correct to NUM_CORRECT used in three instances.
Running Pylint at this point gives us a score of 8.64 out of 10.
For C0114: Missing module docstring (missing-module-docstring). A docstring is a short description of what your code does, and it may include specifics on aspects of the code. It mainly occurs as the first statement in a module, function, class, or method definition.
We will add """A quiz app based on the show: The Big Bang Theory""" at the start of our program.
For C0304: Final newline missing (missing-final-newline), we will add an empty line at the end of our program.
We can ignore W0631: Using possibly undefined loop variable 'num' (undefined-loop-variable). Since changing it will affect how our program runs.
Running Pylint at this point gives us a score of 9.55 out of 10.
Your final code will be similar to this:

"""A quiz app based on the show: The Big Bang Theory"""
import random
from string import ascii_lowercase

NUM_QUESTIONS_PER_QUIZ = 5
QUESTIONS = {
    "How old was Sheldon when he got his first P.h.d?": [
        "16",
        "18",
        "20",
        "22",
    ],
    "What’s Amy’s job": [
        "Neurobiologist",
        "Marine biologist",
        "Forensic biologist",
        "Microbiologist",
    ],
    "Which couple gets married first?": [
        "Bernadette and Howard",
        "Penny and Leonard",
        "Amy and Sheldon",
        "Emily and raj",
    ],
    "What is Leonard primary health concern?": [
        "He is lactose intolerant",
        "He is allergic to peanuts",
        "He has to eat gluten free",
        "He has diabetes",
    ],
    "Who does Howard meet while serving Thanksgiving dinner at a shelter?": [
        "Elon Musk",
        "Jeff Bezos",
        "Bill Gates",
        "Steve Jobs",
    ]
}

num_questions = min(NUM_QUESTIONS_PER_QUIZ, len(QUESTIONS))
questions = random.sample(list(QUESTIONS.items()), k=num_questions)

NUM_CORRECT = 0
for num, (question, alternatives) in enumerate(questions, start=1):
    print(f"\nQuestion {num}:")
    print(f"{question}?")
    correct_answer = alternatives[0]
    labeled_alternatives = dict(
        zip(ascii_lowercase, random.sample(alternatives, k=len(alternatives)))
    )
    for label, alternative in labeled_alternatives.items():
        print(f"  {label}) {alternative}")

    while (answer_label := input("\nChoice? ")) not in labeled_alternatives:
        print(f"Please answer one of {', '.join(labeled_alternatives)}")

    answer = labeled_alternatives[answer_label]
    if answer == correct_answer:
        NUM_CORRECT += 1
        print("⭐ Correct! ⭐")
    else:
        print(f"The answer is {correct_answer!r}, not {answer!r}")

print(f"\nYou got {NUM_CORRECT} correct out of {num} questions")

Enter fullscreen mode Exit fullscreen mode

Conclusion

There are a number of tools used to improve your python code quality, Pylint is one of them. You can read more about improving your code quality here.

Top comments (0)