Python Code Example and Review
Python Code Example and Review
A key aspect of a Python code review is ensuring code adheres to a style guide like PEP 8. PEP 8, the
official Python style guide, promotes code consistency by offering standardized formatting and
naming conventions.
Why is this important? Code is read far more than it’s written. A consistent style, as enforced by
PEP 8, makes your code clean, organized, and easier to maintain. This translates to smoother
collaboration – team members can easily understand each other’s work.
Code Layout:
• Check if top-level functions and class definitions are surrounded with two blank lines
• Verify if imports are put at the top of the file, just after any module comments and
docstrings, and before module globals and constants
# Wrong:
var_three, var_four)
def long_function_name(
var_four):
print(var_one)
# Correct:
# Aligned with opening delimiter
var_three, var_four)
# Add 4 spaces (an extra level of indentation) to distinguish arguments from the rest
def long_function_name(
var_four):
print(var_one)
foo = long_function_name(
var_one, var_two,
var_three, var_four)
• Check if there’s no extraneous whitespace between a trailing comma and a following close
parenthesis
# Wrong:
# Correct:
Comments:
• Check if inline comments are used sparingly and only when the code itself isn’t clear
• Use docstrings to provide comprehensive explanations for functions, classes, and modules
return a + b
"""
Parameters:
Returns:
"""
return a + b
Naming Conventions:
• Check if module names use lowercase letters and underscores (snake_case). For example,
my_module.py
• Verify if class names use CapWords (also known as CamelCase) convention, where the first
letter of each word is capitalized without underscores. For example, MyClass
• Ensure variable and function names are descriptive and clearly indicate their purpose. For
example, calculate_distance, format_string
• Check if function and variable names use lowercase letters and underscores (snake_case).
For example, my_function, my_variable
• Check if constants use all capital letters with underscores separating words. For example,
MAX_SIZE, PI
• Ensure private variables and functions use a single underscore prefix (_) to indicate that the
variable or function is intended for internal use. For example, _internal_function
• Check if protected variables and functions use a double underscore prefix (__) to indicate
that the variable or function is protected (kind of private, but subclasses can access them).
For example, __protected_variable
• If a variable or function doesn’t have any prefix, it’s considered public. For example,
public_variable, public_function()
a = 30
age_of_customer = 30
Code quality
Code quality in Python development is key to creating reliable, maintainable, and efficient software.
This part of the checklist will help you maintain high Python coding standards.
• Assess the code for its readability: Python’s syntax and design principles advocate for
simplicity and clarity
• Ensure the logic is clear and concise: there should be no overly complex or convoluted
code structures
• Confirm that the code’s structure promotes maintainability with proper use of functions
and classes
• Evaluate adherence to Pythonic idioms and best practices. This includes using list
comprehensions, generator expressions, and context managers effectively
• Review the implementation of Python’s advanced features like decorators and metaclasses
• Examine the use of Python’s dynamic typing and duck typing principles
def filter_numbers():
filtered_numbers = []
if number % 2 == 0:
filtered_numbers.append(number)
return filtered_numbers
def filter_numbers():
return [number for number in numbers if number % 2 == 0 and number > 10]
• Check if Python’s built-in functions and libraries are leveraged to a full extent
• Review the use of Python’s built-in data structures, such as lists, tuples, dictionaries, and
sets, ensuring they are used optimally for their intended purposes
• Check for the effective use of Python’s file handling and I/O operations
word_count = {}
lines = file.readlines()
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
return word_count
# Efficient use of file handling and word counting using Python's built-in functions
# The with statement ensures that the file is properly closed after its suite finishes,
def count_words():
return Counter(file.read().split())
Python-Specific Challenges:
• Evaluate the code for proper handling of Python-specific challenges, such as the Global
Interpreter Lock (GIL) in multi-threaded applications
• Review the handling of dynamic features, such as late binding and runtime type checking
if type(a) is not int or type(b) is not int: # Using 'type' for type checking
raise ValueError("Both arguments must be integers")
return a + b
return a + b
Code functionality
When reviewing code functionality, ask yourself this fundamental question: Does the code do what
it should? Here’s what else to keep in mind.
Intended Purpose:
• Confirm that the code meets desired outcomes and aligns with project specifications while
considering Python’s dynamic and interpreted nature
• Test the code under various scenarios to validate consistent and accurate results, given
Python’s versatility in handling different types of data
• Check if the code leverages Python’s idiomatic features like list comprehensions or
generator expressions for efficient logic implementation
• Assess the code’s ability to handle unexpected scenarios: Python’s dynamic typing and
extensive library support necessitate careful handling of edge cases
• Evaluate responses to unexpected inputs, such as null values or incorrect data types
return a / b
# Correct handling: Includes anticipatory logic for null values and incorrect data types
if a is None or b is None:
if b == 0:
return a / b
• Check how effectively the exception handling mechanism is used to catch and manage
errors
• Review error messages for clarity and helpfulness: Python enables customizable error
messages for informative troubleshooting
• Inspect if Python’s built-in logging module is used to its full potential to facilitate monitoring
and debugging
import math
import logging
def sqrt_less_effective(num):
try:
result = math.sqrt(num)
return result
except Exception:
def sqrt_effective(num):
try:
if num < 0:
except ValueError as e:
return result
Python-Specific Functionalities:
• Evaluate the use of Python decorators for enhancing functionality without modifying the
core logic
• Check for the effective use of Python’s standard library, which offers diverse modules to
simplify complex functionalities
• Assess the integration with Python frameworks or third-party libraries where necessary,
such as requests for HTTP operations or Pandas for data manipulation
• Assess the quality of the unit tests, ensuring they are well-structured, readable, and
maintainable
• Check if there are integration tests to simulate real-world interactions with external systems
like databases or APIs
• Examine the use of mock objects and test fixtures for isolating and testing specific
components or functionalities in Python
Performance
• Examine algorithm choices, ensuring they are optimal for the tasks at hand and consider
Python-specific implications like the Global Interpreter Lock (GIL)
• Check if the code uses Python’s built-in data types and structures, like lists, dictionaries,
and sets, in the most efficient manner
numbers_list = [1, 3, 5, 7, 9, 3]
# Inefficient usage: Using a list where a set would be more appropriate
def check_duplicates_inefficient(numbers_list):
for i in range(len(numbers_list)):
if numbers_list[i] == numbers_list[j]:
return True
return False
def check_duplicates_efficient(numbers_list):
unique_numbers = set(numbers_list)
• Evaluate computational complexity, key in Python to minimize slow execution due to the
language’s interpreted nature
• Identify areas for computational efficiency improvement, such as optimizing loops, list
comprehensions, or leveraging the efficiency of NumPy arrays for numerical data
• Check if redundant processes can be streamlined with Python’s standard library and
optimized third-party packages to replace inefficient custom implementations
list1 = [1, 2, 3, 4, 5]
list2 = [3, 4, 5, 6, 7]
if element in list2:
common_elements.append(element)
return common_elements
Performance Optimization:
• Analyze potential bottlenecks, such as I/O operations, network latency, or inefficient use of
Python’s threading and multiprocessing capabilities
• Confirm the absence of common performance issues, like memory leaks, which can be
particularly tricky in Python due to its garbage collection system, or excessive CPU usage
due to inefficient algorithms
import math
def find_prime_numbers(n):
primes = []
prime = True
if num % i == 0:
prime = False
break
if prime:
primes.append(num)
return primes
def find_prime_numbers(n):
is_primal = [True] * (n + 1)
if is_primal[i]:
j = i*i
while j <= n:
is_primal[j] = False
j += i
• Verify if the codebase utilizes profiling tools like cProfile or line_profiler to identify sections
of code with potential performance bottlenecks
• Determine if the project incorporates performance testing frameworks like PyTest or unittest
to establish performance benchmarks
• Examine the use of JIT compilers like PyPy or optimization tools like Cython for
performance-critical code sections
• Evaluate the use of asynchronous programming with asyncio or other libraries for handling
I/O-bound and high-latency operations efficiently
• Check for the effective use of async/await syntax in Python 3.5+, crucial for writing non-
blocking code and improving the performance of I/O-bound applications
import requests
import asyncio
import aiohttp
def download_file(url):
response = requests.get(url)
f.write(response.content)
def run_download():
url1 = "https://example.com/file1.txt"
url2 = "https://example.com/file2.txt"
download_file(url1)
download_file(url2)
run_download()
if response.status == 200:
filename = f"file_{url.split('/')[-1]}"
url1 = "https://example.com/file1.txt"
url2 = "https://example.com/file2.txt"
asyncio.run(main())
Go and get it
Imagine your Python project taking off – more users, more data, more features. Here’s how to
ensure your code can handle the growth and remain manageable.
• Assess whether the code is segmented into logical units like modules or packages
• Check if modules are loosely coupled and have minimal dependencies between them
• Check if functionalities are broken down into well-defined, reusable functions and classes
• Evaluate the reusability of code components: a wealth of reusable modules and functions
can be found in Python’s standard library
import math
def main():
radius = 5
length = 10
width = 6
if __name__ == "__main__":
main()
def calculate_circle_area(radius):
def main():
radius = 5
circle_area = calculate_circle_area(radius)
length = 10
width = 6
if __name__ == "__main__":
main()
• Review the code’s handling of large datasets, a common requirement in Python apps,
particularly in data science and machine learning
• Analyze the architecture and design patterns for scalability, such as using lazy loading,
generators, or efficient data processing techniques like vectorization with NumPy
• Identify bottlenecks that may impede scaling, such as excessive memory allocations or
inefficient database queries
import numpy as np
data = np.random.rand(1000000)
def process_data_inefficient(data):
total = sum(data)
return mean
def process_data_efficient(data):
np_data = np.array(data)
mean = np.mean(np_data)
return mean
• Assess the use of Python libraries such as Pandas, NumPy, or SciPy in data-heavy
applications for their impact on performance and scalability
This part of our Python code review checklist ensures the code functions as intended across
different environments and dependencies are properly managed. Here are the steps to follow.
• Evaluate the use and integration of external libraries and frameworks, given Python’s rich
ecosystem of third-party packages
• Check for accurate specification and management of dependencies, using tools like pip for
package installation and virtualenv or pipenv for creating isolated environments
• Review the compatibility of library versions with the project’s Python version
Check for deprecated libraries or those with known security vulnerabilities
• Identify potential conflicts among dependencies, a common issue in Python projects due to
multiple packages interacting
• Inspect the code for dependency redundancy: look for multiple packages that offer similar
functionalities
• Examine strategies for resolving dependency conflicts, crucial for Python projects to
maintain stability and functionality
• Check for version pinning of critical dependencies to avoid unexpected breaks due to
package updates
Security Considerations:
• Review the use of protection mechanisms against well-known security vulnerabilities like
SQL injection, cross-site scripting, and insecure direct object references
• Verify if sensitive data like passwords, tokens, or credit card numbers is encrypted in transit
and at rest and if proper access controls are in place
• Ensure all user input is sanitized: validating data types, lengths, and expected formats
• Check how user roles and permissions are managed to ensure only authorized users can
access specific functionalities
• Ensure proper session timeouts and invalidation mechanisms are in place to prevent
unauthorized access
@app.route('/search', methods=['GET'])
def search():
user_query = request.args.get('query')
db_connection = sqlite3.connect('database.db')
cursor = db_connection.cursor()
----------------------------
----------------------------
----------------------------
results = cursor.fetchall()
cursor.close()
db_connection.close()
return str(results)
Version control
Version control is essential for managing and tracking code changes effectively, especially in
collaborative environments. It ensures a clear history of development and is crucial for maintaining
high-quality code.
• Review commit messages for clarity and informativeness: they should succinctly describe
changes, updates to logic, optimizations, or bug fixes
Bad commit messages: “fixed bug”, “updates”, “fixed all errors”, “improved performance”
Good commit messages: “fix: handle null values in user input”, “feat: implement user registration
feature”, “test: add unit tests for login functionality”
• Ensure good version control hygiene is practiced – using descriptive branching strategies
and no large, unfocused commits
• Ensure pull requests are thoroughly reviewed, focusing on code quality, adherence to
project standards, and integration with existing code
• Check if there are overly complex or redundant branches to maintain a clean and
manageable codebase
• Review collaboration processes on code changes: ensure they promote effective teamwork
and are suited to the project’s scale and complexity
• Confirm smooth handling of code integrations and effective resolution of merge conflicts
• Assess the use of Python code review tools and practices, ensuring they are contributing to
maintaining code quality and consistency
While this Python code review checklist empowers you to conduct effective reviews in-house, there
are significant benefits to leveraging independent code review services.
Here is why hiring an external expert to perform an in-depth analysis of your codebase is a sound
idea:
• Fresh Perspective: It’s a known fact that when developers become very familiar with their
own codebase, they can develop a certain “blind spot” and lose sight of the bigger picture.
External reviewers will help identify overlooked mistakes.
• Objective Analysis: External reviewers are not influenced by team dynamics and existing
relationships, so their reviews are more critical and always impartial.
• Deeper Review: Code reviews at Redwerk go beyond just functionality. Our reviewers will
inspect your code for security vulnerabilities, identify performance bottlenecks, and help
you achieve readable and maintainable code.
• Stronger Expertise: External reviewers work on diverse projects, encountering a wide range
of coding styles and potential pitfalls. This multifaceted experience allows them to
recognize patterns that can indicate potential problems, whereas your internal team is
usually more focused on the specific functionalities of your project.
Before we talk about how you can benefit from our services, we’d like to briefly mention the results
of our most recent Python code review.
Complete Network, a US network IT support company, partnered with Redwerk to audit their quote
management app, which is written in Python. We were asked to review the app’s backend API. Our
code reviewers reported 40 critical issues concerning the architecture, performance, and security.
We also shared some easy wins for increasing performance with Django caching and Python
speed-up tools. With our help, Complete Network boosted their code maintainability by 80% and
learned Python code review best practices to avoid future headaches.
Whether you’re prepping your product for a future acquisition or major release, a comprehensive
and unbiased code review can be your safety net. Here is how we can help:
• Project Review: Our static code analysis coupled with automated code review will highlight
areas for improvement in functionality, security, maintainability, and performance.
• Due Diligence: Our code review can be part of a due diligence audit, providing a clear
picture of the code’s quality, potential risks, and long-term maintainability.
• Pre-Deployment Review: Ensure your Python project is ready for launch with our pre-
deployment review. We’ll identify and address any lingering issues to guarantee a smooth
rollout.
• Security Review: We can conduct a targeted Python security code review to scrutinize your
code against industry-standard practices, uncover security vulnerabilities, and carefully
examine external libraries and dependencies.
Have specific areas you’d like us to focus on? Contact us to discuss how we can tailor our review
process to address your unique needs.
Final thoughts
A code review is an investment in the future of your project, saving you time, money, and headaches
down the road. By using the expertise of external reviewers, you gain access to a wider pool of
knowledge and experience. This, combined with their fresh perspective and focus on code review
best practices, will allow you to identify subtle issues and optimization opportunities that your
internal team, fantastic as they are, might miss.