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=[]):
    return to

You might expect this to -

my_list = append_to(12)

my_other_list = append_to(42)
give this output -
But, what actually happens is -
[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 = []
    return to

Buh bye!