Code Review Assistant for Python Development: A comprehensive prompt template designed to guide developers and teams through systematic code reviews of Python applications. This template ensures thorough evaluation of code quality, security, performance, and maintainability, helping teams maintain high standards in production environments. It includes detailed instructions for reviewers to assess various aspects of code quality while providing clear examples and actionable recommendations.
Purpose and Scope
This prompt template serves as a standardized framework for conducting code reviews in Python projects. It is intended to be used by senior developers, team leads, and quality assurance engineers who need to evaluate code contributions before merging into main branches. The template ensures consistency in review approaches across different teams and projects, promoting best practices that align with industry standards and organizational quality goals. It can be applied to any Python codebase regardless of size or complexity, making it a versatile tool for maintaining code quality.
Key Evaluation Areas
The template focuses on six critical dimensions of code quality:
-
Style and Readability: Ensures code follows PEP 8 guidelines, uses consistent naming conventions, proper indentation, and logical structure. Reviewers check for meaningful variable names, appropriate use of whitespace, line length limitations (maximum 79 characters per line), and adherence to Python idioms. The goal is to make code easily understandable by any developer on the team. Specific checks include:
- Variable naming conventions (snake_case for functions/variables, PascalCase for classes)
- Consistent indentation (4 spaces per level)
- Line length compliance
- Avoidance of magic numbers and strings
- Proper use of whitespace and blank lines
- Logical flow and code organization
- Function and class size limitations (e.g., keeping functions under 50 lines)
- Avoidance of deep nesting and complex control flows
- Proper use of list comprehensions and generator expressions
- Consistent use of exception handling patterns
-
Correctness: Verifies that the code functions as intended under all expected conditions. This includes checking for logical errors, proper handling of edge cases, correct use of conditionals and loops, and appropriate error handling. Reviewers look for issues like mutable default arguments, uninitialized variables, potential race conditions, and off-by-one errors. The goal is to ensure the code behaves correctly in all scenarios and handles unexpected inputs gracefully. Specific checks include:
- Testing edge cases like empty lists, None values, and invalid inputs
- Verifying that all code paths are covered
- Checking for proper exception handling and avoid broad exception catches
- Ensuring that functions return appropriate values in all cases
- Verifying that loops have proper termination conditions
- Validating that data types are used correctly and consistently
-
Security: Identifies potential vulnerabilities that could lead to security breaches. This includes checking for injection risks (SQLi, XSS), unsafe deserialization (pickle, eval on untrusted data), hardcoded credentials, insecure random number generation, and improper input validation. Reviewers ensure that security best practices are followed throughout the codebase, including proper authentication, least privilege principle, and protection against common attacks. Specific checks include:
- Input validation for all user-supplied data
- Proper handling of sensitive data (avoiding logging secrets)
- Secure random number generation for cryptographic operations
- Safe deserialization practices (avoiding pickle for untrusted data)
- Proper authentication and authorization mechanisms
Detailed Review Process
When using this template, reviewers should follow these steps:
-
Start by examining the overall structure of the code to understand its purpose and organization. Look for high-level patterns and identify the main components of the application.
-
Check each function and class for proper documentation, including docstrings that follow Google or NumPy style conventions. Ensure that each function has a clear purpose, documented parameters, and return types.
-
Analyze each section for style compliance, looking for PEP 8 violations and opportunities for improvement. Use automated tools as references but manually review for logical flow and clarity.
-
Verify correctness by testing edge cases and reviewing the logic flow. Consider how the code handles various input scenarios, including empty inputs, None values, and invalid data.
-
Search for security vulnerabilities by examining data flows and input handling. Look for points where untrusted data might be processed without proper validation.
-
Evaluate performance by considering algorithmic complexity and resource usage. Identify potential bottlenecks and areas for optimization.
-
Assess maintainability by looking at code organization and documentation quality. Consider how easy it would be to modify or extend the code in the future.
-
Check compatibility with the specified Python version by identifying any version-specific issues or deprecated features.
Example Review
Here is an example of how the template would be used with actual code:
def process_data(data):
result = []
for item in data:
if item is not None:
result.append(item.upper())
return result
This simple function demonstrates several areas for review:
- The function name
process_datais descriptive but could be more specific about what it does. - The loop uses a for-each approach which is appropriate, but the condition
if item is not Nonecould be simplified toif itemin many cases. - The
upper()method is called on each item, which assumes all items are strings. This could cause issues if non-string items are passed. - The function returns a list, which is appropriate for the operation shown.
Actionable Recommendations
The template requires reviewers to provide specific, actionable recommendations rather than vague feedback. Each issue should be categorized by severity (critical, major, minor, info) and include:
- A clear description of the issue
- The location in the code where it occurs
- The potential impact of the issue
- A concrete suggestion for improvement
- Example code showing the before and after states
Related Resources
This prompt complements the LLM production deployment guidance found in the article: Monitoring and Observability for Production LLM Applications. Effective code review practices support reliable LLM service deployment by ensuring code quality and maintainability.
Usage Instructions
To use this prompt template:
- Replace
code_snippetwith the actual Python code to be reviewed - Specify the
file_pathwhere the code is located - Choose a
review_focus(security, performance, readability, all) - Set the
python_versionto match the project's requirements - Submit the completed prompt to your LLM of choice for review
This template is designed to be flexible while maintaining structure, ensuring comprehensive reviews that address critical quality aspects of Python applications.
Prompt template
You are a senior Python code reviewer with extensive experience in large-scale applications and deep knowledge of PEP 8, security patterns, performance optimization, and maintainability best practices.
Review the following Python code thoroughly with a focus on identifying critical issues that could impact system reliability, security, and long-term maintainability:
File: {{file_path}}
Target Python version: {{python_version}}
Review focus: {{review_focus}}
Code to review:
```python
{{code_snippet}}
```
Please provide a comprehensive review covering:
1. **Style and Readability**: Check compliance with PEP 8 and Python idioms. Identify naming conventions (e.g., snake_case for functions/variables, PascalCase for classes), line length limitations (maximum 79 characters), proper indentation (4 spaces), and consistent formatting. Look for meaningful variable names, avoidance of magic numbers, and adherence to 'flat is better than nested' principle. Use tools like `flake8` or `black` as reference but manually review for logical flow and clarity. Verify docstrings follow Google or NumPy style with clear parameter/return type descriptions.
2. **Correctness**: Look for logical errors including off-by-one mistakes, incorrect conditionals (e.g., `is` vs `==` for None checks), edge case handling, null handling, and potential runtime exceptions. Verify all code paths are covered and exceptions are properly handled. Check for mutable default arguments, uninitialized variables, and unintended side effects from variable assignments.
3. **Security**: Identify vulnerabilities including injection risks, unsafe deserialization, hardcoded secrets, insecure randomness, and improper input validation. Check for secure authentication patterns, least privilege principle, and protection against common attacks. Verify sensitive operations use secure APIs and avoid broad exception catches that mask issues.
4. **Performance**: Spot inefficient algorithms, unnecessary loops, memory issues, and opportunities for optimization. Consider time and space complexity. Check for optimal use of standard library functions versus custom implementations.
5. **Maintainability**: Assess code structure through single responsibility principle, modularity, testability, documentation, and separation of concerns. Ensure comprehensive test coverage and separation of business logic from framework-specific code.
6. **Python Version Compatibility**: Check for features incompatible with Python {{python_version}} and suggest modern alternatives where appropriate.
7. **Actionable Recommendations**: Provide specific, prioritized suggestions with code examples for improvements. Categorize issues by severity (critical, major, minor, info) and include a summary of severity levels (critical, major, minor, info) for each finding.
Format your response with clear sections, bullet points for specific issues, code examples for suggested changes, and a severity-ranked summary at the end.