22-11-2023 Project Sem7

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 28

Automated code review process Using python

INTRODUCTION :
Software development teams face challenges in maintaining code quality and
consistency. The manual code review process is time-consuming and prone to
human errors. This project aims to implement an automated code review system
using Python to enhance the efficiency and effectiveness of the
code review process.

MALLABHUM INSTITUTE OF TECHNOLOG


Python Code Review Tools
A code review is a process that applies various checks and tests to ensure that code is high
quality before it’s merged. During a code review, senior developers lend a second pair of
eyes to code, giving developers guidance from a more experienced counterpart.
A code reviewer looks for ways to improve code across several areas:

 Bugs: Code reviews can uncover bugs so they can be remediated before going into
production.

 Readability/maintainability: Code reviews are an opportunity to enforce style


guides to ensure developers can collaborate and understand each others’ work.

 Efficiency: Code reviews involve checks to ensure code will run quickly and
efficiently.

 Security: Code reviews ensure code is free of high-risk vulnerabilities.

Code reviews initially happened manually, but a variety of tools exist to help
developers automate the review process. In this post, we’ll cover the types of code reviews,
the role of static analysis, our top eight Python code review tools, and a checklist to help you
execute your own code reviews.

Types of code reviews

There are several types of code reviews, including manual, unit testing, and linting. Let’s take
a quick look at each one:

Manual reviews

In this type of review, the process is manual, with a review team coordinating the steps from
start to finish. Virtual collaboration tools that allow developers to see and share work can
help streamline manual review tasks.

Unit testing

Unit testing works on the principle that it’s much easier to correct a small portion of code
than a large section of code. Unit testing is built into Python and allows you to analyze code
in the smallest testable chunks. Developers can confirm that code sections work as expected
before merging them with the remainder of the code.
Linting
Linting is a type of code review that uses a linting tool to scan code to uncover potential
bugs. Since linters scan code without running it, they are considered a simple type of static
analysis tool.

How can static analysis tools help your code review?

Static analysis tools do much of the heavy lifting that would normally require careful line-
by-checks during a code review. These quickly grow cumbersome for longer, more complex
projects.

As mentioned above, linters are an example of static analysis tools that serve this purpose.

Top 8 Python code review tools

1. Pylint

An open source that is widely used in the Python community, pylint is highly
configurable so you can customize your pre-commit checks. For instance, you can customize
the confidence level a warning requires to be displayed, or configure pylint to show
suggestions instead of false positive-prone error messages.

2. Snyk Code

Snyk Code is a static analysis tool that uncovers vulnerabilities within code before it goes
into production, ensuring that the code you’re reviewing is secure, and you don’t pass any
security vulnerabilities down the development pipeline.

3. Github

GitHub has a built-in code review tool that performs lightweight code reviews for every pull
request. GitHub includes other features that help with reviews, including diffs, history, and
blame view that give you various insights into the changes a piece of code has undergone.

4. CodeScene

CodeScene uses machine learning to identify areas of poor code health and offers suggestions
for improvement. It differs from other tools in its behavioral analysis component, which gives
insights into how teams of developers collaborate. This helps you understand the factors
contributing to technical debt.

5. Collaborator
Collaborator is a code review tool designed for companies with hefty regulatory
requirements. It features a comprehensive tool for reviews along with detailed reports and
electronic signatures for regulatory compliance.

6. Codacy

Codacy is an automated code review tool that works with Python (among more than 40
programming languages). It is noted for its easy GitHub integration, its sharing features that
establish a single source of truth, and its open source and startup friendly principles.

7. RhodeCode

RhodeCode unifies security and code review across repositories including Git, Subversion,
and Mercurial. Large-scale, global organizations that use multiple repositories can benefit
from its coding and collaboration features. An on-premises version is available by download.
A cloud-hosted instance is available for enterprises.

8. Reviewable

Reviewable is a GitHub tool that gives richer features than what is built into GitHub. These
include a commenting feature that requires all threads to be completed before merging, and a
feature that blocks multiple commits from a single pull request.

Python code review checklist


As we’ve seen, there are a plethora of tools that approach Python code review with different
tactics. Despite the convenience of these tools, none of them are smarter than a competent
code review team. Here are some best practices your team should follow to conduct better
Python code reviews:

1. Verify requirements

2. Code readability

3. Follow pull request protocol

4. Code that meets requirements

5. Testing code security

6. Documentation

1. Verify your requirements


Code reviews don’t exist in a vacuum. Instead, they should start with your project
requirements. Being clear about these can ensure your code addresses a specific problem.

2. Check your code's readability

Modern development is typically a team practice so it’s important to ensure that code is also
easy to read and understand. This helps other developers maintain code in case its author
moves on from the organization. PEP 8 is a widely used Python style guide (written by
authors including Guido himself!) that’s intended to help Python developers write more
readable code.

3. Examine whether the pull request (PR) corresponds to the basic protocol

It's important to follow protocol around pull requests to help teammates work together as they
review code. GitHub has its own recommendations for pull requests, such as including the
purpose of the pull request and specifications about feedback. These serve as a good template
for your own protocol.

4. Make sure your code meets your requirements.

Does your code actually work? Verifying that code meets your requirements is a critical step
in any review. Furthermore, code should be checked to ensure that it will integrate well with
the larger project.

5. Test your code for security

With the arrival of agile development methodologies and a shift left approach to security,
testing should occur early and often within the development process. Developers should also
apply secure coding practices to avoid issues from the start.
6. Documentation

One of the key factors for code quality is maintainability, a subjective quality around how
easy it is for someone other than the author to maintain or update code. To help other
developers understand what code does, it’s important to use documentation. This can include
self-documentation, where the code itself is simple enough to understand on its own, or
docstrings after a definition of a function or class for more complex code.

For more tips, check out our post on code review best practices.

Keep learning:

Python security best practices cheat sheet

Java code review tools

Code Security Audit


Frequently asked questions
Why should you use a code review tool for Python?

Developers love to automate tasks as much as possible, and code review is no different. Code
review tools make it possible to review large-scale projects with dozens of developers. They
allow you to test code without running it, and ensure you can be confident before merging the
pull request.

How is a Python code review done?

A Python code review starts with being clear about the requirements for the code. It then
checks if the requirements are satisfied (ie: the code actually works), along with other
considerations such as readability, security, and documentation. The overall process is
manual but a plethora of tools exist to help development teams as they conduct code reviews.

Why you should implement an


automated code review process
Conducting an automated code review is an essential step in creating a high-
quality, secure application. With the potential for human error during
development, implementing best practices for a systematic code review is a
powerful step toward improving software quality. While a manual review
leverages the expertise and skill of the code review team, the possibility for
security threats designed to avoid human detection within the code still exists.
The benefits of having an expert team review new code for its intent and logic is
invaluable. However, augmenting this manual code review with an automated
one can address publicly disclosed vulnerabilities, as well as vulnerabilities
introduced through custom code and potential security breach points.

What is an automated code review process?

An automated code review process compares source code to a standard set of


guidelines to check for common sources of error or security threats. This
review can produce false positives and negatives, but still improves the
software’s resistance to security threats and overall application performance .
An increased risk of security breaches and suboptimal performance could
compromise the software’s ability to perform as intended. As a result, a
powerful way to improve both the quality and safety of the code is to reduce
false positives and negatives produced by your automated code review tool.

False positive and negatives


Because no automated code checker is perfect, there will always be the
potential for false positives or false negatives during a code review. These terms
are defined below for clarity.
False positive – The analyzer raises a diagnostic flag in the absence of a rule
violation occurring. This action is not detrimental on the surface, but it does
increase the human time it takes to separate false positives from real ones. True
positives are actual errors that the developer needs to fix while false positives
waste the developer’s time.
False negative – The analyzer not raising a diagnostic flag, letting an issue
through during the code review. This type of undetected issue is the specific risk
that an effective automated code review should prevent.

How to reduce false positives and


negatives

One of the most essential parts of a secure code review is to ensure the reviewer
takes the time to understand the code's functionality fully. As a result, one of the
best ways to reduce false positives and negatives during a manual code review
is for the reviewer to take a slow, methodical approach.
Assuming the code functions as intended is a significant source of error when
conducting a code review. The probability of humans — even an expert review
panel — allowing undetected errors through the manual review highlights the
need for an effective automated review process. In addition, a manual review
can guide the programmers in creating standards by which the analyzer can use
to compare the source code with its intended performance .

Employ unit and integration tests


Reducing false positives simplifies the diagnostic report. Reducing false
negatives, however, can:

 Improve the code's security and performance


 Identify unused or bypassed code sections

 Confirm accurate code style

These features are critical aspects of effective software development.


Reducing false negatives accelerates code compiling and run time
while checking that the code functions as it should when compared
with the standard.

It isn't enough to run the analyzer, let it find the errors, and correct
them in the source code. You can require that code changes and pull
requests (PRs) be accompanied by unit and integration tests, which
can improve confidence and reduce errors to improve the entire
process continuously. Employing a unit test ensures the new code
section operates as the developer intended before merging it into the
main code repository. Setting general input conditions or tailoring the
code to deliver a known output are good practices to conduct this type
of testing. After that, adding integration testing in a stepwise fashion
by linking a few units at a time can ensure the interaction is seamless
and will not yield false positives or negatives during an effective code
review.

Use advanced automated scanning tools

The best way to do a code review that minimizes false positives and
negatives is to select a high-quality, robust scanning tool. Using an
automated code reviewer that differentiates when an issue should be
flagged or not is critical to improving the quality and security of the
application.

As critical as it is to conduct a security code review, a sophisticated


automated tool includes a massive amount of vulnerabilities in its
database, often before they’re included in publicly available
databases. An effective automated code review tool rapidly compares
the source code against this data, letting your team fix the errors right
away to deliver secure code sooner.
The automated tool you select must integrate with your existing
development process for ease of use. Achieving seamless integration
ensures the code analyzer will work with your source code, catching
errors and identifying potential security issues throughout the
entire continuous integration and continuous delivery (CI/CD)
process.
Finally, another objective of the automated scanner is to rapidly
compare the code against security and code quality standards. An
advanced scanning tool can even generate a PR, automatically
sending the findings to the review team to continue analyzing the
code or merging the recommendations for reduced issue remediation
time.
//"With the automation that Snyk provides, we have //been able to
divert head count from mundane //manual security work to highly
productive feature //development. Due to Snyk alerting us on new
//vulnerabilities in the form of a Pull Request (that //already include
the “fix”), we have shrunk what would //otherwise be a lengthy
triage->remediate manual //flow to a simple “merge” we can do in
minutes.”
Peter Vanhee - Engineering Practice Lead - Comic Relief

Why you should be using automated code reviews


Manual code reviews are a critical part of software development.
They add several fresh perspectives from experts to identify logic
errors, confirm the code performs its intended function, and provide a
level of accountability for the developer knowing the code will be
checked.
However, while the manual review addresses logic and intent, an
advanced automated code review can help deliver a safer and more
efficient application much faster than manual review alone. With an
automated review, you’ll catch more issues, quicker, improving both
the speed and accuracy of the development process as well.
Automated code review FAQ
How do you automate the code review process?
An automated code review compares source code against a known
standard. An analyzer is adept at finding issues related to things like
style guidelines, standard errors, bugs, or security vulnerabilities. An
automated code review tool integrated into the development process
compares source code against a standard and outputs a report. This
report becomes a pull request that indicates changes the developer
needs to make to the code before it can be merged upstream.
Advanced analysis tools generate a pull request and merge it upstream
to create a secure, accurate, and efficient application.
Visit our Security Resources page to learn about how Snyk can help
developers create high-quality, secure code. You can also try our
free code checker tool to see how the Snyk code engine analyses
your code for security and quality issues.

Python code review checklist


Python code review checklist

As developers, we are all too familiar with code reviews. Having


another pair of eyes take a look at our code can be wonderful; it
shows us so many aspects of our code we would not have noticed
otherwise. A code review can be informative, and it can be
educational. I can confidently attribute most of what I know
about good programming practices to code reviews.

The amount of learning a reviewee takes away from a code review


depends on how well the review is performed. It thus falls on the
reviewer to make their review count by packing the most lessons into
the review as possible.

This is a guide on some vital aspects of the code you should be


checking in your reviews, the expectations you should have from
those checks, and some ideas on how tooling (such as linters,
formatters, and test suites) can help streamline the process.
Code review checklist

We have formulated this guide in the form of a checklist. It lists a set of questions
that you need to ask about the code. If the answer to any of them is not a 'yes', you
should leave a remark on the PR.

Do note that this list is only meant to serve as a guideline. Your codebase, like
every codebase, has its own specific set of needs, so feel free to build upon this
guide and override pieces of it that do not fit well for your use-cases.

Etiquettes

The first and foremost thing to check during a review is how closely the PR
adheres to basic etiquettes. Good PRs are composed of bite-sized changes and
solve a single well-defined problem. They should be focused and purposefully
narrow to have as few merge conflicts as possible. Put simply, a good PR
facilitates being reviewed.

For large-scale swooping changes, make a separate target branch and then make
small incremental PRs to that target, finally merging the target with the main
branch. Making one humongous PR makes it harder to review, and if it goes stale,
many merge conflicts may pop up.

When reviewing PRs from new developers, I also make it a point to ensure their
commit messages are well-written.

Checklist:

 Is the PR atomic?
 Does the PR follow the single concern principle?
 Are the commit messages well-written?

Ideas:
Enforce a commit message format in the team. For example, you
could try gitmoji wherein you use emoji in commit messages. For

example, bugfixes should start with [FIX], or the 🐛 emoji and new

features should start with [FEAT] or the ✨ emoji. This makes the
intention of the commit very clear.

Functionality

and syntax

The next thing to check is whether the PR is effective in that it works.


Code changed by the PR should work as expected. A bug fix should
solve the bug it was supposed to fix. A feature should provide the
additional functionality that was required without breaking something
else.

An important thing to keep in mind is that any new feature added by a


PR is justified. A simple way to ensure this is to accept only the PRs
that are associated with an already triaged issue. This practice
minimizes feature-creep.

Checklist:

 Does the PR work?


 Does the new feature add value or is it a sign of feature-creep?
 Does the PR add test-cases for the modified code?

Ideas:

Having comprehensive tests in the code makes it easier to check that


new functionality works and harder for PRs to break existing stuff.
The portion of the code covered should never go down in a PR. Any
new code should come with complete coverage in unit/functional
tests. Python comes with a robust unit testing framework built into
the language itself. You should make use of it in your codebase.

Design

Once we've established that the code works, the next step is to check
how well it integrates with the existing codebase. One key thing to
inspect in this regard is duplication. Often, code added to a repo
provides functionality that might already be a part of the code in a
different location or something provided by the frameworks or Pip
packages in use. This knowledge is something that one can only gain
by experience. As a senior, it becomes your duty to point such
duplication out to new developers contributing to your repo.

Attention to paradigms is also essential. Many projects have pre-


adopted design paradigms such as microservices, mono repo, or
cloud-nativity. Any incoming code should be in line with these
paradigms.

Checklist:

 Is the code properly planned and designed?


 Will the code work well with the existing code and not increase
duplication?
 Is the code well organised in terms of placement of
components?
Patterns and idioms

Python is a very mature language. It is driven based on certain


philosophies, described as the Zen of Python. Those philosophies
have given birth to many conventions and idioms that new code is
expected to follow.

The difference between idiomatic and non-idiomatic code is very


subtle, and in most cases, can only be intuitively gauged. As with all
things honed by experience, intuition must be transferred from
experienced people, like yourself, to newbies like your reviewees.
Checklist:

 Does the code keep with the idioms and code patterns of the
language?
 Does the code make use of the language features and standard
libraries?

Ideas:

Most linters, popularly PyLint, can help you identify deviations from
the style guides and, in most cases, even automatically fix them.
Linters work incredibly fast and can make corrections to the code in
real-time, making them a valuable addition to your toolchain.

Readability

Python is widely regarded as a very readable language. Python's


simplicity of syntax and reduced usage of punctuation contribute
heavily to its readability. It only makes sense for code written in the
language to be readable as well.

Checklist:

 Is the code clear and concise?


 Does it comply with PEP-8?
 Are all language and project conventions followed?
 Are identifiers given meaningful and style guide-compliant
names?

Ideas:

A good code formatter like Black can help a lot in formatting the
code for consistency and readability. Black also offers minimal
customization, which is good because it eliminates all forms of
bikeshedding.

We've previously talked about integrating Black into your CI


pipeline can work wonders during a code review.
Documentation and maintainability

The next thing to check is the maintainability of the code. Any code
added or changed by the PR should be written to facilitate someone
other than the original author to maintain it.

It should preferably be self-documenting, which means written in a


way that anyone reading the code may be able to understand what it
does. This is one of the hallmarks of good Python code. If the code
has to be complex by design, it should be amply documented. In an
ideal world, all classes and functions would have Python docstrings,
complete with examples.

Checklist:

 Is the code self-documenting or well-documented?


 Is the code free of obfuscation and unnecessary complexity?
 Is the control flow and component relationship clear to understand?

Ideas:

Sphinx is a documentation generator that exports beautiful


documentation from Python docstrings. The exported documentation
can then be uploaded to ReadTheDocs, a popular doc-hosting tool.
Sphinx is one of the main reasons why I absolutely love writing
documentation.

Security

Ensuring that the application remains secure is critical. The next thing
to check is if the PR maintains or improves the security of the project.
You need to ensure that the changes do not increase the attack surface
area or expose vulnerabilities. If the PR adds new dependencies, they
could potentially be unsafe, in which case you might need to check
the version for known exploits and update the dependencies, if
necessary.

Checklist:
 Is the code free of implementation bugs that could be
exploited?
 Have all the new dependencies been audited for
vulnerabilities?

Ideas:

One of the renowned security analyzers for Python is Bandit. Also, if


you use GitHub for hosting code, you should absolutely read this
guide about setting up vulnerability detection and Dependabot for
your codebase.

Once you set up vulnerability detection on GitHub, you'll get


notifications like this...

... with details about the vulnerability and PRs in your repositories
that you can merge to patch them.

We've also recently talked about common security pitfalls in


Python development and how you can secure your projects against
them.
Performance, reliability and scalability

The final things to check are the performance and reliability of the
code at scale. While these are undoubtedly key metrics, I put them on
the bottom of the checklist because I believe well-planned, well-
designed, and well-written code generally works well too.

The ideal code review


Returning to my point about code reviews being educational and informative, I would also
like to add that code reviews are time-consuming and resource-intensive. While each review
takes time, the more in-depth and comprehensive ones consume even more.

So each review must be as productive as possible. This is where all the tooling and
automation efforts should be directed. By automating whatever can be automated, which is
generally the mundane parts of the review, such as code style and formatting, we can allow
devs to focus on the important stuff like architecture, design, and scalability.

I'll leave you with a profound thought my mentor shared with me.

A good code review not only improves the code but the coder as well.

More from DeepSource

VS Code Extension, with LLM-based Autofix

VS Code Extension, with LLM-based Autofix

Perform analysis and resolve issues directly from the convenience of your VS Code environment.

Integrations

Announcements

Product
Introducing, DeepSource Runner

Introducing, DeepSource Runner

Run DeepSource with SaaS convenience and on-premise security

Announcements

Platform Engineering

Get started with DeepSource

DeepSource is free forever for small teams and open-source projects.


Start analyzing your code in less than 2 minutes.

CHOOSE AN ACCOUNT

GitHub

GitLab

Bitbucket

Newsletter

Read product updates, company announcements, how we build


DeepSource, what we think about good code, and more.

Thank you! Your submission has been received!


Oops! Something went wrong while submitting the form.
platform
Platform Overview Pricing
Static Analysis
SAST
Autofix™️
IaC Analysis
Reports
Code Coverage
Self-hosting
IDE
RoadmapChangelog
resources
BlogGlossaryGood Code PodcastGood First IssueSpotlight
State of Code Health
State of Code Health
State of Go
OWASP® Top 10 Whitepaper
company
AboutSecurityTrust Report
Jobs
WE ARE HIRING
Press EnquiriesBrand AssetsTermsPrivacy
support
DocumentationSystem StatusContact SalesCommunity Forum

Python Code Reviews


Style Guide
Developers should follow the PEP8 style guide with type hints. The use of type hints
throughout paired with linting and type hint checking avoids common errors that are tricky to
debug.

Projects should check Python code with automated tools.

Linting should be added to build validation, and both linting and code formatting can be
added to your pre-commit hooks and VS Code.

Code Analysis / Linting


The 2 most popular python linters are Pylint and Flake8. Both check adherence to PEP8 but
vary a bit in what other rules they check. In general Pylint tends to be a bit more stringent and
give more false positives but both are good options for linting python code.

Both Pylint and Flake8 can be configured in VS Code using the VS Code python extension.

Flake8
Flake8 is a simple and fast wrapper around Pyflakes (for detecting coding errors)
and pycodestyle (for pep8).

Install Flake8

pip install flake8

Add an extension for the pydocstyle (for doc strings) tool to flake8.

pip install flake8-docstrings

Add an extension for pep8-naming (for naming conventions in pep8) tool to flake8.

pip install pep8-naming

Run Flake8

flake8 . # lint the whole project


Pylint
Install Pylint

pip install pylint

Run Pylint

pylint src # lint the source directory

Automatic Code Formatting


Black
Blackis an unapologetic code formatting tool. It removes all need from pycodestyle nagging
about formatting, so the team can focus on content vs style. It's not possible to configure
black for your own style needs.

pip install black

Format python code

black [file/folder]

Autopep8
Autopep8 is more lenient and allows more configuration if you want less stringent formatting.

pip install autopep8

Format python code

autopep8 [file/folder] --in-place

yapf
yapf Yet Another Python Formatter is a python formatter from Google based on ideas from
gofmt. This is also more configurable, and a good option for automatic code formatting.

pip install yapf

Format python code

yapf [file/folder] --in-place


VS Code Extensions
Python
The Python language extension is the base extension you should have installed for python
development with VS Code. It enables intellisense, debugging, linting (with the above
linters), testing with pytest or unittest, and code formatting with the formatters mentioned
above.

Pyright
The Pyright extension augments VS Code with static type checking when you use type hints

def add(first_value: int, second_value: int) -> int:


return first_value + second_value

Build validation
To automate linting with flake8 and testing with pytest in Azure Devops you can add the
following snippet to you azure-pipelines.yaml file.

trigger:
branches:
include:
- develop
- master
paths:
include:
- src/*

pool:
vmImage: 'ubuntu-latest'

jobs:
- job: LintAndTest
displayName: Lint and Test

steps:

- checkout: self
lfs: true

- task: UsePythonVersion@0
displayName: 'Set Python version to 3.6'
inputs:
versionSpec: '3.6'

- script: pip3 install --user -r requirements.txt


displayName: 'Install dependencies'

- script: |
# Install Flake8
pip3 install --user flake8
# Install PyTest
pip3 install --user pytest
displayName: 'Install Flake8 and PyTest'

- script: |
python3 -m flake8
displayName: 'Run Flake8 linter'
- script: |
# Run PyTest tester
python3 -m pytest --junitxml=./test-results.xml
displayName: 'Run PyTest Tester'

- task: PublishTestResults@2
displayName: 'Publish PyTest results'
condition: succeededOrFailed()
inputs:
testResultsFiles: '**/test-*.xml'
testRunTitle: 'Publish test results for Python $(python.version)'

To perform a PR validation on GitHub you can use a similar YAML configuration


with GitHub Actions

Pre-commit hooks
Pre-commit hooks allow you to format and lint code locally before submitting the pull
request.

Adding pre-commit hooks for your python repository is easy using the pre-commit package

1. Install pre-commit and add to the requirements.txt


2. pip install pre-commit

3. Add a .pre-commit-config.yaml file in the root of the repository, with the desired pre-
commit actions
4. repos:
5. - repo: https://github.com/ambv/black
6. rev: stable
7. hooks:
8. - id: black
9. language_version: python3.6
10. - repo: https://github.com/pre-commit/pre-commit-hooks
11. rev: v1.2.3
12. hooks:
13. - id: flake8

14. Each individual developer that wants to set up pre-commit hooks can then run
15. pre-commit install

At the next attempted commit any lint failures will block the commit.

Note: Installing pre-commit hooks is voluntary and done by each developer individually.
Thus, it's not a replacement for build validation on the server

Code Review Checklist


In addition to the Code Review Checklist you should also look for these python specific code
review items

 Are all new packages used included in requirements.txt

 Does the code pass all lint checks?

 Do functions use type hints, and are there any type hint errors?
 Is the code readable and using pythonic constructs where?

PYTHON CODE REVIEW CHECKLIST

Code reviews are a crucial part of development. During reviews, developers often
identify issues and inefficiencies that otherwise would've slipped right by the team.
Given how informative a code review can be, it's one of the most crucial aspects of
development, but time is always a factor.

To save time and get the most out of your code review process, always adhere to established
best practices.

Here is our list of Python code review checklist that we consider it should be followed and
not only;

1. Backtrack on Requirements
It's critical that you always confirm the need for a new feature before you begin building it,
but sometimes requirements are overlooked.

Therefore, the best way to kick off a Python code review is by comparing it to the original
scope.

Get to know:

 What problem did you try to solve, and is this the best way to solve it?
 Is implementing this code the only way to solve the problem, or is there a simpler solution?
 Have you missed requirements that may not have been disclosed?
There's always a trade-off, but if you don't solve the problem you set out to solve, you need to
evaluate whether moving forward is a viable option.

You also need to consider if implementing the code is the best way forward. Sometimes
coding a solution is unnecessarily complicated, and the problem could be more easily
resolved by a third-party provider or by addressing the issue from another angle.

Lastly, you should always test the code in multiple scenarios, especially those that haven't
been thought of at first.

This will help you address any bugs or missing features.

Following up with the author of the original requirements is also a good idea to ensure
everything was appropriately interpreted and addressed.
2. Confirm Your Implementation Plan
The next step in your Python code review process is evaluating how well the implementation
fits into your existing system.

Review your plan for implementation and ask:

 Is this being implemented in the right way?


 Is this being implemented in the right place?
 Are there any existing classes or methods that you can reuse?
Think about the approach taken (manual trigger, cron job, job queue) along with where it's
being implemented before you move forward.

Making adjustments to your implementation plan is far easier now than it will be later.

Remember always to follow the golden rule of avoiding duplicate code by looking for
opportunities to reuse what's already there.

3. Examine The Code


Once you've addressed your preliminary questions, it's time to dive into the most
comprehensive phase of the code review process.

During this phase, you want to ask:

 Have your requirements been met with this implementation?


 Have you considered all user experience scenarios?
 Is the user experience acceptable across devices?
 Does the implementation perform reasonably well?
 Does everything have a logical name?
 Have you been sufficiently concise with classes and methods?
 Have you designed a logical hierarchy?
 Have you used constants, config values, and parameters in the right places?
 Are there any unused methods, variables, or constants you can remove?
If you discover problems with any of these checks, you'll need to discuss them with your
team to determine their severity.

For instance, you might move forward even if there are performance issues and plan to make
the code lighter down the road.

On the other hand, if you've left out key user scenarios, like what happens with "no data" or
when someone isn't logged in, those are likely more pressing issues.

Decide what is of the highest priority to address so that you have an efficient plan moving
forward.
4. Prepare for Production
If you've made it to this phase, you're now ready to prepare the code for production by
checking testing, monitoring, and security tools.

Ask:

 Have you tested this implementation sufficiently?


 Have our tests covered all reasonable scenarios?
 Will all errors be adequately logged?
 Will the team get alerts for important errors?
 Are you protected from malicious user input?
 Are you exposing any vulnerabilities?
 Have you encrypted config values, access tokens, and other data correctly?
 What other steps are needed to deploy this implementation?
If your implementation checks all these boxes, you'll probably be able to move forward with
deployment swiftly since most deployment steps tend to be automated.

However, never forget about documentation updates and any notices that you need to send
out to users or partners.

Enlist The Help of Adservio


Enhancing performance, improving resiliency, and moving away from technical debt and
legacy applications is just a small slice of what we do at Adservio.

If you're in the process of reviewing Python code and you need help making sure that it
"checks all of these boxes", our team can take your processes to the next level.

We are quality enablers for your software applications, no matter how complex or coupled
they may be.

Interested in learning more about how Adservio can help your business succeed with its
digital experiences? Contact us today!

Published on

November 30, 2021

Industry insights you won’t delete. Delivered to your inbox


weekly.
Other posts
QUALITY
5 min
Best Tools for Continuous Code Quality and Automated Code
Review
View more
January 5, 2022
.

You might also like