bizarre Recursive/class interaction

Steven Taschuk staschuk at
Tue Mar 11 09:31:36 CET 2003

Quoth Bob Roberts:
> The following code gives me an assertion error from the line
> assert( not
> which means that some how is getting set to something besides
> an empty list.  I don't see how this can happen since nothing is
> passed into the construction of ret and defaults to an empty
> list.

This is a common gotcha.  The default value is evaluated only once
(not each time the function is called).  Thus, for example:

    >>> def spam(eggs=[]):
    ...     eggs.append('x') 
    ...     return eggs
    >>> spam()
    >>> spam()
    ['x', 'x']

In your code, each instance of MyClass uses the same list as, so changes to one instance will be reflected in the
others.  Also -- it will be reflected in the default value for new
instances.  Hence the assertion failure on the second list you

Something like this is probably better:

    class MyClass(UserList.UserList):
        def __init__(self, data=None):
            UserList.UserList.__init__(self, data)

(Note that you don't have to set; UserList does that for

Steven Taschuk                                                   w_w
staschuk at                                      ,-= U
                                                               1 1

More information about the Python-list mailing list