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
- What is Pylint
- Install Pylint
- Create a simple quiz app
- Run Pylint on our Quiz app
- Make recommended changes.
- 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 terminalpip install pylint
orpip3 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:
- Make a directory of the project. I named mine quiz_app.Run
mkdir quiz_app
in your terminal - Change into your quiz_app directory.Run
cd quiz_app
- You can create the file at this point.Run
touch app.py
- Open Vs Code
Code .
- Open the created file and input the code below. Alternatively, you can copy the code directly from thisrepository.
import randomfrom string import ascii_lowercaseNUM_QUESTIONS_PER_QUIZ = 5QUESTIONS = { "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 = 0for 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")
Run Pylit on our quiz_app
Now, run pylint on the above code. If you are using Vs Code, launch bash and runpylint 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 runpylint app.py
.
After running pylint, the command window will display the Pylint results. The result is as shown below:
************* Module appapp.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
Note thatapp.py:62:0, indicates what line is affected whileC0304:, 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 itapp_modified.py
. Copy the code fromapp.py
,which will be used to make the recommended changes.
Start withC0103: 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 changenum_correct
to uppercase. Find and replacenum_correct
toNUM_CORRECT
used in three instances.
Running Pylint at this point gives us a score of 8.64 out of 10.
ForC0114: Missing module docstring (missing-module-docstring)
. Adocstring 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.
ForC0304: Final newline missing (missing-final-newline)
, we will add an empty line at the end of our program.
We can ignoreW0631: 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 randomfrom string import ascii_lowercaseNUM_QUESTIONS_PER_QUIZ = 5QUESTIONS = { "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 = 0for 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")
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 qualityhere.
Top comments(0)
For further actions, you may consider blocking this person and/orreporting abuse