[Python-Dev] __del__ and tp_dealloc in the IO lib

Antoine Pitrou solipsis at pitrou.net
Mon Jan 19 00:03:49 CET 2009

Dear python-dev,

The Python implementation of IOBase, the base class for everything IO, has the
(strange) idea to define a __del__ method. It is probably meant to avoid code
duplication, so that users subclassing IOBase automatically get the
close-on-destruct behaviour.

(there is an even stranger test in test_io which involves overriding the __del__
method in a class derived from FileIO...)

However, it has the drawback that all IO objects inherit a __del__ method,
meaning problems when collecting reference cycles (the __del__ may not get
called if caught in a reference cycle, defeating the whole point).

While rewriting the IO stack in C, we have tried to keep this behaviour, but it
seems better to just do it in the tp_dealloc function, and kill the __del__
(actually, we *already* do it in tp_dealloc, because __del__ / tp_del behaviour
for C types is shady). Subclassing IOBase in Python would keep the tp_dealloc
and therefore the close-on-destruct behaviour, without the problems of a __del__

(the implementation has to take a few precautions, first revive the object, then
check its "closed" attribute/property - ignoring errors -, and if "closed" ended
False then call the close() method)

What do you think?


More information about the Python-Dev mailing list