problem calling functions with default arguments

Russell E. Owen owen at astro.washington.edu
Wed Aug 15 18:08:55 EDT 2001


In article <3B7AC3B9.D6FB66 at wohnheim.fh-wedel.de>,
 Dietmar Lang <dietmar at wohnheim.fh-wedel.de> wrote:

>...
>It has to do with the fact that we have just one list object here: The
>one created when atest() was first executed. It seems that Python
>doesn't create a new list every time, so it keeps growing with each
>append.
>
>You can though, move the default value into the function body. For
>example:
>
>def atest(alist = None):
>    if alist is None:
>        alist = []
>    print 'alist =', alist
>    alist.append('test')
>
>Now it should work. Thanks to my O'Reilly book for pointing that one out
>on me before I had to come face to face with it. :-)
>
>Kudos, Dietmar

Thank you very much. I can certainly see it if the default argument was 
a named variable pointing to the desired default list (since Python 
doesn't have the equivalent of C's "const"), but I didn't expect it for 
a constant such as [] or {}. Anyway, your fix works and all is well.

I did look in the FAQs before posting, but if it's there, I managed to 
miss it.

Regards,

-- Russell



More information about the Python-list mailing list