July 01, 2023 - Array as default values is bad

Using an empty list [] as default value to a python function is a bad idea

Empty lists [] has some very unplanned side-effects

def some_function(a=[]):
    a.append('x')
    print(a)

some_function()
some_function()
some_function()

When you run this code you would be surprised at the output

>>> some_function()
['x']
>>> some_function()
['x', 'x']
>>> some_function()
['x', 'x', 'x']
>>> some_function()
['x', 'x', 'x', 'x']
>>> 

It is as if there is a hidden function scoped variable that is created statically once and never destroyed. Incidentally pylint pointed this error in my code and thats how I learned about this little “feature” in python.

updatedupdated2023-07-012023-07-01