From afc7d8d0b012b8be86e00411c5cb69de62478ee5 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Thu, 30 May 2024 17:17:22 +1000 Subject: [PATCH 1/6] Added type hints --- Tests/test_font_leaks.py | 2 +- Tests/test_image.py | 20 +++++++++++++++----- Tests/test_imagecms.py | 26 ++++++++++++++------------ Tests/test_imagestat.py | 4 ++-- 4 files changed, 32 insertions(+), 20 deletions(-) diff --git a/Tests/test_font_leaks.py b/Tests/test_font_leaks.py index 08a0e7431..3fb92a62e 100644 --- a/Tests/test_font_leaks.py +++ b/Tests/test_font_leaks.py @@ -12,7 +12,7 @@ class TestTTypeFontLeak(PillowLeakTestCase): iterations = 10 mem_limit = 4096 # k - def _test_font(self, font: ImageFont.FreeTypeFont) -> None: + def _test_font(self, font: ImageFont.FreeTypeFont | ImageFont.ImageFont) -> None: im = Image.new("RGB", (255, 255), "white") draw = ImageDraw.ImageDraw(im) self._test_leak( diff --git a/Tests/test_image.py b/Tests/test_image.py index 742d0dfe4..c7694a0ef 100644 --- a/Tests/test_image.py +++ b/Tests/test_image.py @@ -99,10 +99,18 @@ class TestImage: JPGFILE = "Tests/images/hopper.jpg" with pytest.raises(TypeError): - with Image.open(PNGFILE, formats=123): + with Image.open(PNGFILE, formats=123): # type: ignore[arg-type] pass - for formats in [["JPEG"], ("JPEG",), ["jpeg"], ["Jpeg"], ["jPeG"], ["JpEg"]]: + format_list: list[list[str] | tuple[str, ...]] = [ + ["JPEG"], + ("JPEG",), + ["jpeg"], + ["Jpeg"], + ["jPeG"], + ["JpEg"], + ] + for formats in format_list: with pytest.raises(UnidentifiedImageError): with Image.open(PNGFILE, formats=formats): pass @@ -138,7 +146,7 @@ class TestImage: def test_bad_mode(self) -> None: with pytest.raises(ValueError): - with Image.open("filename", "bad mode"): + with Image.open("filename", "bad mode"): # type: ignore[arg-type] pass def test_stringio(self) -> None: @@ -497,9 +505,11 @@ class TestImage: def test_check_size(self) -> None: # Checking that the _check_size function throws value errors when we want it to with pytest.raises(ValueError): - Image.new("RGB", 0) # not a tuple + # not a tuple + Image.new("RGB", 0) # type: ignore[arg-type] with pytest.raises(ValueError): - Image.new("RGB", (0,)) # Tuple too short + # tuple too short + Image.new("RGB", (0,)) # type: ignore[arg-type] with pytest.raises(ValueError): Image.new("RGB", (-1, -1)) # w,h < 0 diff --git a/Tests/test_imagecms.py b/Tests/test_imagecms.py index 8d2029c21..082eb8162 100644 --- a/Tests/test_imagecms.py +++ b/Tests/test_imagecms.py @@ -7,7 +7,7 @@ import shutil import sys from io import BytesIO from pathlib import Path -from typing import Any +from typing import Any, Literal, cast import pytest @@ -209,13 +209,13 @@ def test_exceptions() -> None: ImageCms.buildTransform("foo", "bar", "RGB", "RGB") with pytest.raises(ImageCms.PyCMSError, match="Invalid type for Profile"): - ImageCms.getProfileName(None) + ImageCms.getProfileName(None) # type: ignore[arg-type] skip_missing() # Python <= 3.9: "an integer is required (got type NoneType)" # Python > 3.9: "'NoneType' object cannot be interpreted as an integer" with pytest.raises(ImageCms.PyCMSError, match="integer"): - ImageCms.isIntentSupported(SRGB, None, None) + ImageCms.isIntentSupported(SRGB, None, None) # type: ignore[arg-type] def test_display_profile() -> None: @@ -239,7 +239,7 @@ def test_unsupported_color_space() -> None: "Color space not supported for on-the-fly profile creation (unsupported)" ), ): - ImageCms.createProfile("unsupported") + ImageCms.createProfile("unsupported") # type: ignore[arg-type] def test_invalid_color_temperature() -> None: @@ -352,7 +352,7 @@ def test_extended_information() -> None: p = o.profile def assert_truncated_tuple_equal( - tup1: tuple[Any, ...], tup2: tuple[Any, ...], digits: int = 10 + tup1: tuple[Any, ...] | None, tup2: tuple[Any, ...], digits: int = 10 ) -> None: # Helper function to reduce precision of tuples of floats # recursively and then check equality. @@ -368,6 +368,7 @@ def test_extended_information() -> None: for val in tuple_value ) + assert tup1 is not None assert truncate_tuple(tup1) == truncate_tuple(tup2) assert p.attributes == 4294967296 @@ -513,22 +514,22 @@ def test_non_ascii_path(tmp_path: Path) -> None: def test_profile_typesafety() -> None: # does not segfault with pytest.raises(TypeError, match="Invalid type for Profile"): - ImageCms.ImageCmsProfile(0).tobytes() + ImageCms.ImageCmsProfile(0) # type: ignore[arg-type] with pytest.raises(TypeError, match="Invalid type for Profile"): - ImageCms.ImageCmsProfile(1).tobytes() + ImageCms.ImageCmsProfile(1) # type: ignore[arg-type] # also check core function with pytest.raises(TypeError): - ImageCms.core.profile_tobytes(0) + ImageCms.core.profile_tobytes(0) # type: ignore[arg-type] with pytest.raises(TypeError): - ImageCms.core.profile_tobytes(1) + ImageCms.core.profile_tobytes(1) # type: ignore[arg-type] if not is_pypy(): # core profile should not be directly instantiable with pytest.raises(TypeError): ImageCms.core.CmsProfile() with pytest.raises(TypeError): - ImageCms.core.CmsProfile(0) + ImageCms.core.CmsProfile(0) # type: ignore[call-arg] @pytest.mark.skipif(is_pypy(), reason="fails on PyPy") @@ -537,7 +538,7 @@ def test_transform_typesafety() -> None: with pytest.raises(TypeError): ImageCms.core.CmsTransform() with pytest.raises(TypeError): - ImageCms.core.CmsTransform(0) + ImageCms.core.CmsTransform(0) # type: ignore[call-arg] def assert_aux_channel_preserved( @@ -637,7 +638,8 @@ def test_auxiliary_channels_isolated() -> None: continue # convert with and without AUX data, test colors are equal - source_profile = ImageCms.createProfile(src_format[1]) + src_colorSpace = cast(Literal["LAB", "XYZ", "sRGB"], src_format[1]) + source_profile = ImageCms.createProfile(src_colorSpace) destination_profile = ImageCms.createProfile(dst_format[1]) source_image = src_format[3] test_transform = ImageCms.buildTransform( diff --git a/Tests/test_imagestat.py b/Tests/test_imagestat.py index b1c1306c1..0dfbc5a2a 100644 --- a/Tests/test_imagestat.py +++ b/Tests/test_imagestat.py @@ -25,10 +25,10 @@ def test_sanity() -> None: st.stddev with pytest.raises(AttributeError): - st.spam() + st.spam() # type: ignore[attr-defined] with pytest.raises(TypeError): - ImageStat.Stat(1) + ImageStat.Stat(1) # type: ignore[arg-type] def test_hopper() -> None: From 66ab7e0de22251b32eccd8938ac7f985579dc0ac Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Sat, 1 Jun 2024 21:31:53 +1000 Subject: [PATCH 2/6] Added type hints --- Tests/test_file_gif.py | 5 +++-- Tests/test_file_jpeg.py | 4 ++-- Tests/test_file_libtiff.py | 3 ++- Tests/test_image.py | 4 +++- Tests/test_image_array.py | 2 +- Tests/test_image_crop.py | 26 +++++++++++++------------- Tests/test_image_filter.py | 4 ++-- Tests/test_image_getextrema.py | 2 +- Tests/test_imagecms.py | 8 ++++++-- Tests/test_imagedraw.py | 2 +- 10 files changed, 34 insertions(+), 26 deletions(-) diff --git a/Tests/test_file_gif.py b/Tests/test_file_gif.py index 48c70db8a..4e790926b 100644 --- a/Tests/test_file_gif.py +++ b/Tests/test_file_gif.py @@ -1252,10 +1252,11 @@ def test_palette_save_L(tmp_path: Path) -> None: im = hopper("P") im_l = Image.frombytes("L", im.size, im.tobytes()) - palette = bytes(im.getpalette()) + palette = im.getpalette() + assert palette is not None out = str(tmp_path / "temp.gif") - im_l.save(out, palette=palette) + im_l.save(out, palette=bytes(palette)) with Image.open(out) as reloaded: assert_image_equal(reloaded.convert("RGB"), im.convert("RGB")) diff --git a/Tests/test_file_jpeg.py b/Tests/test_file_jpeg.py index f24faecaa..33f9ce00e 100644 --- a/Tests/test_file_jpeg.py +++ b/Tests/test_file_jpeg.py @@ -154,7 +154,7 @@ class TestFileJpeg: assert k > 0.9 def test_rgb(self) -> None: - def getchannels(im: Image.Image) -> tuple[int, int, int]: + def getchannels(im: JpegImagePlugin.JpegImageFile) -> tuple[int, int, int]: return tuple(v[0] for v in im.layer) im = hopper() @@ -443,7 +443,7 @@ class TestFileJpeg: assert_image(im1, im2.mode, im2.size) def test_subsampling(self) -> None: - def getsampling(im: Image.Image): + def getsampling(im: JpegImagePlugin.JpegImageFile): layer = im.layer return layer[0][1:3] + layer[1][1:3] + layer[2][1:3] diff --git a/Tests/test_file_libtiff.py b/Tests/test_file_libtiff.py index 6c13999a5..22bcd2856 100644 --- a/Tests/test_file_libtiff.py +++ b/Tests/test_file_libtiff.py @@ -668,7 +668,8 @@ class TestFileLibTiff(LibTiffTestCase): pilim.save(buffer_io, format="tiff", compression=compression) buffer_io.seek(0) - assert_image_similar_tofile(pilim, buffer_io, 0) + with Image.open(buffer_io) as saved_im: + assert_image_similar(pilim, saved_im, 0) save_bytesio() save_bytesio("raw") diff --git a/Tests/test_image.py b/Tests/test_image.py index c7694a0ef..d6a739c79 100644 --- a/Tests/test_image.py +++ b/Tests/test_image.py @@ -25,6 +25,7 @@ from PIL import ( from .helper import ( assert_image_equal, assert_image_equal_tofile, + assert_image_similar, assert_image_similar_tofile, assert_not_all_same, hopper, @@ -193,7 +194,8 @@ class TestImage: with tempfile.TemporaryFile() as fp: im.save(fp, "JPEG") fp.seek(0) - assert_image_similar_tofile(im, fp, 20) + with Image.open(fp) as reloaded: + assert_image_similar(im, reloaded, 20) def test_unknown_extension(self, tmp_path: Path) -> None: im = hopper() diff --git a/Tests/test_image_array.py b/Tests/test_image_array.py index 342bd8654..d7e6c562c 100644 --- a/Tests/test_image_array.py +++ b/Tests/test_image_array.py @@ -86,8 +86,8 @@ def test_fromarray() -> None: assert test("RGBX") == ("RGBA", (128, 100), True) # Test mode is None with no "typestr" in the array interface + wrapped = Wrapper(hopper("L"), {"shape": (100, 128)}) with pytest.raises(TypeError): - wrapped = Wrapper(test("L"), {"shape": (100, 128)}) Image.fromarray(wrapped) diff --git a/Tests/test_image_crop.py b/Tests/test_image_crop.py index d095364ba..07fec2e64 100644 --- a/Tests/test_image_crop.py +++ b/Tests/test_image_crop.py @@ -18,7 +18,7 @@ def test_crop(mode: str) -> None: def test_wide_crop() -> None: - def crop(*bbox: int) -> tuple[int, ...]: + def crop(bbox: tuple[int, int, int, int]) -> tuple[int, ...]: i = im.crop(bbox) h = i.histogram() while h and not h[-1]: @@ -27,23 +27,23 @@ def test_wide_crop() -> None: im = Image.new("L", (100, 100), 1) - assert crop(0, 0, 100, 100) == (0, 10000) - assert crop(25, 25, 75, 75) == (0, 2500) + assert crop((0, 0, 100, 100)) == (0, 10000) + assert crop((25, 25, 75, 75)) == (0, 2500) # sides - assert crop(-25, 0, 25, 50) == (1250, 1250) - assert crop(0, -25, 50, 25) == (1250, 1250) - assert crop(75, 0, 125, 50) == (1250, 1250) - assert crop(0, 75, 50, 125) == (1250, 1250) + assert crop((-25, 0, 25, 50)) == (1250, 1250) + assert crop((0, -25, 50, 25)) == (1250, 1250) + assert crop((75, 0, 125, 50)) == (1250, 1250) + assert crop((0, 75, 50, 125)) == (1250, 1250) - assert crop(-25, 25, 125, 75) == (2500, 5000) - assert crop(25, -25, 75, 125) == (2500, 5000) + assert crop((-25, 25, 125, 75)) == (2500, 5000) + assert crop((25, -25, 75, 125)) == (2500, 5000) # corners - assert crop(-25, -25, 25, 25) == (1875, 625) - assert crop(75, -25, 125, 25) == (1875, 625) - assert crop(75, 75, 125, 125) == (1875, 625) - assert crop(-25, 75, 25, 125) == (1875, 625) + assert crop((-25, -25, 25, 25)) == (1875, 625) + assert crop((75, -25, 125, 25)) == (1875, 625) + assert crop((75, 75, 125, 125)) == (1875, 625) + assert crop((-25, 75, 25, 125)) == (1875, 625) @pytest.mark.parametrize("box", ((8, 2, 2, 8), (2, 8, 8, 2), (8, 8, 2, 2))) diff --git a/Tests/test_image_filter.py b/Tests/test_image_filter.py index 47f9ffa3d..1f0644471 100644 --- a/Tests/test_image_filter.py +++ b/Tests/test_image_filter.py @@ -46,9 +46,9 @@ def test_sanity(filter_to_apply: ImageFilter.Filter, mode: str) -> None: @pytest.mark.parametrize("mode", ("L", "I", "RGB", "CMYK")) def test_sanity_error(mode: str) -> None: + im = hopper(mode) with pytest.raises(TypeError): - im = hopper(mode) - im.filter("hello") + im.filter("hello") # type: ignore[arg-type] # crashes on small images diff --git a/Tests/test_image_getextrema.py b/Tests/test_image_getextrema.py index a5b974459..de5956f3e 100644 --- a/Tests/test_image_getextrema.py +++ b/Tests/test_image_getextrema.py @@ -6,7 +6,7 @@ from .helper import hopper def test_extrema() -> None: - def extrema(mode: str) -> tuple[int, int] | tuple[tuple[int, int], ...]: + def extrema(mode: str) -> tuple[float, float] | tuple[tuple[int, int], ...]: return hopper(mode).getextrema() assert extrema("1") == (0, 255) diff --git a/Tests/test_imagecms.py b/Tests/test_imagecms.py index 082eb8162..55f72c3b9 100644 --- a/Tests/test_imagecms.py +++ b/Tests/test_imagecms.py @@ -247,7 +247,7 @@ def test_invalid_color_temperature() -> None: ImageCms.PyCMSError, match='Color temperature must be numeric, "invalid" not valid', ): - ImageCms.createProfile("LAB", "invalid") + ImageCms.createProfile("LAB", "invalid") # type: ignore[arg-type] @pytest.mark.parametrize("flag", ("my string", -1)) @@ -256,7 +256,7 @@ def test_invalid_flag(flag: str | int) -> None: with pytest.raises( ImageCms.PyCMSError, match="flags must be an integer between 0 and " ): - ImageCms.profileToProfile(im, "foo", "bar", flags=flag) + ImageCms.profileToProfile(im, "foo", "bar", flags=flag) # type: ignore[arg-type] def test_simple_lab() -> None: @@ -588,11 +588,13 @@ def assert_aux_channel_preserved( ) # apply transform + result_image: Image.Image | None if transform_in_place: ImageCms.applyTransform(source_image, t, inPlace=True) result_image = source_image else: result_image = ImageCms.applyTransform(source_image, t, inPlace=False) + assert result_image is not None result_image_aux = result_image.getchannel(preserved_channel) assert_image_equal(source_image_aux, result_image_aux) @@ -650,6 +652,7 @@ def test_auxiliary_channels_isolated() -> None: ) # test conversion from aux-ful source + test_image: Image.Image | None if transform_in_place: test_image = source_image.copy() ImageCms.applyTransform(test_image, test_transform, inPlace=True) @@ -657,6 +660,7 @@ def test_auxiliary_channels_isolated() -> None: test_image = ImageCms.applyTransform( source_image, test_transform, inPlace=False ) + assert test_image is not None # reference conversion from aux-less source reference_transform = ImageCms.buildTransform( diff --git a/Tests/test_imagedraw.py b/Tests/test_imagedraw.py index 69d09e03d..c221fe008 100644 --- a/Tests/test_imagedraw.py +++ b/Tests/test_imagedraw.py @@ -1083,8 +1083,8 @@ def test_line_horizontal() -> None: ) +@pytest.mark.xfail(reason="failing test") def test_line_h_s1_w2() -> None: - pytest.skip("failing") img, draw = create_base_image_draw((20, 20)) draw.line((5, 5, 14, 6), BLACK, 2) assert_image_equal_tofile( From 54150f2061fa87cb5f629f28958d53c293ea4b90 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Sun, 2 Jun 2024 16:26:35 +1000 Subject: [PATCH 3/6] Corrected docstring --- src/PIL/ImageCms.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/PIL/ImageCms.py b/src/PIL/ImageCms.py index 5f5c5df54..5915cc944 100644 --- a/src/PIL/ImageCms.py +++ b/src/PIL/ImageCms.py @@ -777,7 +777,7 @@ def createProfile( :param colorSpace: String, the color space of the profile you wish to create. Currently only "LAB", "XYZ", and "sRGB" are supported. - :param colorTemp: Positive integer for the white point for the profile, in + :param colorTemp: Positive number for the white point for the profile, in degrees Kelvin (i.e. 5000, 6500, 9600, etc.). The default is for D50 illuminant if omitted (5000k). colorTemp is ONLY applied to LAB profiles, and is ignored for XYZ and sRGB. From 4aba0b8238db501b5f498fee9335f380a7d08f88 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Sun, 2 Jun 2024 16:27:05 +1000 Subject: [PATCH 4/6] Changed default colorTemp --- src/PIL/ImageCms.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/PIL/ImageCms.py b/src/PIL/ImageCms.py index 5915cc944..ec9471f84 100644 --- a/src/PIL/ImageCms.py +++ b/src/PIL/ImageCms.py @@ -754,7 +754,7 @@ def applyTransform( def createProfile( - colorSpace: Literal["LAB", "XYZ", "sRGB"], colorTemp: SupportsFloat = -1 + colorSpace: Literal["LAB", "XYZ", "sRGB"], colorTemp: SupportsFloat = 0 ) -> core.CmsProfile: """ (pyCMS) Creates a profile. From 8dae9b618f39b8afd9ae2177dcce6a02ea227006 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Sun, 2 Jun 2024 17:53:52 +1000 Subject: [PATCH 5/6] Corrected type hint --- src/PIL/ImageCms.py | 2 +- src/PIL/_imagingcms.pyi | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/PIL/ImageCms.py b/src/PIL/ImageCms.py index ec9471f84..19a79facc 100644 --- a/src/PIL/ImageCms.py +++ b/src/PIL/ImageCms.py @@ -1089,7 +1089,7 @@ def isIntentSupported( raise PyCMSError(v) from v -def versions() -> tuple[str, str, str, str]: +def versions() -> tuple[str, str | None, str, str]: """ (pyCMS) Fetches versions. """ diff --git a/src/PIL/_imagingcms.pyi b/src/PIL/_imagingcms.pyi index f704047be..2abd6d0f7 100644 --- a/src/PIL/_imagingcms.pyi +++ b/src/PIL/_imagingcms.pyi @@ -2,7 +2,7 @@ import datetime import sys from typing import Literal, SupportsFloat, TypedDict -littlecms_version: str +littlecms_version: str | None _Tuple3f = tuple[float, float, float] _Tuple2x3f = tuple[_Tuple3f, _Tuple3f] From f5da04adb07f19bd79aededb2be7291d445e4f96 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Mon, 3 Jun 2024 21:58:02 +1000 Subject: [PATCH 6/6] Added type hints Co-authored-by: Nulano --- src/PIL/Image.py | 10 ++++------ src/PIL/ImageDraw.py | 8 +++++++- src/PIL/PyAccess.py | 41 ++++++++++++++++++++++++++--------------- 3 files changed, 37 insertions(+), 22 deletions(-) diff --git a/src/PIL/Image.py b/src/PIL/Image.py index 958b95e3b..dd6984020 100644 --- a/src/PIL/Image.py +++ b/src/PIL/Image.py @@ -1511,7 +1511,7 @@ class Image: self._exif._loaded = False self.getexif() - def get_child_images(self): + def get_child_images(self) -> list[ImageFile.ImageFile]: child_images = [] exif = self.getexif() ifds = [] @@ -1535,10 +1535,7 @@ class Image: fp = self.fp thumbnail_offset = ifd.get(513) if thumbnail_offset is not None: - try: - thumbnail_offset += self._exif_offset - except AttributeError: - pass + thumbnail_offset += getattr(self, "_exif_offset", 0) self.fp.seek(thumbnail_offset) data = self.fp.read(ifd.get(514)) fp = io.BytesIO(data) @@ -1604,7 +1601,7 @@ class Image: or "transparency" in self.info ) - def apply_transparency(self): + def apply_transparency(self) -> None: """ If a P mode image has a "transparency" key in the info dictionary, remove the key and instead apply the transparency to the palette. @@ -1616,6 +1613,7 @@ class Image: from . import ImagePalette palette = self.getpalette("RGBA") + assert palette is not None transparency = self.info["transparency"] if isinstance(transparency, bytes): for i, alpha in enumerate(transparency): diff --git a/src/PIL/ImageDraw.py b/src/PIL/ImageDraw.py index 17c176430..8fe179dd5 100644 --- a/src/PIL/ImageDraw.py +++ b/src/PIL/ImageDraw.py @@ -908,7 +908,13 @@ def getdraw(im=None, hints=None): return im, handler -def floodfill(image: Image.Image, xy, value, border=None, thresh=0) -> None: +def floodfill( + image: Image.Image, + xy: tuple[int, int], + value: float | tuple[int, ...], + border: float | tuple[int, ...] | None = None, + thresh: float = 0, +) -> None: """ (experimental) Fills a bounded region with a given color. diff --git a/src/PIL/PyAccess.py b/src/PIL/PyAccess.py index a9da90613..fe12cb641 100644 --- a/src/PIL/PyAccess.py +++ b/src/PIL/PyAccess.py @@ -22,6 +22,7 @@ from __future__ import annotations import logging import sys +from typing import TYPE_CHECKING from ._deprecate import deprecate @@ -48,9 +49,12 @@ except ImportError as ex: logger = logging.getLogger(__name__) +if TYPE_CHECKING: + from . import Image + class PyAccess: - def __init__(self, img, readonly=False): + def __init__(self, img: Image.Image, readonly: bool = False) -> None: deprecate("PyAccess", 11) vals = dict(img.im.unsafe_ptrs) self.readonly = readonly @@ -77,7 +81,8 @@ class PyAccess: """ Modifies the pixel at x,y. The color is given as a single numerical value for single band images, and a tuple for - multi-band images + multi-band images. In addition to this, RGB and RGBA tuples + are accepted for P and PA images. :param xy: The pixel coordinate, given as (x, y). See :ref:`coordinate-system`. @@ -108,7 +113,7 @@ class PyAccess: return self.set_pixel(x, y, color) - def __getitem__(self, xy): + def __getitem__(self, xy: tuple[int, int]) -> float | tuple[int, ...]: """ Returns the pixel at x,y. The pixel is returned as a single value for single band images or a tuple for multiple band @@ -130,13 +135,19 @@ class PyAccess: putpixel = __setitem__ getpixel = __getitem__ - def check_xy(self, xy): + def check_xy(self, xy: tuple[int, int]) -> tuple[int, int]: (x, y) = xy if not (0 <= x < self.xsize and 0 <= y < self.ysize): msg = "pixel location out of range" raise ValueError(msg) return xy + def get_pixel(self, x: int, y: int) -> float | tuple[int, ...]: + raise NotImplementedError() + + def set_pixel(self, x: int, y: int, color: float | tuple[int, ...]) -> None: + raise NotImplementedError() + class _PyAccess32_2(PyAccess): """PA, LA, stored in first and last bytes of a 32 bit word""" @@ -144,7 +155,7 @@ class _PyAccess32_2(PyAccess): def _post_init(self, *args, **kwargs): self.pixels = ffi.cast("struct Pixel_RGBA **", self.image32) - def get_pixel(self, x, y): + def get_pixel(self, x: int, y: int) -> tuple[int, int]: pixel = self.pixels[y][x] return pixel.r, pixel.a @@ -161,7 +172,7 @@ class _PyAccess32_3(PyAccess): def _post_init(self, *args, **kwargs): self.pixels = ffi.cast("struct Pixel_RGBA **", self.image32) - def get_pixel(self, x, y): + def get_pixel(self, x: int, y: int) -> tuple[int, int, int]: pixel = self.pixels[y][x] return pixel.r, pixel.g, pixel.b @@ -180,7 +191,7 @@ class _PyAccess32_4(PyAccess): def _post_init(self, *args, **kwargs): self.pixels = ffi.cast("struct Pixel_RGBA **", self.image32) - def get_pixel(self, x, y): + def get_pixel(self, x: int, y: int) -> tuple[int, int, int, int]: pixel = self.pixels[y][x] return pixel.r, pixel.g, pixel.b, pixel.a @@ -199,7 +210,7 @@ class _PyAccess8(PyAccess): def _post_init(self, *args, **kwargs): self.pixels = self.image8 - def get_pixel(self, x, y): + def get_pixel(self, x: int, y: int) -> int: return self.pixels[y][x] def set_pixel(self, x, y, color): @@ -217,7 +228,7 @@ class _PyAccessI16_N(PyAccess): def _post_init(self, *args, **kwargs): self.pixels = ffi.cast("unsigned short **", self.image) - def get_pixel(self, x, y): + def get_pixel(self, x: int, y: int) -> int: return self.pixels[y][x] def set_pixel(self, x, y, color): @@ -235,7 +246,7 @@ class _PyAccessI16_L(PyAccess): def _post_init(self, *args, **kwargs): self.pixels = ffi.cast("struct Pixel_I16 **", self.image) - def get_pixel(self, x, y): + def get_pixel(self, x: int, y: int) -> int: pixel = self.pixels[y][x] return pixel.l + pixel.r * 256 @@ -256,7 +267,7 @@ class _PyAccessI16_B(PyAccess): def _post_init(self, *args, **kwargs): self.pixels = ffi.cast("struct Pixel_I16 **", self.image) - def get_pixel(self, x, y): + def get_pixel(self, x: int, y: int) -> int: pixel = self.pixels[y][x] return pixel.l * 256 + pixel.r @@ -277,7 +288,7 @@ class _PyAccessI32_N(PyAccess): def _post_init(self, *args, **kwargs): self.pixels = self.image32 - def get_pixel(self, x, y): + def get_pixel(self, x: int, y: int) -> int: return self.pixels[y][x] def set_pixel(self, x, y, color): @@ -296,7 +307,7 @@ class _PyAccessI32_Swap(PyAccess): chars[0], chars[1], chars[2], chars[3] = chars[3], chars[2], chars[1], chars[0] return ffi.cast("int *", chars)[0] - def get_pixel(self, x, y): + def get_pixel(self, x: int, y: int) -> int: return self.reverse(self.pixels[y][x]) def set_pixel(self, x, y, color): @@ -309,7 +320,7 @@ class _PyAccessF(PyAccess): def _post_init(self, *args, **kwargs): self.pixels = ffi.cast("float **", self.image32) - def get_pixel(self, x, y): + def get_pixel(self, x: int, y: int) -> float: return self.pixels[y][x] def set_pixel(self, x, y, color): @@ -357,7 +368,7 @@ else: mode_map["I;32B"] = _PyAccessI32_N -def new(img, readonly=False): +def new(img: Image.Image, readonly: bool = False) -> PyAccess | None: access_type = mode_map.get(img.mode, None) if not access_type: logger.debug("PyAccess Not Implemented: %s", img.mode)