“Least Astonishment” and the Mutable Default Argument in Python


In Python, the principle of "least astonishment" (also known as the "principle of least surprise") refers to the concept that the behavior of a piece of software should be intuitive and predictable to the user. This means that, when faced with a design decision, the developers of the software should choose the option that is most likely to be expected by the user.

One common application of the principle of least astonishment in Python is in the handling of mutable default arguments. In Python, when a default argument to a function is a mutable object (such as a list or dictionary), any changes to the object made within the function are preserved between calls to the function. For example:

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

print(append_to_list(1))  # [1]
print(append_to_list(2))  # [1, 2]
print(append_to_list(3))  # [1, 2, 3]

In this code, the default value of my_list is an empty list. However, because the default value is a mutable object and the append() method modifies the object in-place, the changes to the list are preserved between calls to the append_to_list() function.

Recommended Course

Python Mega Course: Learn Python in 60 Days, Build 20 Apps
Learn Python on Udemy completely in 60 days or less by building 20 real-world applications from web development to data science.