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

Added argument to raise warnings from factory errors on UnidentifiedImageError #8033

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions Tests/test_image.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,13 @@ def test_open_formats(self) -> None:
assert im.mode == "RGB"
assert im.size == (128, 128)

def test_open_verbose_failure(self) -> None:
im = io.BytesIO(b"")
with pytest.warns(UserWarning):
with pytest.raises(UnidentifiedImageError):
with Image.open(im, warn_possible_formats=True):
Comment on lines +122 to +124
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think these can all be in the same with statement, separated by commas. Though that might make the line too long.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If I do that, and then run black, I get

with pytest.warns(UserWarning), pytest.raises(
    UnidentifiedImageError
), Image.open(im, warn_possible_formats=True):

This does not look clearer to me.

pass

def test_width_height(self) -> None:
im = Image.new("RGB", (1, 2))
assert im.width == 1
Expand Down
13 changes: 9 additions & 4 deletions src/PIL/Image.py
Original file line number Diff line number Diff line change
Expand Up @@ -3251,6 +3251,7 @@ def open(
fp: StrOrBytesPath | IO[bytes],
mode: Literal["r"] = "r",
formats: list[str] | tuple[str, ...] | None = None,
warn_possible_formats: bool = False,
) -> ImageFile.ImageFile:
"""
Opens and identifies the given image file.
Expand All @@ -3272,6 +3273,8 @@ def open(
Pass ``None`` to try all supported formats. You can print the set of
available formats by running ``python3 -m PIL`` or using
the :py:func:`PIL.features.pilinfo` function.
:param warn_possible_formats: If an image cannot be identified, raise warnings
from formats that attempted to read the data.
:returns: An :py:class:`~PIL.Image.Image` object.
:exception FileNotFoundError: If the file cannot be found.
:exception PIL.UnidentifiedImageError: If the image cannot be opened and
Expand Down Expand Up @@ -3318,7 +3321,7 @@ def open(

preinit()

accept_warnings: list[str] = []
warning_messages: list[str] = []

def _open_core(
fp: IO[bytes],
Expand All @@ -3334,16 +3337,18 @@ def _open_core(
factory, accept = OPEN[i]
result = not accept or accept(prefix)
if isinstance(result, str):
accept_warnings.append(result)
warning_messages.append(result)
elif result:
fp.seek(0)
im = factory(fp, filename)
_decompression_bomb_check(im.size)
return im
except (SyntaxError, IndexError, TypeError, struct.error):
except (SyntaxError, IndexError, TypeError, struct.error) as e:
# Leave disabled by default, spams the logs with image
# opening failures that are entirely expected.
# logger.debug("", exc_info=True)
if warn_possible_formats:
warning_messages.append(i + " opening failed. " + str(e))
Comment on lines 3347 to +3351
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
# Leave disabled by default, spams the logs with image
# opening failures that are entirely expected.
# logger.debug("", exc_info=True)
if warn_possible_formats:
warning_messages.append(i + " opening failed. " + str(e))
if warn_possible_formats:
warning_messages.append(i + " opening failed. " + str(e))

The comment is probably no longer relevant with this change.

continue
except BaseException:
if exclusive_fp:
Expand All @@ -3369,7 +3374,7 @@ def _open_core(

if exclusive_fp:
fp.close()
for message in accept_warnings:
for message in warning_messages:
warnings.warn(message)
msg = "cannot identify image file %r" % (filename if filename else fp)
raise UnidentifiedImageError(msg)
Expand Down
Loading