Search code examples
pythonmemory-managementpython-imaging-library

is this a possible memory leak issue for updating python PIL image data to a variable?


saving data from PIL.Image.open("image.png") into a variable doesnt update the variable data but instead creates a new instance of the image data and just reassigns where the variable is pointing to in memory, this can cause memory problems by creating hundreds of image files that cant be closed as the variable is no longer pointing to it in memory and can lead to performance issues

for x in range(0,100):
  var = PIL.Image.open("cat.png")              #1
  var = PIL.ImageTk.PhotoImage(var)            #2
  print(var)

this is a short example of what was happening when the code was running after it loops once the variable data for var was updated but the image file wasnt closed and couldnt be closed as var had been updated it requires it to run using the code

with PIL.Image.open("cat.png") as var: 

any code containing a loop thats not running using this will cause potential memory problems but most noticeably lag

i was wondering if its an issue with PIL not closing files when the variable location and information for the file is updated and how does the PIL memory storing system fully work?


Solution

  • PIL closes the handle and releases associated resources when the object is garbage collected, just as you would expect it to. There's no danger of a memory leak.

    Also, the Image.open() does not actually read anything into memory - image data is lazy-loaded as needed - in this case under the PhotoImage() call. Image.open() only creates the Image object and associates a file location with it.

    https://omz-software.com/pythonista/docs/ios/Image.html

    Image objects are closable, so you can close them if you like, but it's not necessary. Cleanup will occur when they are collected.