¿La excepción ocurre de forma un poco aleatoria?
En la documentación oficial de Python puedes leer los siguientes extractos:
Note: del x
doesn’t directly call x.__del__()
— the former decrements the reference count for x
by one, and the latter is only called when x
‘s reference count reaches zero. Some common situations that may prevent the reference count of an object from going to zero include: circular references between objects (e.g., a doubly-linked list or a tree data structure with parent and child pointers); a reference to the object on the stack frame of a function that caught an exception (the traceback stored in sys.exc_info()
keeps the stack frame alive); or a reference to the object on the stack frame that raised an unhandled exception in interactive mode (the traceback stored in sys.last_traceback
keeps the stack frame alive). The first situation can only be remedied by explicitly breaking the cycles; the second can be resolved by freeing the reference to the traceback object when it is no longer useful, and the third can be resolved by storing None in sys.last_traceback
. Circular references which are garbage are detected and cleaned up when the cyclic garbage collector is enabled (it’s on by default). Refer to the documentation for the gc
module for more information about this topic.
Mira lo que está en negrita y cursiva en el siguiente extracto:
Warning: Due to the precarious circumstances under which __del__()
methods are invoked, exceptions that occur during their execution are ignored, and a warning is printed to sys.stderr
instead. Also, when __del__()
is invoked in response to a module being deleted (e.g., when execution of the program is done), other globals referenced by the __del__()
method may already have been deleted or in the process of being torn down (e.g. the import machinery shutting down). For this reason, __del__()
methods should do the absolute minimum needed to maintain external invariants. Starting with version 1.5, Python guarantees that globals whose name begins with a single underscore are deleted from their module before other globals are deleted; if no other references to such globals exist, this may help in assuring that imported modules are still available at the time when the __del__()
method is called.
En general, __del__
no se debería usar ya que el recolector de basura se encarga de ir eliminando lo que no es necesario. Si se decide usar __del__
debería usarse para que haga lo mínimo.
Respecto a porqué sale el error/warning, cuando heredas de P
ya estás heredando su método __del__
, ¿por qué sobreescribirlo? Solo tiene sentido si, además, quieres que el método haga alguna cosa extra. Por otra parte, el método __del__
de la clase P
, usado tal como lo usas, solo acepta instancias de la clase P
pero self
ahí es una instancia de la clase C
. De ahí el error/warning. Y como ocurre dentro del método __del__
es ignorado.