Question about garbage collection

Chris Angelico rosuav at gmail.com
Mon Jan 15 21:57:08 EST 2024


On Tue, 16 Jan 2024 at 13:49, Akkana Peck via Python-list
<python-list at python.org> wrote:
>
> I wrote:
> > > Also be warned that some modules (particularly if they're based on libraries not written in Python) might not garbage collect, so you may need to use other methods of cleaning up after those objects.
>
> Chris Angelico writes:
> > Got any examples of that?
>
> The big one for me was gdk-pixbuf, part of GTK. When you do something like gtk.gdk.pixbuf_new_from_file(), there's a Python object that gets created, but there's also the underlying C code that allocates memory for the pixbuf. When the object went out of scope, the Python object was automatically garbage collected, but the pixbuf data leaked. Calling gc.collect() caused the pixbuf data to be garbage collected too.
>
> There used to be a post explaining this on the pygtk mailing list: the link was
> http://www.daa.com.au/pipermail/pygtk/2003-December/006499.html
> but that page is gone now and I can't seem to find any other archives of that list (it's not on archive.org either). And this was from GTK2; I never checked whether the extra gc.collect() is still necessary in GTK3, but I figure leaving it in doesn't hurt anything. I use pixbufs in a tiled map application, so there are a lot of small pixbufs being repeatedly read and then deallocated.
>

Okay, so to clarify: the Python object will always be garbage
collected correctly, but a buggy third-party module might have
*external* resources (in that case, the pixbuf) that aren't properly
released. Either that, or there is a reference loop, which doesn't
necessarily mean you NEED to call gc.collect(), but it can help if you
want to get rid of them more promptly. (Python will detect such loops
at some point, but not always immediately.) But these are bugs in the
module, particularly the first case, and should be considered as such.
2003 is fully two decades ago now, and I would not expect that a
serious bug like that has been copied into PyGObject (the newer way of
using GTK from Python).

So, Python's garbage collection CAN be assumed to "just work", unless
you find evidence to the contrary.

ChrisA


More information about the Python-list mailing list