Claude Python Debugger Prompt

You are a senior Python developer and debugging expert.

Category
💻 Coding
Difficulty
Beginner
Models
4
Last Updated
2026-06-28
💻 Coding Beginner python debugging bug fix error
Works with
📋 Prompt
You are a senior Python developer and debugging expert.

Error message: [error message]
Expected behaviour: [expected behaviour]

BUGGY CODE:
[code causing error]

Task:
1. DIAGNOSIS: What is the exact cause of this error?
2. EXPLANATION: Why does this happen in Python specifically?
3. FIXED CODE: The corrected version with inline comments explaining every change
4. PREVENTION: How to avoid this class of error in future Python code
5. RELATED BUGS: 2–3 similar bugs to check for in the same codebase

Bonus: Provide a defensive version of the fixed code with:
- Input validation
- Proper try/except with specific exception types (not bare except)
- Type hints (Python 3.10+)
- Logging instead of print statements
DIAGNOSIS:
You're getting a TypeError: 'NoneType' object is not subscriptable because get_user_data() is returning None when the user doesn't exist, and the code tries to access the result with [0] without checking if data was actually returned.

Line 7: user_name = get_user_data(user_id)[0]

FIXED CODE:
```python
import logging
from typing import Optional

logger = logging.getLogger(__name__)

def get_user_name(user_id: int) -> Optional[str]:
"""Retrieve username by ID. Returns None if user not found."""
if not isinstance(user_id, int) or user_id <= 0:
raise ValueError(f'Invalid user_id: {user_id}')

try:
user_data = get_user_data(user_id)

if user_data is None: # ← THE FIX: check before subscripting
logger.warning(f'No user found for id={user_id}')
return None

return user_data[0]

except (IndexError, KeyError) as e:
logger.error(f'Failed to parse user data for id={user_id}: {e}')
return None
```

RELATED BUGS TO CHECK:
1. Any other place get_user_data() result is used without None check
2. get_user_data() itself — does it handle database connection errors?
3. Are there similar patterns with other database fetch functions?
🏆
Best model for this prompt
DeepSeek
DeepSeek V3 / R1
💡 Pro Tips
Always check what a function returns on failure — Python functions that return None on error are a common source of NoneType errors
Use isinstance() checks before assuming a variable's type, especially from external data sources
Read the full traceback from bottom to top — the last line is usually the exact line, but the cause is often higher up
Add assert statements during development (remove in production) to catch assumptions early
⚠️ Common Mistakes
Catching bare except: — this catches SystemExit and KeyboardInterrupt and hides real errors
Printing the error instead of logging it — print statements disappear in production
Fixing the symptom without finding the root cause — NoneType errors are usually symptoms of a missing data check upstream
Using mutable default arguments: def func(data=[]) — this is a Python-specific trap that bites almost every developer once
❓ FAQ 🔗 Related Prompts