Default arguments is a helpful feature and there is one situation where they can surprisingly unhelpful. Using a mutable type (like a list or dictionary) as a default argument and then modifying that argument can leads to Strang E results. It's usually best to avoid using mutable default arguments:to see why, try the following code locally.
Consider this function which the adds items to a todo list. Users can provide their own Todo list, or add items to a default list:
def todo_list (new_task, base_list=['wakeup'): base_list.append (new_ Task) return base_list
We can call the function as this:
>>> todo_list ("check the mail") ['wake up ' ' Check the Mail ']
If later on the We call it again:
>>> todo_list ("begin orbital Transfer")
The result is actully:
['wakeup'Check the mail'begin Orbital Transfer']
The list object is a base_list
created once: when the todo_list
function is defined. Lists is mutable objects. This list object was used every time the function is called, it isn ' t redefined each time the function is called. Because todo_list
appends an item to the list, base_list
can get longer each time this is todo_list
called.
[Python] Problem with Default Arguments