Cyclic references et C libraries

Martin v. Löwis martin at
Sun Aug 31 03:28:04 CEST 2003

Fabien SK <fabsk+news at> writes:

> One solution would be to wrap the parent objet in a new class
> (forwarding all the calls to the parent object). In the "__del__"
> method of this class, I would clean the list of children object, and
> then remove the reference on the parent objet so its "__del__" method
> will be called. Am I right ?

I would not wrap the parent object, but the file handle. So do

class Handle:
  def __init__(self, *args):
    self.h = lib_open(*args)
  def read_section(self, *args):
    return lib_read_section(self.h, *args)
  def __del__(self):

class Parent:
  def __init__(self, ...):
    # change 
    # self.handle = lib_open(...)
    # to

Then, the Handle class won't participate in a cycle, and it can safely
have an __del__.

> Last question: why does the python file objects not have a "__del__"
> method ? How the file can be closed when the last reference is remove
> ?

If a Python type is implemented in C, it does not need to have an
__del__. Instead, having a tp_del slot in its PyTypeObject C structure
is sufficient.


More information about the Python-list mailing list