Problem with garbage collection (sort of)

Frank Millman frank at chagford.com
Mon Aug 18 10:08:39 EDT 2003


Hi all

I am writing a general accounting application. A user can log in to
the application and stay there for a long time, maybe all day, moving
around the menu system, selecting an item to perform a task, then
returning to the menu and selecting another item. I want to ensure
that each item selected cleans itself up correctly when it is
completed. My worry is that if I do not do this, the number of 'dirty'
items will accumulate in memory and will cause performance to suffer.

I have come across a situation where a number of instances created by
an item are not deleted when the item has completed. It took me a long
time to identify what was actually happening, but now that I have
identified it, the 'fix' that I have come up with is rather ugly.
Below is a very artificial example to explain the scenario.

Should I worry about this, or is the performance hit negligible?
Assuming that I should worry about it, can anyone suggest a better
solution? It may be that the problem is caused by bad design, in which
case I may follow this up with more details, to see if anyone can come
up with a better approach.

#------------------------------------------------------
class a:
    def __init__(self,b):
        self.b = b
        print 'a created'
    def __del__(self):
        print 'a deleted'
 
class b:
    def __init__(self):
        self.p = []
        e = a(self)
        self.p.append(e)
        print 'b created'
    def __del__(self):
        print 'b deleted'

class c:
    def __init__(self):
        self.f = b()
        print 'c created'
    def __del__(self):
#       del self.f.p
        print 'c deleted'

y = c()
#del y.f.p

#--------------------------------------------

y is an instance of class c, which creates an instance of class b,
which creates an instance of class a. When y goes out of scope and is
deleted, I want the instances of class b and class a to be deleted as
well.

The problem is that class a keeps a reference to class b (self.b) and
class b keeps a reference to class a (self.p), so the reference counts
do not go down to zero without some additional action.

I have 2 possible solutions - the two commented-out lines. If either
of these lines are uncommented, all instances are deleted.

The ugliness is that p is internal to class b - neither class c nor
the main application requires any knowledge of it. However, my
solution requires one or the other to explicitly delete it.

Any advice will be much appreciated.

Many thanks

Frank Millman




More information about the Python-list mailing list