Introduction
GitHub Copilot has become an indispensable tool for developers since its launch in June 2022. According to GitHub's own research, developers who use Copilot complete tasks 55% faster, and 75% of surveyed users report feeling more fulfilled in their work (GitHub, 2023). Yet many developers only scratch the surface — using it for autocomplete while writing code. The real power lies in writing precise prompts that guide Copilot to generate commit messages, explain complex logic, refactor legacy code, and even perform code reviews.
In this article, I share 12 practical prompts organized into three skill levels: basic for daily productivity, advanced for deeper code analysis, and expert for architectural and security reviews. Each prompt includes a task description, the exact prompt to use, and a realistic example result. These prompts have been tested with GitHub Copilot in VS Code (version 1.92.0, July 2026) and GitHub Copilot Chat (v0.22.x).
1. Basic Prompts for Daily Development
1.1 Generate a Commit Message from Changes
Task: You've made changes to several files and want a clear, conventional commit message.
Prompt:
Given the following diff, generate a concise commit message following the Conventional Commits format (type: description). The diff is:
[PASTE YOUR DIFF]
Example result (for a diff adding error handling to a login function):
feat(auth): add error handling for login endpoint
- Add try-catch block to login function
- Return 401 for invalid credentials
- Log errors to console for debugging
1.2 Explain a Code Snippet
Task: You encountered a complex piece of code and need a plain-English explanation.
Prompt:
Explain the following code as if I were a beginner developer. Include the purpose of each major section, and highlight any potential pitfalls:
[PASTE CODE]
Example result (for a Python decorator that measures execution time):
This code defines a decorator named `timer`. The decorator wraps a function so that when you call it, it prints how long the function took to run. The `@functools.wraps` line preserves the original function's metadata (name, docstring). A potential pitfall: if the wrapped function is a generator, the timing will only measure the creation of the generator, not its iteration.
1.3 Write Unit Tests for a Function
Task: You have a function and need to cover it with unit tests.
Prompt:
Write pytest unit tests for the following function. Include edge cases such as empty input, None, and large numbers. Use descriptive test function names:
[PASTE FUNCTION]
Example result (for a function that calculates factorial):
def test_factorial_zero():
assert factorial(0) == 1
def test_factorial_positive():
assert factorial(5) == 120
def test_factorial_large():
assert factorial(10) == 3628800
def test_factorial_negative():
with pytest.raises(ValueError):
factorial(-1)
2. Advanced Prompts for Code Analysis and Refactoring
2.1 Refactor a Function to Improve Readability
Task: You have a long, nested function that needs to be broken into smaller parts.
Prompt:
Refactor the following function to improve readability by extracting helper functions. Use descriptive names for each helper. Keep the same external behavior:
[PASTE CODE]
Example result (refactoring a data validation function):
def validate_user_input(data):
errors = []
if not _is_email_valid(data.get('email', '')):
errors.append('Invalid email format')
if not _is_age_valid(data.get('age', -1)):
errors.append('Age must be between 0 and 150')
return errors
def _is_email_valid(email):
return '@' in email and '.' in email
def _is_age_valid(age):
return 0 <= age <= 150
2.2 Identify Code Smells and Suggest Improvements
Task: You suspect a module has design issues and want Copilot to act as a code reviewer.
Prompt:
Analyze this code for common code smells: long method, large class, duplicate code, magic numbers, and poor naming. For each smell found, suggest a specific improvement:
[PASTE CODE]
Example result (for a class with a 200-line method):
- **Long Method**: The `process_order` method is 180 lines. Suggest extracting the payment validation and shipping logic into separate methods.
- **Magic Numbers**: Line 42 uses `0.15` for tax rate. Replace with a named constant `TAX_RATE = 0.15`.
- **Duplicate Code**: The discount calculation appears three times. Extract into a `_calculate_discount` helper.
2.3 Generate Documentation for a Module
Task: You need to document a Python module with docstrings and a README.
Prompt:
Generate Google-style docstrings for each function in this module. Also create a README.md section that explains the module's purpose and how to use it:
[PASTE MODULE CODE]
Example result (for a module with two functions):
def fetch_data(url: str, timeout: int = 10) -> dict:
"""Fetch JSON data from a URL.
Args:
url (str): The endpoint URL.
timeout (int, optional): Request timeout in seconds. Defaults to 10.
Returns:
dict: Parsed JSON response.
Raises:
HTTPError: If the request fails.
"""
3. Expert Prompts for Code Review and Security
3.1 Perform a Security Review of Code
Task: You want to find potential security vulnerabilities before deployment.
Prompt:
Act as a senior security engineer. Review this code for OWASP Top 10 vulnerabilities, particularly SQL injection, XSS, and insecure deserialization. For each vulnerability, explain the risk and provide a fix:
[PASTE CODE]
Example result (for a Flask endpoint with raw SQL):
- **SQL Injection (Critical)**: Line 15 uses f-string to build SQL query. Use parameterized queries instead.
Fix: `cursor.execute("SELECT * FROM users WHERE id = %s", (user_id,))`
- **XSS (High)**: Line 22 renders user input directly in HTML. Use `escape()` or a template engine's auto-escaping.
3.2 Review Code for Performance Bottlenecks
Task: Your application is slow, and you suspect a specific function is the culprit.
Prompt:
Analyze this function for performance issues. Look for unnecessary loops, redundant database calls, and inefficient data structures. Suggest optimized alternatives with time complexity analysis:
[PASTE CODE]
Example result (for a function that filters a list in a loop):
- **Inefficient Loop**: The nested loop results in O(n²) complexity. Replace with a set for O(n).
- **Redundant DB Calls**: The function queries the database inside the loop. Use a single JOIN query instead.
Optimized version:
3.3 Generate a Code Review Checklist
Task: You want a reusable checklist to consistently review pull requests.
Prompt:
Create a code review checklist for a Python web application using Flask and PostgreSQL. Cover: code style, security, performance, error handling, and testing. Format as a table with columns: Category, Check, Example of Good Practice, Example of Bad Practice.
Example result:
| Category | Check | Good Practice | Bad Practice |
|---|---|---|---|
| Security | SQL injection | Use ORM or parameterized queries | String concatenation in SQL |
| Performance | N+1 queries | Use select_related() |
Querying in loop |
| Error handling | Graceful fallbacks | Try-except with logging | Silent failures |
3.4 Convert Code Between Languages
Task: You need to port a JavaScript function to Python.
Prompt:
Convert the following JavaScript function to idiomatic Python 3. Use type hints, list comprehensions where appropriate, and follow PEP 8. Preserve the exact logic:
[PASTE JS CODE]
Example result (for a JS function that maps and filters):
from typing import List
def process_data(items: List[int]) -> List[int]:
return [x * 2 for x in items if x > 0]
3.5 Create a Pull Request Description
Task: You've completed a feature branch and need a clear PR description.
Prompt:
Generate a pull request description based on these changes. Include: summary of changes, motivation, testing steps, and any breaking changes. The branch modifies authentication middleware and adds a rate limiter.
[PASTE SUMMARY OF CHANGES]
Example result:
## Summary
Adds rate limiting to the authentication middleware to prevent brute-force attacks.
## Changes
- Introduced `RateLimiter` class using Redis for distributed rate counting.
- Modified `auth_middleware.py` to check rate limit before validating token.
- Added unit tests for rate limiter with mocked Redis.
## Testing
1. Run `pytest tests/test_rate_limiter.py`.
2. Send 10 rapid requests to `/api/login` — the 11th should return 429.
## Breaking Changes
None.
3.6 Simulate a Code Review Conversation
Task: You want to practice receiving and responding to code review feedback.
Prompt:
Act as a senior developer reviewing my code. For each issue, provide a comment explaining the problem and a suggestion. Then I will respond with my fix. Start with the first issue in this code:
[PASTE CODE]
Example result:
**Comment 1:** The function `calculate_total` modifies the input list `items` by appending a tax line. This is a side effect that callers may not expect. Consider returning a new list instead.
Conclusion
GitHub Copilot is far more than an autocomplete tool. By crafting precise prompts, you can turn it into a junior developer that writes commit messages, a code reviewer that catches security flaws, or a senior engineer that refactors legacy code. The 12 prompts in this article cover a spectrum of tasks — from simple daily needs to deep architectural analysis.
To get the most out of Copilot, treat prompts as you would code: be specific, provide context, and iterate. Start with the basic prompts today, and as you grow comfortable, explore the advanced and expert ones. Your future self — and your codebase — will thank you.
Ready to level up? Try the commit message prompt on your next change, or use the security review prompt before your next deployment. Share your own best prompts in the comments below — the community learns together.
Comments