Python default arguments can be...tricky

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)

give this output -

 [12] [42] 

But, what actually happens is -

[12] [12, 42]

A new list is only created once during the function definition, and the same reference is used for future calls. So...if you use a mutable default argument, it will have the same reference for all the future function calls. Pretty sucky. That's why follow this code pattern

def append_to(element, to=None): 
    if to is None: 
        to = []
        to.append(element) 
    return to

Buh bye!

Published: Jul 23, 2024