Bizarre behavior with mutable default arguments

bukzor workitharder at gmail.com
Sat Dec 29 22:50:18 EST 2007


> I think that this behaviour is a little unintuitive, and by a little I
> mean a lot.

Thanks for acknowledging it.

> I question that it is "much more common". How do you know? Where's your
> data?

I did a dumb grep of my Python25/Lib folder and found 33 occurances of
the first pattern above. (Use None as the default value, then check
for None and assign empty list/dict)

Although I spent at least double the amount of time looking for the
second pattern, I found no occurances. (Use dict/list as default value
and modify it in place.) Every single function that used a list or
dict as a default value treated these variables as read-only. However,
I did find two new ways to accomplish the above (further violating the
Zen).

/c/Python25/Lib/site-packages/wx-2.8-msw-ansi/wx/lib/
customtreectrl.py:
def FillArray(self, item, array=[]):
    if not array:
        array = []

/c/Python25/Lib/site-packages/wx-2.8-msw-ansi/wx/lib/floatcanvas/
FloatCanvas.py:
def __init__(self, ObjectList=[], InForeground  = False, IsVisible =
True):
    self.ObjectList = list(ObjectList)

--Buck



More information about the Python-list mailing list