Mutable default argument
add_tag() should return a fresh tag list for each post unless one is passed in. Why do tags from one post show up on another?
def add_tag(tag: str, tags: list[str] = []) -> list[str]: """Append a tag and return the list of tags.""" if tag not in tags: tags.append(tag) return tags first = add_tag("python") # ["python"]second = add_tag("sql") # expected ["sql"]Show answer
line 1 · Wrong API usage
Default values are evaluated once, when the function is defined, so every call without tags shares the same list. second comes back as ["python", "sql"], and the list keeps growing for the life of the process.
def add_tag(tag: str, tags: list[str] | None = None) -> list[str]: tags = [] if tags is None else tagsInterview follow-up: Interviewers often ask why None is the conventional sentinel and whether the same trap applies to dicts and sets (it does).