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

Brett Cannon brett at python.org
Mon Jan 19 00:19:39 CET 2009


On Sun, Jan 18, 2009 at 15:03, Antoine Pitrou <solipsis at pitrou.net> wrote:
> 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__
> method.
>
> (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?

Fine by me. People should be using the context manager for guaranteed
file closure anyway IMO.

-Brett


More information about the Python-Dev mailing list