Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Do not retry specified formats if they failed when opening #6893

Merged
merged 1 commit into from
Jan 18, 2023

Conversation

radarhere
Copy link
Member

When opening an image, Pillow loop through the different possible formats.

Pillow/src/PIL/Image.py

Lines 3242 to 3244 in 43bb035

def _open_core(fp, filename, prefix, formats):
for i in formats:
i = i.upper()

If I add a print statement to see which formats it checks,

    def _open_core(fp, filename, prefix, formats):
        for i in formats:
            print(i)
            i = i.upper()

and then attempt to open a SPIDER image, while only asking Pillow to check the JPEG format,

from PIL import Image
im = Image.open("Tests/images/hopper.spider", formats=["JPEG"])

it prints

JPEG
JPEG
Traceback (most recent call last):
  File "Tests/test_image.py", line 2, in <module>
    im = Image.open("Tests/images/hopper.spider", formats=["JPEG"])
  File "PIL/Image.py", line 3284, in open
    raise UnidentifiedImageError(msg)
PIL.UnidentifiedImageError: cannot identify image file 'Tests/images/hopper.spider'

JPEG is checked twice.

This is because in the following code, Pillow doesn't recognise that formats is a fixed list, and that calling init() will not increase the number of formats to try.

Pillow/src/PIL/Image.py

Lines 3268 to 3272 in 43bb035

im = _open_core(fp, filename, prefix, formats)
if im is None:
if init():
im = _open_core(fp, filename, prefix, formats)

So this PR changes it to only retry _open_core if formats has not been specified.

    im = _open_core(fp, filename, prefix, formats)

    if im is None and formats is ID:
        if init():
            im = _open_core(fp, filename, prefix, formats)

But wait, you say, you've also skipped calling init(). What if the needed format hasn't been imported before the call to _open_core?

Not to worry. _open_core already automatically calls init() if there is something surprising in formats

Pillow/src/PIL/Image.py

Lines 3242 to 3246 in 43bb035

def _open_core(fp, filename, prefix, formats):
for i in formats:
i = i.upper()
if i not in OPEN:
init()

@radarhere radarhere changed the title Do not retry specified formats if they failed Do not retry specified formats if they failed when opening Jan 14, 2023
@hugovk hugovk merged commit 0b53853 into python-pillow:main Jan 18, 2023
@radarhere radarhere deleted the formats branch January 18, 2023 21:05
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants