Why the “mutable default argument fix” syntax is so ugly, asks python newbie

This is called the ‘mutable defaults trap’. See: http://www.ferg.org/projects/python_gotchas.html#contents_item_6

Basically, a_list is initialized when the program is first interpreted, not each time you call the function (as you might expect from other languages). So you’re not getting a new list each time you call the function, but you’re reusing the same one.

I guess the answer to the question is that if you want to append something to a list, just do it, don’t create a function to do it.

This:

>>> my_list = []
>>> my_list.append(1)

Is clearer and easier to read than:

>>> my_list = my_append(1)

In the practical case, if you needed this sort of behavior, you would probably create your own class which has methods to manage it’s internal list.

Leave a Comment