Chapter 3

AI-Assisted Python Development — 10x Speed Methodology

Chapter 3: AI-Assisted Python Development — 10x Speed Methodology

AI coding assistants are powerful enough — but most developers use them wrong. They either dump an entire requirement into the chat and get unrunnable code, or use AI as a slightly smarter search engine. This chapter gives you a proven methodology that genuinely delivers 10x speed: not by letting AI replace your thinking, but by making you and AI work together efficiently.

The Right Approach to AI-Assisted Coding

Why You Can't Let AI Write Everything at Once

The most common beginner mistake is handing the entire requirement to AI: "Write a scraper that pulls product prices from Amazon, saves to a database, and runs daily." AI will generate hundreds of lines — but with fatal flaws:

The Correct Collaboration Flow

Decompose requirements AI generates skeleton You fill business logic AI reviews Test and ship

Step 1 — Decompose. Before talking to AI, clarify for yourself: what does this script do? What are the inputs and outputs? What are the edge cases? Break the big task into small modules.

Step 2 — AI generates the skeleton. Ask AI for a code framework — function signatures, class structure, main flow — without demanding it fill in every detail. Skeleton code is short, readable, and understandable.

Step 3 — You fill the business logic. The parts only you know — your database connection string, your company's special rules, your server's path configuration — you fill in yourself. This is what makes you understand the code and makes the code fit your environment.

Step 4 — AI reviews. Once the code is written, ask AI to audit it: performance bottlenecks, security vulnerabilities, incomplete error handling. This step catches things you won't catch yourself.

Core principle: You are the architect. AI is your senior engineer assistant. You decide what to build and how to organize it. AI helps you implement and optimize the details. Not the other way around.

Prompt Engineering for Python (Professional Level)

Element 1: Provide Context

AI doesn't know your project environment. Always specify: Python version, existing dependencies, target environment (local / cloud server / Docker), and paste relevant existing function signatures or class definitions if you're extending existing code.

Element 2: Require Type Hints and Docstrings

❌ Prompt Without Constraints

Write a function that reads a CSV and returns the top 10 rows by sales amount AI gives you something runnable but without type hints, docstrings, or error handling. Low maintainability.

✅ Professional Prompt With Constraints

Python 3.11, existing dependencies: pandas 2.x.

Write a function that reads a CSV file and returns the top N rows sorted by a sales column descending.

Requirements:

  1. Full type hints for all parameters and return value
  2. Google-style docstring documenting arguments, return type, and exceptions
  3. Exception handling: file not found, column name not found
  4. Explain key design decisions (why nlargest instead of sort_values?) Specifying version and deps, requiring type hints and docstring, listing two key exception cases, and asking for decision explanations. The resulting code quality is dramatically higher.
import pandas as pd
from pathlib import Path

def top_n_by_sales(
    csv_path: str | Path,
    sales_column: str = "sales",
    n: int = 10,
) -> pd.DataFrame:
    """Read a CSV file and return the top N rows by sales value.

    Args:
        csv_path: Path to the CSV file (string or Path object).
        sales_column: Column name to sort by, defaults to "sales".
        n: Number of rows to return, defaults to 10.

    Returns:
        DataFrame of top n rows sorted by sales_column descending.

    Raises:
        FileNotFoundError: If the file path does not exist.
        KeyError: If sales_column is not in the CSV.
    """
    path = Path(csv_path)
    if not path.exists():
        raise FileNotFoundError(f"File not found: {path}")

    df = pd.read_csv(path)

    if sales_column not in df.columns:
        raise KeyError(
            f"Column '{sales_column}' not found. "
            f"Available columns: {list(df.columns)}"
        )

    # Using nlargest instead of sort_values().head():
    # nlargest uses a heap internally — O(n log k) vs full sort O(n log n).
    # Significantly faster when k << n (e.g., top 10 from 1 million rows).
    return df.nlargest(n, sales_column)

Prompt Comparison: Vague vs. Precise

Scenario: Async Web Scraper You need an async scraper that handles anti-bot measures and stores results as dataclasses.

#### ❌ Vague Prompt
Write a web scraper
AI doesn't know sync or async, which library, anti-bot handling, or output format. You'll get a basic requests + for loop that fits no real use case.

#### ✅ Precise Prompt
Python 3.11, using httpx (async) + BeautifulSoup4.

Write an async URL fetcher:

AI-Powered Debugging

The Golden Rules for Debugging Prompts

Rule 1: Paste the complete Traceback. Include every line — the full call stack matters. Many people paste only the last line, losing context about which function the error occurred in.

Rule 2: Provide a minimal reproduction (MRE). Extract the smallest code snippet that reproduces the problem — usually 10-30 lines. Don't paste your entire 500-line file.

Rule 3: State your expected behavior. Tell AI "I expect X but it does Y." Without this, AI only knows something is wrong, not what you're trying to achieve.

Standard Debugging Prompt Template Running a Python script produces an unexpected error.

#### ❌ Ineffective Debugging Prompt
My code has an error, what's wrong?

TypeError: unsupported operand type(s) for +: 'int' and 'str' AI only knows the error type. No idea what line, what the variable values are, or what you were trying to do.

#### ✅ Effective Debugging Prompt
Python 3.11. Running the following code produces an error:

[Minimal Reproduction] def calculate_total(prices: list) -> float: total = 0 for price in prices: total = total + price # error here return total

data = ["12.5", "30.0", "8.75"] # data read from CSV print(calculate_total(data))

[Full Traceback] Traceback (most recent call last): File "main.py", line 9, in print(calculate_total(data)) File "main.py", line 4, in calculate_total total = total + price TypeError: unsupported operand type(s) for +: 'int' and 'str'

[Expected behavior] data contains price strings; I expect calculate_total to return 51.25.

Please explain: 1. Why the error occurs; 2. How to fix it; 3. How to prevent similar issues (type validation best practices). Complete Traceback, minimal reproduction code, data source explanation (read from CSV, hence strings), and expected behavior. AI can give a precise, defensive fix.

Code Review Workflow

✅ Comprehensive Review Prompt

Please review this Python code across these dimensions:

  1. Correctness: Logic bugs? Unhandled edge cases?
  2. Performance: Obvious bottlenecks (repeated computation in loops, N+1 queries)?
  3. Security: Injection vulnerabilities, path traversal, hardcoded credentials?
  4. Maintainability: Functions too long? Naming unclear? Should it be split?
  5. Test coverage: Which edge cases need unit tests? Suggest test cases.

For each issue: describe the problem, cite the specific code location, and give a fix (include improved code if applicable).

[Code to review] ...

✅ Generate Unit Tests Prompt

Generate complete pytest unit tests for the function below.

Requirements:

[Function code] ...

AI Tool Comparison

Tool Core positioning Best for Python automation fit
Cursor AI-native IDE with deep codebase context Large projects; cross-file understanding; refactoring ★★★★★ Understands entire project structure, cross-file edits
GitHub Copilot VSCode/JetBrains plugin, line-level completion Daily coding acceleration; expanding existing codebases ★★★★☆ High completion accuracy, limited context window
Claude Conversational AI, long context, deep reasoning Architecture design; code review; debugging analysis; explaining principles ★★★★★ Best at explaining "why", ideal for learning and complex problems
GPT-4o General multimodal AI, supports image input Screenshot/UI to code; multimodal tasks; quick prototyping ★★★★☆ Fast, great for generating code from screenshots

Recommended stack: Cursor for daily development (IDE-level integration) + Claude for complex problems and reviews. Copilot fits teams deeply invested in the VSCode ecosystem. Don't limit yourself to one tool — different AIs offer complementary perspectives on the same problem.

Case Study: Writing a File Organizer Script in 30 Minutes

A complete AI collaboration record. Goal: automatically sort files in the Downloads folder into subfolders by type (images, documents, videos, archives, etc.).

Round 1: Requirements and Skeleton

✅ Round 1 Prompt

Python 3.11, standard library only (pathlib, shutil).

File organizer script: scan a directory, move files into subfolders based on extension.

Categories:

Round 2: Collision Handling

✅ Round 2 Prompt

Implement the get_destination function.

Collision rule: if report.pdf already exists at the destination, name the new file report_1.pdf; if that exists, report_2.pdf, and so on.

Constraint: don't use an infinite while loop — cap retries at 9999 and raise RuntimeError beyond that.

Round 3: AI Security Review

✅ Round 3 Prompt

Review the complete script for safety and robustness:

  1. Any risk of accidentally deleting or overwriting files?
  2. Cross-platform compatibility issues on Windows/macOS/Linux?
  3. If interrupted mid-run (Ctrl+C), is the file state safe?

AI flagged two key issues: ① shutil.move can fail when moving across device boundaries (different disk partitions) — needs exception handling; ② extension comparison must be lowercased to treat .JPG and .jpg as the same type.

Retrospective: The entire process took 3 rounds of conversation, about 25 minutes. Round 1: skeleton (10 min). Round 2: key implementation details (8 min). Round 3: review and fixes (7 min). Writing the same-quality code from scratch would take at least 2 hours. The key: you controlled the overall structure, AI rapidly implemented and audited the details.

Previous

Next
Chapter 4: Exceptions & Logging
Rate this chapter
4.8  / 5  (74 ratings)

💬 Comments