Debug Detective
Paste an error and surrounding code, get a diagnosis, root cause, and fix.
Prompt
Diagnose the following error and provide a fix.
Language/Framework: [LANGUAGE/FRAMEWORK]
Error message:
[PASTE ERROR OR STACK TRACE]
Relevant code:
[PASTE CODE]
What I expected to happen:
[DESCRIBE EXPECTED BEHAVIOR]
Provide:
1. Diagnosis: What is happening and why
2. Root Cause: The underlying issue (not just the symptom)
3. Fix: Corrected code
4. Prevention: How to avoid this class of error in the future
Example
Input:
Language/Framework: Python / SQLAlchemy
Error message:
sqlalchemy.orm.exc.DetachedInstanceError: Instance <User at 0x...>
is not bound to a Session
Relevant code:
def get_user(user_id):
with Session() as session:
user = session.query(User).get(user_id)
return user.name # error here
What I expected: Return the user's name
Output:
Diagnosis: You're accessing user.name after the session is closed.
SQLAlchemy objects are bound to their session -- once the session
closes, accessing unloaded attributes triggers DetachedInstanceError.
Root Cause: The `with` block closes the session before `.name` is
accessed. The `name` attribute wasn't eagerly loaded.
Fix:
def get_user(user_id):
with Session() as session:
user = session.query(User).get(user_id)
return user.name # access within session
Prevention: Either access all needed attributes within the session,
or use eager loading (joinedload/subqueryload) for attributes you
need after the session closes.
Read other prompts