Python default arguments can be...tricky
Tue, Jan 5, 2021
One-minute read
Debugging is fun, and according to me debugging time exponentially increases if the code was written in a sloppy manner. Point being…python default arguments can be tricky to deal with. If the code you’ve written is -
def append_to(element, to=[]):
to.append(element)
return to
You might expect this to -
my_list = append_to(12)
print(my_list)
my_other_list = append_to(42)
print(my_other_list)
[12]
[42]
[12]
[12, 42]
def append_to(element, to=None):
if to is None:
to = []
to.append(element)
return to
Buh bye!