FAQ Index - Search - Recent Changes - Everything - Add entry

<< Previous Entry | FAQ Entry 8.4 | Next Entry >>

8.4. Is there a resource leak? Why do I run out of memory using Pixbuf?

The answer is "Interesting GC behaviour" in Python. Apparently finalizers are not necessarily called as soon as an object goes out of scope. My guess is that the python memory manager doesn't directly know about the storage allocated for the image buffer (since it's allocated by the gdk) and that it therefore doesn't know how fast memory is being consumed. The solution is to call gc.collect() at some appropriate place.

For example, I had some code that looked like this:

  for image_path in images:
     pb = gtk.gdk.pixbuf_new_from_file(image_path)
     pb = pb.scale_simple(thumb_width, thumb_height, gtk.gdk.INTERP_BILINEAR)
     thumb_list_model.set_value(thumb_list_model.append(None), 0, pb)
This chewed up an unacceptably large amount of memory for any reasonable image set. Changing the code to look like this fixed the problem:

  import gc

  for image_path in images:
     pb = gtk.gdk.pixbuf_new_from_file(image_path)
     pb = pb.scale_simple(thumb_width, thumb_height, gtk.gdk.INTERP_BILINEAR)
     thumb_list_model.set_value(thumb_list_model.append(None), 0, pb)
     del pb
     gc.collect()

PyGTK FAQ Wizard | PyGTK Homepage | Feedback to faq at pygtk.org