Loading Python for AI Engineering...
Python uses pass-by-object-reference (or call-by-sharing). Function arguments receive references to existing objects; modifying a mutable object (list, dict, tensor buffer) inside a function mutates the caller’s original state.
“Passing an object in Python is like handing someone the GPS coordinates of your whiteboard. If they write on the whiteboard, everyone looking at that same whiteboard sees the scribbles.”
Defining def generate(prompt: str, history: list = []): ... Every call shares the exact same persistent history list in memory!
from typing import Optional
# BAD: Mutable default argument bug
def append_token(token: str, sequence: list = []):
sequence.append(token)
return sequence
# CORRECT: None sentinel pattern
def append_token_safe(token: str, sequence: Optional[list] = None) -> list:
if sequence is None:
sequence = []
sequence.append(token)
return sequence