Question about garbage collection

Frank Millman frank at chagford.com
Mon Jan 15 08:51:26 EST 2024


Hi all

I have read that one should not have to worry about garbage collection 
in modern versions of Python - it 'just works'.

I don't want to rely on that. My app is a long-running server, with 
multiple clients logging on, doing stuff, and logging off. They can 
create many objects, some of them long-lasting. I want to be sure that 
all objects created are gc'd when the session ends.

I do have several circular references. My experience is that if I do not 
take some action to break the references when closing the session, the 
objects remain alive. Below is a very simple program to illustrate this.

Am I missing something? All comments appreciated.

Frank Millman

==================================================

import gc

class delwatcher:
     # This stores enough information to identify the object being watched.
     # It does not store a reference to the object itself.
     def __init__(self, obj):
         self.id = (obj.type, obj.name, id(obj))
         print('***', *self.id, 'created ***')
     def __del__(self):
         print('***', *self.id, 'deleted ***')

class Parent:
     def __init__(self, name):
         self.type = 'parent'
         self.name = name
         self.children = []
         self._del = delwatcher(self)

class Child:
     def __init__(self, parent, name):
         self.type = 'child'
         self.parent = parent
         self.name = name
         parent.children.append(self)
         self._del = delwatcher(self)

p1 = Parent('P1')
p2 = Parent('P2')

c1_1 = Child(p1, 'C1_1')
c1_2 = Child(p1, 'C1_2')
c2_1 = Child(p2, 'C2_1')
c2_2 = Child(p2, 'C2_2')

input('waiting ...')

# if next 2 lines are included, parent and child can be gc'd
# for ch in p1.children:
#     ch.parent = None

# if next line is included, child can be gc'd, but not parent
# p1.children = None

del c1_1
del p1
gc.collect()

input('wait some more ...')



More information about the Python-list mailing list