12 Prompts for GitHub Copilot: From Commits to Code Review

Introduction

GitHub Copilot has transformed from a niche autocomplete tool into a full-fledged coding partner. As of mid-2026, Copilot powers over 1.8 million paid users (GitHub, 2025) and is embedded in editors from VS Code to JetBrains. But most developers use only 10–20% of its potential — typing vague comments and hoping for the best. This article delivers 12 battle-tested prompts that cover the entire development lifecycle: writing code, generating commit messages, explaining logic, and performing code review. Each prompt is copy-paste ready, with real examples and explanations. Whether you’re a solo developer or part of a team, these prompts will save you hours and improve code quality.

1. Generate a Function from a Natural Language Description

Purpose: Create a specific, production-ready function based on a clear description.

Prompt:

Write a Python function that takes a list of dictionaries representing users (each with "name" and "age") and returns a list of names of users older than 18, sorted alphabetically. Include type hints, a docstring, and a simple error check for empty input.

Example output:

from typing import List, Dict

def get_adult_names(users: List[Dict[str, object]]) -> List[str]:
    """Return sorted names of users older than 18."""
    if not users:
        return []
    adults = [user["name"] for user in users if isinstance(user.get("age"), (int, float)) and user["age"] > 18]
    return sorted(adults)

Explanation: This prompt works because it specifies data structure, edge case (empty list), and style requirements. Copilot sees the constraints and generates robust code.

2. Explain a Complex Code Snippet Line by Line

Purpose: Understand unfamiliar or legacy code quickly.

Prompt:

Explain the following JavaScript code line by line, focusing on what each part does and why it works:

const result = data.filter(item => item.active).map(item => ({ ...item, processed: true })).reduce((acc, item) => acc + item.value, 0);

Example output:
- Line 1: data.filter(item => item.active) — creates a new array containing only items where active is truthy.
- Line 2: .map(item => ({ ...item, processed: true })) — transforms each item by adding a processed property set to true, using spread operator to copy existing properties.
- Line 3: .reduce((acc, item) => acc + item.value, 0) — sums up all value properties, starting from 0.

Explanation: Copilot excels at explaining chained operations. This prompt saves you from reading documentation or tracing through a debugger.

3. Generate a Git Commit Message from Changes

Purpose: Create meaningful, conventional commit messages without mental effort.

Prompt:

Generate a conventional commit message (type: description) for the following diff. Use types like feat, fix, refactor, docs, test. Keep the subject under 50 characters and include a bullet list body:

+ function validateEmail(email) {
+   return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
+ }
- function oldCheck(email) { return email.includes('@'); }

Example output:

feat: add email validation function

- Replaced oldCheck with validateEmail using regex
- Added RFC 5322-compliant pattern

Explanation: Copilot understands conventional commits and adapts to your diff. It even suggests appropriate type prefixes.

4. Refactor a Function for Readability and Performance

Purpose: Improve existing code without changing its behavior.

Prompt:

Refactor this Python function to be more readable and faster. Use list comprehensions, avoid nested loops, and add type hints:

def find_duplicates(items):
    dups = []
    for i in range(len(items)):
        for j in range(i+1, len(items)):
            if items[i] == items[j] and items[i] not in dups:
                dups.append(items[i])
    return dups

Example output:

from typing import List, Hashable

def find_duplicates(items: List[Hashable]) -> List[Hashable]:
    """Return a list of duplicate items using a set for O(n) lookup."""
    seen = set()
    duplicates = set()
    for item in items:
        if item in seen:
            duplicates.add(item)
        else:
            seen.add(item)
    return list(duplicates)

Explanation: Copilot identifies the O(n²) bottleneck and replaces it with an O(n) set-based solution. The prompt guides it to add type hints and comments.

5. Write Unit Tests for an Existing Function

Purpose: Automatically generate test cases covering edge conditions.

Prompt:

Write pytest unit tests for the following function. Include tests for normal cases, edge cases (empty list, None, mixed types), and test names that explain the scenario:

def divide(a: float, b: float) -> float:
    if b == 0:
        raise ValueError("Cannot divide by zero")
    return a / b

Example output:

import pytest

def test_divide_normal():
    assert divide(10, 2) == 5.0

def test_divide_negative():
    assert divide(-6, 3) == -2.0

def test_divide_zero_numerator():
    assert divide(0, 5) == 0.0

def test_divide_by_zero_raises():
    with pytest.raises(ValueError, match="Cannot divide by zero"):
        divide(1, 0)

Explanation: Copilot generates test cases you might overlook (negative, zero numerator). The prompt’s test_ prefix ensures pytest discovery.

6. Generate a Code Review Checklist for a Pull Request

Purpose: Standardize review process and catch common issues.

Prompt:

Create a code review checklist for a Python PR that adds a new REST API endpoint. Include items for security (input validation, SQL injection), performance (N+1 queries), style (PEP 8, naming), and testing (coverage, edge cases).

Example output:
- Security: Are all inputs validated? Is there any raw SQL concatenation? Are authentication tokens checked?
- Performance: Are database queries using indexes? Are there any N+1 SELECTs?
- Style: Does the code follow PEP 8? Are variable names descriptive? Are there any unused imports?
- Testing: Are there tests for success, error, and edge cases? Is the test coverage above 80%?

Explanation: Copilot generates a structured checklist tailored to your stack. You can copy it into your PR template.

7. Perform an Automated Code Review on a Snippet

Purpose: Get an AI reviewer’s suggestions for improvement.

Prompt:

Act as a senior code reviewer. Review this JavaScript function for bugs, performance issues, and style problems. List each issue with severity (critical, major, minor) and a fix suggestion:

function process(items) {
  let total = 0;
  for (var i = 0; i <= items.length; i++) {
    total += items[i].price;
  }
  return total;
}

Example output:
- Critical: Off-by-one error — loop condition i <= items.length should be i < items.length. Causes undefined access on last iteration.
- Major: Using var instead of letvar has function scope, which can lead to bugs in closures.
- Minor: Missing null check — if items is null, it will throw a TypeError.
- Fix: Use let, change condition, add guard clause.

Explanation: Copilot spots the classic off-by-one bug. The prompt’s severity scale helps prioritize fixes.

8. Translate Code from One Language to Another

Purpose: Migrate a small function to a different language or framework.

Prompt:

Translate the following Python function to idiomatic TypeScript with async/await and proper error handling:

def fetch_user(user_id):
    import requests
    response = requests.get(f"https://api.example.com/users/{user_id}")
    if response.status_code != 200:
        raise Exception("Failed to fetch user")
    return response.json()

Example output:

async function fetchUser(userId: string): Promise<User> {
  const response = await fetch(`https://api.example.com/users/${userId}`);
  if (!response.ok) {
    throw new Error(`Failed to fetch user: ${response.statusText}`);
  }
  return response.json() as Promise<User>;
}

Explanation: Copilot adapts to target language idioms — using fetch instead of requests, adding types, and using async/await.

9. Write a Brief Summary of a Codebase Module

Purpose: Quickly understand a new module’s structure and purpose.

Prompt:

Summarize this Python module in 3-4 sentences. List its main classes, their responsibilities, and how they relate:

class UserManager:
    def create_user(self, data): ...
    def find_by_email(self, email): ...

class EmailService:
    def send_welcome(self, user): ...

# main.py uses UserManager and EmailService to register new users

Example output:
This module handles user registration. UserManager manages CRUD operations on user records. EmailService sends welcome emails. The main.py orchestrates both classes to register a user and send a confirmation.

Explanation: Copilot extracts the high-level architecture. Useful for onboarding or documenting a legacy system.

10. Generate a Simple Documentation Comment

Purpose: Add docstrings or JSDoc comments to existing code.

Prompt:

Add a Google-style docstring to this Python function. Include Args, Returns, and Raises sections:

def parse_config(path: str) -> dict:
    with open(path) as f:
        return json.load(f)

Example output:

def parse_config(path: str) -> dict:
    """Parse a JSON configuration file and return its contents.

    Args:
        path: Path to the JSON file.

    Returns:
        A dictionary containing the configuration.

    Raises:
        FileNotFoundError: If the file does not exist.
        json.JSONDecodeError: If the file contains invalid JSON.
    """
    with open(path) as f:
        return json.load(f)

Explanation: Copilot fills in the docstring structure you specified, including error cases you might forget.

11. Suggest an Alternative Implementation with Trade-offs

Purpose: Evaluate different approaches to a problem.

Prompt:

Given this function that filters even numbers, suggest two alternative implementations (one using list comprehension, one using filter()). Compare their readability, performance, and memory usage:

def get_even(numbers):
    result = []
    for n in numbers:
        if n % 2 == 0:
            result.append(n)
    return result

Example output:
- List comprehension: [n for n in numbers if n % 2 == 0] — most readable, same performance as loop, slightly faster in CPython due to internal optimizations.
- filter(): list(filter(lambda n: n % 2 == 0, numbers)) — less readable, but may be faster with large datasets in some interpreters. Memory usage is identical.

Explanation: Copilot explains trade-offs without bias, helping you make informed decisions.

12. Generate a .gitignore or Configuration File

Purpose: Quickly scaffold project config files.

Prompt:

Create a .gitignore file for a Python project that uses Flask, virtualenv, and SQLite. Include common patterns for __pycache__, .env, and database files.

Example output:

__pycache__/
*.pyc
.env
*.db
instance/
venv/
.venv/
*.egg-info/
dist/
build/

Explanation: Copilot knows the standard patterns for your stack. You can adapt the prompt for any framework.

Conclusion

These 12 prompts cover the most common developer tasks — from writing code to reviewing it. The key to getting great results from Copilot is specificity: include constraints, examples, and desired output format. Start by copy-pasting these prompts into your editor, then tweak them for your own projects.

Action step: Pick one prompt from this list and use it in your next commit or PR review. You’ll see immediate time savings and higher code quality. For more advanced workflows, combine prompts (e.g., generate a function, then write tests for it in one session). Happy coding!

← All posts

Comments