Skip to content

Image.close() should not close an externally provided file pointer (when exclusive_fp is False) #5309

@andreymal

Description

@andreymal

When using context manager, Image does not close file pointer, as expected. It checks getattr(self, "_exclusive_fp", False) and closes the file pointer only if it's True.

with open("file.png", "rb") as fp:
    assert fp.closed is False
    with Image.open(fp) as im:
        ...
    assert fp.closed is False  # OK

But the Image.close() method misses _exclusive_fp check and closes the file pointer unexpectedly:

with open("test.png", "rb") as fp:
    assert fp.closed is False
    im = Image.open(fp)
    ...
    im.close()
    assert fp.closed is False  # AssertionError

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions