
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:
add_badge(badge, badges=None)appendsbadgetobadges(a new list if none was given) and returns that list.count_word(word, counts=None)adds 1 tocounts[word](a new dict if none was given) and returns that dict.
Fix both functions with the None idiom:
add_badge(badge, badges=None)appendsbadgetobadges(a new list if none was given) and returns that list.count_word(word, counts=None)adds 1 tocounts[word](a new dict if none was given) and returns that dict.
main.py Python sleeping
Press Run to try your code, then Check to test it.