Function attributes: a bug?

Tj tj_scarlet at yahoo.com
Sat Mar 29 00:15:44 EST 2003


Hi,

I'm trying to make a closure using the following code.  It returns a
function that can be used to keep adding stuff to a list.

def make_list_accum(init=[]):
    def accum(elem):
        accum.list.append(elem)
        return accum.list
    accum.list = init
    return accum

But there's a bug -- if I generate a function using this, use it for a
while to build up a list, then call make_list_accum() again, it will
want to init itself with the other list by default, sharing it!  This
is surprising behavior, and doesn't happen if I don't use this
optional init form.

Any thoughts?

BTW, I want to send something like this to Paul Graham for his closure
shootout.  Is this better than the normal version which uses objects?

Tj




More information about the Python-list mailing list