Skip to content

Improve error messages from C - #9784

Open
akx wants to merge 21 commits into
python-pillow:mainfrom
akx:wrong-mode-exc
Open

akx wants to merge 21 commits into
python-pillow:mainfrom
akx:wrong-mode-exc

Conversation

@akx

@akx akx commented Jul 9, 2026 •

Copy link
Copy Markdown
Contributor

Inspired by #6667 (comment)

  • New internal exception type NotSupportedError for operations that are currently not supported; derives from both ValueError and NotImplementedError for backward compatibility.
    • Deriving from NotImplementedError allows for try-excepting in tests, so we can do better than (e.g.) Tests.test_image_filter.test_sanity where the test just quietly does nothing when a mode combo is not (yet, or currently) supported. (This wasn't wired up here yet.)
  • The internal ImagingError_*() C APIs now all support an optional message text, and message texts were added where practical. No longer "image has wrong mode" or "images do not match" for everything! ✨
  • Image nullness checks used to occasionally do ModeErrors, occasionally ValueErrors; now they're all ValueError.

@akx
akx marked this pull request as ready for review July 9, 2026 11:59
Comment thread src/libImaging/Reduce.c Resolved
@akx
akx force-pushed the wrong-mode-exc branch 3 times, most recently from fbf0a1d to 5b9e30f Compare July 20, 2026 07:31
@akx

akx commented Aug 31, 2026

Copy link
Copy Markdown
Contributor Author

Rebased post #9794.

@akx
akx marked this pull request as draft August 31, 2026 06:42
@akx
akx force-pushed the wrong-mode-exc branch 2 times, most recently from 92f9165 to 31a972d Compare August 31, 2026 06:49
@akx
akx marked this pull request as ready for review August 31, 2026 06:50
@akx
akx requested a review from radarhere August 31, 2026 08:11
Comment thread src/libImaging/RankFilter.c Resolved
@akx
akx force-pushed the wrong-mode-exc branch 2 times, most recently from 49db676 to 3a45fc5 Compare September 7, 2026 12:31
@codspeed

codspeed Bot commented Sep 7, 2026 •

Copy link
Copy Markdown

Merging this PR will not alter performance

1 warning

⚠️ 3 benchmarks are dominated by system calls

System calls cannot be simulated consistently and are left out of the measure. The reported value understates the real cost. Switch to the Walltime instrument to measure them.

Learn more about system calls

See affected benchmarks

✅ 668 untouched benchmarks
⏩ 352 skipped benchmarks1


Comparing akx:wrong-mode-exc (a568fc7) with main (16b1c33)

Open in CodSpeed

Footnotes

  1. 352 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports. ↩

Comment thread src/libImaging/Effects.c Resolved
Comment thread src/libImaging/ColorLUT.c Resolved
@akx
akx requested a review from radarhere September 13, 2026 19:11
Comment thread src/libImaging/Blend.c Resolved
Comment thread src/libImaging/Blend.c Resolved
Comment thread src/libImaging/Palette.c Resolved
@radarhere

Copy link
Copy Markdown
Member
>>> from PIL import Image, ImagePalette
>>> im = Image.new("L", (1, 1))
>>> im.palette = ImagePalette.ImagePalette()
>>> im.palette.mode = "L"
>>> im.palette.dirty = 1
>>> im.load()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "PIL/Image.py", line 995, in load
    self.im.putpalette(self.palette.mode, mode, arr)
PIL._imaging.NotSupportedError: only modes RGB/RGBA/CMYK supported

I don't like that it's raising an error that resides in PIL_imaging. I would prefer something like UnidentifiedImageError.

>>> Image.open("setup.py")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "PIL/Image.py", line 3822, in open
    raise UnidentifiedImageError(msg)
PIL.UnidentifiedImageError: cannot identify image file 'setup.py'

@akx

akx commented Nov 29, 2026

Copy link
Copy Markdown
Contributor Author

I don't like that it's raising an error that resides in PIL._imaging. I would prefer something like UnidentifiedImageError.

If the objection is that it lives in PIL._imaging instead of PIL, there are a couple of ways to do this:

  • configure PyErr_NewException so the name of the exception is PIL.NotSupportedError, and then re-export the C-side exception (with def __getattr__() trickery, as currently importing PIL alone does not imply importing the C module) in PIL/__init__.py, so it is actually importable by that name
    • to avoid that trickery, it could also live in PIL.Image (PIL.Image.NotSupportedError then), which already does always require the extension to be importable
  • declare the exception type in Python land, and import it from Python land in the C module (giving the C module a dependency on the Python module).

All of these will effectively make the new exception type a public API, contrary to the idea of it being an internal type (as noted in the PR description).

Would you like me to do any of these?

@radarhere

Copy link
Copy Markdown
Member

All of these will effectively make the new exception type a public API, contrary to the idea of it being an internal type (as noted in the PR description).

The fact that my earlier comment raised it from im.load() says to me that it isn't internal?

I would prefer a Python declaration, to be consistent with

class UnidentifiedImageError(OSError):

@akx

akx commented Nov 29, 2026

Copy link
Copy Markdown
Contributor Author

The fact that my earlier comment raised it from im.load() says to me that it isn't internal?

Internal as in "not reachable from user code". (Unless, well, if you get the C code to raise one, then catch exc.__class__ and use it to raise an exception of your own.)

I would prefer a Python declaration, to be consistent with

Alright. Cooking...

@radarhere

Copy link
Copy Markdown
Member

The fact that my earlier comment raised it from im.load() says to me that it isn't internal?

Internal as in "not reachable from user code". (Unless, well, if you get the C code to raise one, then catch exc.__class__ and use it to raise an exception of your own.)

Is this not reaching it from user code?

#9784 (comment)

>>> from PIL import Image, ImagePalette
>>> im = Image.new("L", (1, 1))
>>> im.palette = ImagePalette.ImagePalette()
>>> im.palette.mode = "L"
>>> im.palette.dirty = 1
>>> im.load()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "PIL/Image.py", line 995, in load
    self.im.putpalette(self.palette.mode, mode, arr)
PIL._imaging.NotSupportedError: only modes RGB/RGBA/CMYK supported

@akx

akx commented Nov 29, 2026

Copy link
Copy Markdown
Contributor Author

NotSupportedError is now in PIL, documented and tested consistently like UnidentifiedImageError.

@akx
akx requested a review from radarhere November 29, 2026 11:57
@akx

akx commented Dec 2, 2026

Copy link
Copy Markdown
Contributor Author

Merged main in, there was a conflict post #10694 merge.

@radarhere radarhere mentioned this pull request Dec 2, 2026
@radarhere

Copy link
Copy Markdown
Member

I've created a few PRs based on this, and the only remaining changes are

  • switching between different C functions that all raise a ValueError - ImagingError_Mismatch vs ImagingError_ModeError vs ImagingError_ValueError. I have a hard time seeing what difference this makes. I'd personally be happy removing ImagingError_Mismatch and ImagingError_ModeError altogether and just leaving ImagingError_ValueError
  • adding a custom NotSupportedError, inheriting from both ValueError, to be backwards compatible, and NotImplementedError.

https://docs.python.org/3/builtins/exceptions.html#NotImplementedError

In user defined base classes, abstract methods should raise this exception when they require derived classes to override the method, or while the class is being developed to indicate that the real implementation still needs to be added.

I don't know if that describes these situations.

https://docs.python.org/3/builtins/exceptions.html#ValueError

Raised when an operation or function receives an argument that has the right type but an inappropriate value, and the situation is not described by a more precise exception such as IndexError.

Is the problem that Pillow hasn't added functionality, or is the problem that the user passed in the wrong image mode, size or other value? I lean towards the latter, as I think the user hasn't followed instructions.

@aclark4life could you explain your thinking on NotSupportedError specifically?

@akx

akx commented Dec 3, 2026 •

Copy link
Copy Markdown
Contributor Author

while the class is being developed to indicate that the real implementation still needs to be added.

might be phrased a little narrowly. The Python standard library also extends NotImplementedError for purposes similar to this PR: pathlib.UnsupportedOperation is a NotImplementedError subclass for operations that are unsupported for certain path objects. The standard library's zipfile also directly raises NotImplementedError for compression methods not yet implemented.

Whether or not to double-inherit is just a backward compatibility question, as noted.

CPython did happily change the above zipfile RuntimeErrors to NotImplementedErrors in a minor release, python/cpython@b0d497c, so maybe that would be OK for Pillow too.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants