-
-
Notifications
You must be signed in to change notification settings - Fork 2.4k
Description
This is a similar issue to #477, but the context is a bit different. Executing this code with python -Wall will generate a ResourceWarning (can be reproduced with an arbitrary image):
from PIL import Image
with Image.open('test_img.png') as img:
img.save('test_img.jpg', format='JPEG', quality=80)This code will not produce a warning:
from PIL import Image
with open('test_img.png', 'rb') as image_file:
with Image.open(image_file) as img:
img.save('test_img.jpg', format='JPEG', quality=80)I've spent a few hours debugging this, and I think I've nailed it down. Apologies if I've misunderstood something.
The warning is caused by the line PIL/Image.py:762, when the file object was opened by Image.open:
return self.im.pixel_access(self.readonly)Looking at he C bindings in _imaging.c:2799 I can see that because the return value of the call above is discarded, the line _imaging.c:2824 gets executed
PyObject_Del(self);which will destroy the file object without closing it, thus generating a ResourceWarning: unclosed file... error.
To verify this, I've added a line to close the file before returning from the load method:
self.fp.close()
return self.im.pixel_access(self.readonly)With this, no ResourceWarning was generated.
Tested with Pillow v2.5.1 and Python 3.3.2.