Level Up Your Python Workflow: 12 Battle-Tested Prompts for Code Generation, Refactoring, Testing, and Debugging
Every Python developer knows the drill: you spend hours wrestling with a tricky bug, writing boilerplate, or refactoring spaghetti code. What if you could offload some of that mental load to an AI assistant? Large language models like ChatGPT, Claude, and GitHub Copilot have become indispensable tools for developers. But the quality of their output depends heavily on how you prompt them. A vague request yields vague code; a precise, well-structured prompt can generate production-ready snippets, comprehensive tests, and insightful documentation.
In this guide, we've compiled 12 practical prompts that cover the daily grind of Python development: writing new functions, refactoring legacy code, debugging, testing, optimizing database queries, and even documenting your modules. Each prompt is ready to copy-paste and comes with an example of how to use it. Whether you're a seasoned engineer or just starting out, these prompts will help you code faster and smarter. And if you're looking to deepen your Python skills systematically, consider exploring the Python course on asibiont.com—it's designed to take you from fundamentals to advanced topics with hands-on practice.
Let's dive in.
1. Generate a Python Function from a Docstring
When to use: You know exactly what a function should do, but you'd rather not write the implementation from scratch. Provide a detailed docstring, and let the AI generate the code.
Prompt:
Write a Python function that matches the following docstring. Include type hints and a concise implementation.
"""
Calculate the moving average of a numeric list.
Args:
data (list[float]): Input data points.
window (int): Size of the moving window.
Returns:
list[float]: Moving averages, with length len(data) - window + 1.
Raises:
ValueError: If window is less than 1 or greater than len(data).
"""
Example output:
from typing import List
def moving_average(data: List[float], window: int) -> List[float]:
if window < 1 or window > len(data):
raise ValueError("Window size must be between 1 and the length of data.")
return [sum(data[i:i+window]) / window for i in range(len(data) - window + 1)]
Why it works: The docstring acts as a specification, leaving little room for ambiguity. The AI fills in the implementation while adhering to the contract.
2. Refactor Imperative Code to Pythonic Style
When to use: You have working code that's verbose or uses anti-patterns (like manual indexing). Ask the AI to refactor it using Python's idiomatic features.
Prompt:
Refactor the following Python code to be more Pythonic. Use list comprehensions, built-in functions, and f-strings where appropriate. Keep the same functionality.
```python
result = []
for i in range(len(items)):
if items[i] % 2 == 0:
result.append(items[i] * 2)
**Example output:**
```python
result = [item * 2 for item in items if item % 2 == 0]
Why it works: The prompt specifies the desired style and constraints, guiding the AI to produce cleaner, more maintainable code.
3. Write Unit Tests with Pytest
When to use: You've written a function and need thorough tests. Provide the function and ask for pytest test cases, including edge cases.
Prompt:
Write pytest unit tests for the following function. Cover normal cases, edge cases, and error conditions. Use parametrize where possible.
```python
def divide(a: float, b: float) -> float:
if b == 0:
raise ValueError("Cannot divide by zero")
return a / b
**Example output:**
```python
import pytest
@pytest.mark.parametrize("a, b, expected", [
(10, 2, 5.0),
(-6, 3, -2.0),
(0, 5, 0.0),
])
def test_divide_valid(a, b, expected):
assert divide(a, b) == expected
def test_divide_by_zero():
with pytest.raises(ValueError, match="Cannot divide by zero"):
divide(1, 0)
Why it works: The prompt explicitly requests edge cases and parametrization, resulting in comprehensive test coverage.
4. Debug an Exception with Full Traceback
When to use: You encounter an error and can't quickly identify the cause. Paste the traceback and relevant code.
Prompt:
I'm getting the following error in Python. Explain the root cause and suggest a fix.
Traceback (most recent call last):
File "example.py", line 5, in <module>
print(data['key'])
KeyError: 'key'
Here's the code:
data = {'name': 'Alice'}
print(data['key'])
Example output:
The error occurs because you're trying to access a dictionary key that doesn't exist. Use data.get('key') to return None if the key is missing, or check for key existence with if 'key' in data:.
Why it works: Providing the traceback and code gives the AI full context to diagnose the issue accurately.
5. Optimize a Slow Database Query
When to use: You have a SQL query that's underperforming. Share the query, the schema, and the database engine.
Prompt:
This PostgreSQL query is slow. Suggest optimizations, including indexes and query rewrites.
```sql
SELECT * FROM orders WHERE customer_id = 123 AND order_date > '2026-01-01';
Table orders has columns: id (PK), customer_id (FK), order_date (timestamp), total (numeric). It contains 10 million rows.
**Example output:**
Create a composite index on `(customer_id, order_date)`. Also, avoid `SELECT *` and specify only needed columns. Consider partitioning by `order_date` if queries often filter by date range.
**Why it works:** The prompt includes schema and scale, enabling the AI to propose targeted optimizations.
## 6. Generate Docstrings in Google Style
**When to use:** You have undocumented functions and want to adhere to a docstring convention.
**Prompt:**
Add Google-style docstrings to the following Python functions. Include Args, Returns, and Raises sections.
def fetch_user(user_id: int) -> dict:
# implementation
pass
**Example output:**
```python
def fetch_user(user_id: int) -> dict:
"""Fetch a user by ID.
Args:
user_id (int): The unique identifier of the user.
Returns:
dict: A dictionary containing user data.
Raises:
UserNotFoundError: If no user exists with the given ID.
"""
Why it works: The prompt specifies the docstring style, ensuring consistency across your codebase.
7. Convert a Script to a CLI with argparse
When to use: You have a standalone script and want to make it command-line friendly.
Prompt:
Convert the following Python script into a CLI tool using argparse. Add arguments for input file and output file, with sensible defaults.
```python
import json
def process(input_path, output_path):
with open(input_path) as f:
data = json.load(f)
# ... processing ...
with open(output_path, 'w') as f:
json.dump(data, f)
process('input.json', 'output.json')
**Example output:**
```python
import argparse
import json
def process(input_path, output_path):
with open(input_path) as f:
data = json.load(f)
# ... processing ...
with open(output_path, 'w') as f:
json.dump(data, f)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Process JSON data.')
parser.add_argument('--input', default='input.json', help='Input file path')
parser.add_argument('--output', default='output.json', help='Output file path')
args = parser.parse_args()
process(args.input, args.output)
Why it works: The prompt clearly states the desired CLI arguments and defaults.
8. Explain Complex Code Line by Line
When to use: You inherit a cryptic piece of code and need to understand it quickly.
Prompt:
Explain the following Python code line by line. Assume I'm an intermediate Python developer.
```python
from functools import lru_cache
@lru_cache(maxsize=None)
def fib(n):
return n if n < 2 else fib(n-1) + fib(n-2)
**Example output:**
- `from functools import lru_cache`: Imports the `lru_cache` decorator, which caches function results.
- `@lru_cache(maxsize=None)`: Decorates `fib` to cache all return values (no size limit).
- `def fib(n):`: Defines a recursive Fibonacci function.
- `return n if n < 2 else fib(n-1) + fib(n-2)`: Base case: if n is 0 or 1, return n; otherwise, return the sum of the two previous Fibonacci numbers.
**Why it works:** The prompt sets the audience level, ensuring the explanation is neither too basic nor too advanced.
## 9. Write a Regex Pattern with Explanation
**When to use:** You need a regular expression but struggle with the syntax. Describe the pattern in plain English.
**Prompt:**
Write a Python regex that matches email addresses. Explain each part of the pattern.
**Example output:**
```python
import re
pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
^and$anchor the start and end.[a-zA-Z0-9._%+-]+matches the local part (letters, digits, dots, underscores, percent, plus, hyphen).@matches the literal '@'.[a-zA-Z0-9.-]+matches the domain name.\.[a-zA-Z]{2,}matches the top-level domain (at least two letters).
Why it works: The prompt requests both the pattern and an explanation, aiding understanding.
10. Refactor to Use Dataclasses
When to use: You have classes with repetitive __init__ methods and want to modernize them.
Prompt:
Refactor the following class to use Python's dataclasses module.
```python
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
**Example output:**
```python
from dataclasses import dataclass
@dataclass
class Point:
x: float
y: float
Why it works: The prompt is straightforward and leverages a specific Python feature.
11. Generate Type Hints for Untyped Code
When to use: You have legacy code without type hints and want to add them for better static analysis.
Prompt:
Add type hints to the following Python function. Use the typing module if necessary.
```python
def greet(name, times):
for _ in range(times):
print(f"Hello, {name}!")
**Example output:**
```python
from typing import NoReturn
def greet(name: str, times: int) -> None:
for _ in range(times):
print(f"Hello, {name}!")
Why it works: The prompt specifies the use of typing, ensuring correct annotations.
12. Create a Dockerfile for a Python Application
When to use: You need to containerize a Python app but aren't sure about best practices.
Prompt:
Write a Dockerfile for a Python 3.11 application that uses pip and has a requirements.txt. Optimize for small image size and caching.
Example output:
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
CMD ["python", "app.py"]
Why it works: The prompt mentions specific optimizations, leading to a production-ready Dockerfile.
Mastering these prompts can significantly reduce the time you spend on routine coding tasks, allowing you to focus on architecture and problem-solving. Remember, the key is to be specific: include context, constraints, and desired outcomes. As you experiment, you'll develop a intuition for what works best with your AI assistant. If you're eager to strengthen your Python foundations and learn more advanced techniques, check out the comprehensive Python course on asibiont.com. It covers everything from syntax to design patterns, with practical exercises that reinforce each concept. Happy coding!
Comments