What is Least Astonishment and the Mutable Default Argument in Python?

0
0

“Least Astonishment” is a principle in software design which states that the behavior of a software component should not surprise its users, and should be consistent with their expectations. This means that when designing software, developers should strive to make the software’s behavior as predictable and intuitive as possible.

In Python, one area where the principle of Least Astonishment is sometimes violated is with mutable default arguments. Consider the following function:

def append_to_list(item, my_list=[]):
my_list.append(item)
return my_list

This function appends an item to a list and returns the updated list. If the my_list argument is not provided, the function uses a default value of []. However, because default arguments are evaluated only once, the same mutable list object is reused across multiple calls to the function. This can lead to unexpected behavior:

>>> append_to_list(1)
[1]
>>> append_to_list(2)
[1, 2] # expected [2], but got [1, 2]

In this example, we expect that the second call to append_to_list will return a list containing only the second item, since we didn’t explicitly pass a value for my_list. However, because the same list object is being reused across both calls, the first item is still present in the list on the second call.

To avoid this issue, a common practice in Python is to use immutable objects (such as None) as default arguments, and then create the mutable object inside the function:

def append_to_list(item, my_list=None):
if my_list is None:
my_list = []
my_list.append(item)
return my_list

Now, if my_list is not provided as an argument, a new empty list is created each time the function is called, avoiding the issue with mutable default arguments.

  • You must to post comments
Showing 0 results
Your Answer

Please first to submit.