862. Fix the agent memory shared between conversations
Why it matters Shared mutable defaults leak one user's messages into another user's agent context. It is a real production bug and a classic Python interview question.
The starter code below runs, but it has a realistic bug. Read the spec, find the bug and fix it. Keep the function name and signature.
add_turn(role, text, history=None) should append {"role": role, "content": text} to the given history list and return that list. When history is not given, it must start a new empty list for that call only, so separate conversations never share messages.
Inputs: role and text are strings. history is a list of message dicts or None.
Return the list of message dicts.
def add_turn(role, text, history=[])Example 1
Input: add_turn('user', 'hi')
Output: [{'role': 'user', 'content': 'hi'}]
Constraints
- Python 3 standard library. Code runs in your browser.
- Your code must pass all 5 tests to be accepted.
Hint 1
Call the function twice with no history. What does the second call return?
Hint 2
Default values are created once.
Hint 3
Use None as the default and build a new list inside.
Common mistakes
- Copying the default list but still mutating it.
- Returning a new list when history is given, so the caller's list is not updated.
- Using a module-level global history.
Understand the idea
Python evaluates default arguments once, when the function is defined. history=[] creates one list that every call without history appends to. The fix is to default to None and create the list inside the function. The second test only passes when each call starts fresh.
Shapes and data flow
Lists of dicts.