Bug hunt

The Sticky Default

Default values are created once, when Python runs the def line. Not on every call! For numbers and text that's fine. But a list or dict default is one shared object that every call reuses.

def add_badge(badge, badges=[]):
    badges.append(badge)
    return badges

print(add_badge("swimmer"))  # ['swimmer']
print(add_badge("climber"))  # ['swimmer', 'climber']  ?!

The fix is a famous Python idiom: default to None, then make a fresh list inside the function.

def add_badge(badge, badges=None):
    if badges is None:
        badges = []
    badges.append(badge)
    return badges

Now each call without a list gets a brand-new one. A caller can still pass in their own list to add to.

The bug report

Ada's badge list shows Pip's badges too. And count_word remembers words from earlier calls.

Assignment

Fix both functions with the None idiom:

  1. add_badge(badge, badges=None) appends badge to badges (a new list if none was given) and returns that list.
  2. count_word(word, counts=None) adds 1 to counts[word] (a new dict if none was given) and returns that dict.