bizarre Recursive/class interaction

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


Quoth Bob Roberts:
> The following code gives me an assertion error from the line
> assert( not ret.data)
> which means that some how ret.data 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 ret.data 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()
    ['x']
    >>> spam()
    ['x', 'x']

In your code, each instance of MyClass uses the same list as
self.data, 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
create.

Something like this is probably better:

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

(Note that you don't have to set self.data; UserList does that for
you.)

-- 
Steven Taschuk                                                   w_w
staschuk at telusplanet.net                                      ,-= U
                                                               1 1





More information about the Python-list mailing list