Apr-26-2024, 12:52 PM
Maybe this makes it more clear.
def incorrect(item, quantity, shopping_list={}): shopping_list[item] = shopping_list.get(item, 0) + quantity return shopping_list # Is needed else there is no way to get the "default" shopping list default_dictionary = {} def whats_happening(item, quantity, shopping_list=default_dictionary): shopping_list[item] = shopping_list.get(item, 0) + quantity return shopping_list # Is needed else there is no way to get the "default" shopping list def correct(item, quantity, shopping_list=None): if shopping_list is None: shopping_list = {} shopping_list[item] = shopping_list.get(item, 0) + quantity return shopping_list # Is needed else there is no way to get the "default" shopping list def test(func): a = func("Shirt", 3) b = func("USB cable", 1) print(func.__name__, a, b, "a is b" if a is b else "a is not b") test(incorrect) test(whats_happening) test(correct)
Output:incorrect {'Shirt': 3, 'USB cable': 1} {'Shirt': 3, 'USB cable': 1} a is b
whats_happening {'Shirt': 3, 'USB cable': 1} {'Shirt': 3, 'USB cable': 1} a is b
correct {'Shirt': 3} {'USB cable': 1} a is not b
Notice that incorrect() and whats_happening() have the same issue. The default dictionary gets reused over and over instead of creating a new dictionary each time. Dictionary a and dictionary b are the same object. Why this happens is easier to see when the dictionary is created explicitly, but explicit or implicit the result is the same. One dictionary is created as the default, and that same dictionary is used every time it is needed. In your example, every dictionary created by calling add_item() without a shopping list returns the same dictionary object.