#!/usr/bin/python
# -*- coding: iso-8859-1 -*-
import gc
#gc.set_debug(gc.DEBUG_LEAK) # Será necesario ponerlo para rastrear los leaks
# a no ser que invoquemos explicitamente a collect()
#------------------------------------------------------------------------------
class MiList(list):
def __del__(self):
# El método del nos sirve, aparte de para sacar una traza
# para que el objeto sea uncollectable. Sin el __del__
# el recolector es capaz de recolectarlo correctamente.
print "En el __del__"
#------------------------------------------------------------------------------
# Collectable
print "-----> Collectable"
l = MiList()
del l
print "collect:", gc.collect()
print "garbage:", gc.garbage
#------------------------------------------------------------------------------
# Prueba de que con una lista normal no hay problema
# Pero que curioso que el metodo collect() devuelve 1
print "-----> Con una lista"
l2 = []
l2.append(l2)
del l2
print "collect:", gc.collect()
print "garbage:", gc.garbage
#------------------------------------------------------------------------------
# Uncollecable
# He metido dos instancias, para ver como collect() devuelve 2
# Y aparecen ambos en 'garbage'
print "-----> Uncollectable"
l = MiList()
l.append(l)
#l.pop() -> Con solo meter esto se resuelve el ciclo!!!
del l
l3 = MiList()
l3.append(l3)
del l3
#------------------------------------------------------------------------------
# ¿como ver dichos objetos que con Uncollectable?
print "collect:", gc.collect()
print "garbage:", gc.garbage # uncollectable objects ¡¡¡no muestra nada!!!
# A no ser que activemos por ejemplo el flact DEBUG_LEAK
# O hayamos invocado explicitamente a collect() ¡Ojo!
Por cierto... la faq de python tiene pinta de estar muy bien. Me lo anoto como lectura futura.
Un ejemplo:
4.15 Why isn't all memory freed when Python exits?
Objects referenced from the global namespaces of Python modules are not always deallocated when Python exits. This may happen if there are circular references. There are also certain bits of memory that are allocated by the C library that are impossible to free (e.g. a tool like Purify will complain about these). Python is, however, aggressive about cleaning up memory on exit and does try to destroy every single object.
If you want to force Python to delete certain things on deallocation use the sys.exitfunc() hook to run a function that will force those deletions.
2 comentarios:
Nota: El código sale cortado.
No me apetece arreglarlo ahora. Si se hace cut&paste está formateado para un editor de texto.
Autoapunte: mirar referencias débiles ("weakrefs")
Publicar un comentario