You know that feeling when you open a Python file you wrote six months ago and think, "Who wrote this mess?" Spoiler: it was you. Legacy code, tangled dependencies, functions that do seventeen things — we've all been there. The good news? AI won't just write code for you; it can also help you clean it up, speed it up, and make it maintainable. In this guide, I'm sharing 15 battle-tested prompts that I use daily to refactor legacy Python, optimize performance, and enforce clean-code principles. Each prompt comes with a real-world scenario and expected output, so you can copy-paste and adapt them immediately.
1. The Code Explainer: "What Does This Function Actually Do?"
Before you can refactor, you need to understand what the code does. This prompt is perfect for untangling that cryptic function your predecessor left behind.
Prompt:
Explain the following Python function in simple terms. Break it down step-by-step, identify the input/output, and list any side effects or potential bugs.
<PASTE CODE>
Example:
You paste a 50-line function that processes CSV files. The AI responds with a clear summary: "This function reads a CSV, filters rows where the 'status' column equals 'active', and returns a list of dictionaries. It also writes a log file. Potential bug: it assumes the 'status' column exists, which may cause a KeyError."
Why it works: It forces the AI to analyze logic, not just syntax, giving you a foundation for refactoring.
2. The Naming Overhaul: "Rename for Clarity"
Vague names like data2 or temp are the enemy of maintainability. This prompt helps you rename variables, functions, and classes for better readability.
Prompt:
Rename all variables, functions, and classes in this Python code to follow PEP 8 naming conventions and be more descriptive. Provide a mapping of old to new names.
<PASTE CODE>
Example:
def calc(a, b): becomes def calculate_area(width, height):. The AI provides a table: a → width, b → height, calc → calculate_area. This makes your code self-documenting.
3. The Function Splitter: "One Function, One Job"
Large functions are hard to test and debug. This prompt splits monolithic functions into smaller, single-responsibility ones.
Prompt:
This function does too many things. Break it into smaller, focused functions. Preserve the original behavior exactly. Provide the refactored code and show how the original function would call these new functions.
<PASTE CODE>
Example:
Your process_data() function reads a file, cleans data, and saves results. The AI splits it into read_file(), clean_data(), and save_results(). Now you can test each part independently.
4. The Type Hint Enforcer: "Add Type Annotations"
Type hints improve readability and catch errors early. This prompt adds them to your code.
Prompt:
Add type hints to this Python code. Use `typing` where necessary (e.g., `List`, `Dict`, `Optional`). Do not change the logic.
<PASTE CODE>
Example:
def get_user(name):
return db.query(name)
becomes
from typing import Optional, Dict
def get_user(name: str) -> Optional[Dict]:
return db.query(name)
5. The Docstring Generator: "Document as You Go"
Good documentation is rare. This prompt generates docstrings for all functions and classes.
Prompt:
Write Google-style docstrings for all functions and classes in this code. Include Args, Returns, and Raises where applicable.
<PASTE CODE>
Example:
The AI adds docstrings like:
def fetch_data(url: str) -> dict:
"""Fetch JSON data from a URL.
Args:
url (str): The endpoint URL.
Returns:
dict: Parsed JSON response.
Raises:
requests.exceptions.RequestException: If the request fails.
"""
6. The Legacy Detangler: "Refactor with Tests"
Refactoring without tests is risky. This prompt suggests a test-first approach.
Prompt:
"Here is legacy Python code. Propose a refactoring plan, and write unit tests for the current behavior first. Then refactor step-by-step, ensuring all tests pass."
Example:
You provide a class with tangled dependencies. The AI suggests extracting methods and mocking external calls. It writes tests using pytest and unittest.mock. This gives you a safety net.
7. The Performance Profiler: "Find Bottlenecks"
This prompt identifies performance issues in your code and suggests optimizations.
Prompt:
"Analyze this Python code for performance bottlenecks. Suggest specific optimizations, such as using generators, list comprehensions, or built-in functions. Provide benchmarks if possible."
Example:
The AI spots a for loop that appends to a list and suggests a list comprehension. It also recommends dict.get() instead of try/except for frequent lookups. The result: code that runs 2x faster.
8. The Loop Optimizer: "Vectorize or List-Comprehend"
Loops are often slow. This prompt converts loops into more efficient forms.
Prompt:
"Replace explicit for-loops with list comprehensions or generator expressions where appropriate. For numerical computations, suggest using NumPy vectorization."
Example:
# Before
squares = []
for i in range(10):
squares.append(i**2)
# After
squares = [i**2 for i in range(10)]
9. The Memory Saver: "Reduce Memory Footprint"
Memory leaks can crash your app. This prompt helps optimize memory usage.
Prompt:
"Review this Python code for memory inefficiencies. Suggest changes like using generators instead of lists, deleting unused objects, or using __slots__ in classes."
Example:
The AI replaces a large list of parsed file contents with a generator that yields one line at a time, cutting memory usage by 80%.
10. The Concurrency Advisor: "Multithread or Async?"
If your code is I/O-bound, this prompt helps you choose between threads and async.
Prompt:
"This code makes many I/O calls. Should I use threading or asyncio? Rewrite the code using the recommended approach. Include error handling."
Example:
For web scraping, the AI suggests asyncio and aiohttp, showing how to use asyncio.gather() to fetch multiple pages concurrently. This cuts runtime from 10 seconds to 1 second.
11. The Dependency Slasher: "Remove Unused Imports"
Unused imports clutter your code. This prompt cleans them up.
Prompt:
"Remove all unused imports from this Python file. Also flag any imports that are used only once and suggest merging them if possible."
Example:
The AI removes import os and import json that were never used — a quick win for readability.
12. The Error Handler: "Add Robust Exception Handling"
Bare except: is a code smell. This prompt improves error handling.
Prompt:
"Improve exception handling in this Python code. Use specific exception types, add else and finally blocks where appropriate, and handle edge cases like empty input or missing files."
Example:
# Before
try:
value = int(input())
except:
pass
# After
try:
value = int(input())
except ValueError:
print("Invalid input")
except KeyboardInterrupt:
raise
except Exception as e:
log.exception(e)
raise
13. The Security Auditor: "Find Vulnerabilities"
Security is non-negotiable. This prompt scans for common issues.
Prompt:
"Audit this Python code for security vulnerabilities: SQL injection, command injection, insecure deserialization, hardcoded secrets. Suggest fixes."
Example:
The AI finds a string-based SQL query and recommends parameterized queries with ? placeholders. It also spots a hardcoded API key and suggests using environment variables.
14. The Style Refactor: "PEP 8 Compliance"
Consistent style makes code easier to read. This prompt enforces PEP 8.
Prompt:
"Refactor this code to be PEP 8 compliant: fix indentation, line length, import order, and naming. Do not change logic."
Example:
The AI adds spaces around operators, breaks long lines, and sorts imports alphabetically.
15. The Full-Stack Refactor: "Modernize with Best Practices"
Finally, this prompt combines everything for a comprehensive overhaul.
Prompt:
"Here is a legacy Python module. Refactor it to follow modern best practices: use dataclasses, type hints, f-strings, pathlib, and context managers. Preserve functionality and add docstrings."
Example:
The AI transforms a class with __init__ setting many attributes into a @dataclass, replaces string concatenation with f-strings, and wraps file operations in with statements. The result is cleaner, safer code.
Putting It All Together
These 15 prompts are your toolkit for turning messy scripts into production-ready code. Start by running the explainer prompt on your worst file, then apply the splitter and type hints. You'll be amazed at the transformation.
Remember, AI is a pair programmer, not a replacement. Always review the changes, run your tests, and understand what the code does. The goal is not just to have clean code, but to learn how to write it yourself.
So, what are you waiting for? Open that legacy file and give it a try. Your future self will thank you.
Comments