Skip to content

Commit 606c422

Browse files
committed
Use sets
1 parent a024016 commit 606c422

2 files changed

Lines changed: 20 additions & 9 deletions

File tree

Tests/test_image.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -128,8 +128,11 @@ def test_open_formats(self) -> None:
128128
assert im.mode == "RGB"
129129
assert im.size == (128, 128)
130130

131-
@pytest.mark.parametrize("formats", (("!PNG",), ("PNG", "!PNG")))
131+
@pytest.mark.parametrize("formats", (("!PNG",), ("PNG", "!PNG"), ("JPEG", "!PNG")))
132132
def test_open_formats_exclude(self, formats: tuple[str]) -> None:
133+
with Image.open("Tests/images/hopper.jpg", formats=formats):
134+
pass
135+
133136
with pytest.raises(UnidentifiedImageError):
134137
with Image.open("Tests/images/hopper.png", formats=formats):
135138
pass

src/PIL/Image.py

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3632,8 +3632,16 @@ def open(
36323632
if not isinstance(formats, (list, tuple)):
36333633
msg = "formats must be a list or tuple" # type: ignore[unreachable]
36343634
raise TypeError(msg)
3635-
formats = tuple(format.upper() for format in formats)
3636-
exclude = all(format.startswith("!") for format in formats)
3635+
3636+
allowed = set()
3637+
excluded = set()
3638+
for f in formats:
3639+
f = f.upper()
3640+
if f.startswith("!"):
3641+
excluded.add(f[1:])
3642+
else:
3643+
allowed.add(f)
3644+
allowed -= excluded
36373645

36383646
exclusive_fp = False
36393647
filename: str | bytes = ""
@@ -3666,13 +3674,13 @@ def _open_core(
36663674
prefix: bytes,
36673675
check_formats: list[str],
36683676
) -> ImageFile.ImageFile | None:
3677+
if formats is not None:
3678+
if allowed:
3679+
check_formats = [f for f in check_formats if f in allowed]
3680+
else:
3681+
check_formats = [f for f in check_formats if f not in excluded]
3682+
36693683
for i in check_formats:
3670-
if formats is not None:
3671-
if exclude:
3672-
if "!" + i in formats:
3673-
continue
3674-
elif i not in formats or "!" + i in formats:
3675-
continue
36763684
try:
36773685
factory, accept = OPEN[i]
36783686
result = not accept or accept(prefix)

0 commit comments

Comments
 (0)