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 type hints #8105

Merged
merged 1 commit into from
Jun 4, 2024
Merged
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
3 changes: 2 additions & 1 deletion src/PIL/BlpImagePlugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
import struct
from enum import IntEnum
from io import BytesIO
from typing import IO

from . import Image, ImageFile

Expand Down Expand Up @@ -448,7 +449,7 @@ def encode(self, bufsize):
return len(data), 0, data


def _save(im, fp, filename):
def _save(im: Image.Image, fp: IO[bytes], filename: str) -> None:
if im.mode != "P":
msg = "Unsupported BLP image mode"
raise ValueError(msg)
Expand Down
2 changes: 1 addition & 1 deletion src/PIL/EpsImagePlugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -228,7 +228,7 @@ def _open(self) -> None:
reading_trailer_comments = False
trailer_reached = False

def check_required_header_comments():
def check_required_header_comments() -> None:
if "PS-Adobe" not in self.info:
msg = 'EPS header missing "%!PS-Adobe" comment'
raise SyntaxError(msg)
Expand Down
6 changes: 3 additions & 3 deletions src/PIL/FpxImagePlugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ def _open(self):

self._open_index(1)

def _open_index(self, index=1):
def _open_index(self, index: int = 1) -> None:
#
# get the Image Contents Property Set

Expand All @@ -85,7 +85,7 @@ def _open_index(self, index=1):
size = max(self.size)
i = 1
while size > 64:
size = size / 2
size = size // 2
i += 1
self.maxid = i - 1

Expand Down Expand Up @@ -118,7 +118,7 @@ def _open_index(self, index=1):

self._open_subimage(1, self.maxid)

def _open_subimage(self, index=1, subimage=0):
def _open_subimage(self, index: int = 1, subimage: int = 0) -> None:
#
# setup tile descriptors for a given subimage

Expand Down
13 changes: 8 additions & 5 deletions src/PIL/ImageEnhance.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,10 @@


class _Enhance:
def enhance(self, factor):
image: Image.Image
degenerate: Image.Image

def enhance(self, factor: float) -> Image.Image:
"""
Returns an enhanced image.

Expand All @@ -46,7 +49,7 @@ class Color(_Enhance):
the original image.
"""

def __init__(self, image):
def __init__(self, image: Image.Image) -> None:
self.image = image
self.intermediate_mode = "L"
if "A" in image.getbands():
Expand All @@ -63,7 +66,7 @@ class Contrast(_Enhance):
gives a solid gray image. A factor of 1.0 gives the original image.
"""

def __init__(self, image):
def __init__(self, image: Image.Image) -> None:
self.image = image
mean = int(ImageStat.Stat(image.convert("L")).mean[0] + 0.5)
self.degenerate = Image.new("L", image.size, mean).convert(image.mode)
Expand All @@ -80,7 +83,7 @@ class Brightness(_Enhance):
original image.
"""

def __init__(self, image):
def __init__(self, image: Image.Image) -> None:
self.image = image
self.degenerate = Image.new(image.mode, image.size, 0)

Expand All @@ -96,7 +99,7 @@ class Sharpness(_Enhance):
original image, and a factor of 2.0 gives a sharpened image.
"""

def __init__(self, image):
def __init__(self, image: Image.Image) -> None:
self.image = image
self.degenerate = image.filter(ImageFilter.SMOOTH)

Expand Down
25 changes: 16 additions & 9 deletions src/PIL/ImageFilter.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@

import abc
import functools
from typing import Sequence
from types import ModuleType
from typing import Any, Sequence


class Filter:
Expand Down Expand Up @@ -57,7 +58,13 @@ class Kernel(BuiltinFilter):

name = "Kernel"

def __init__(self, size, kernel, scale=None, offset=0):
def __init__(
self,
size: tuple[int, int],
kernel: Sequence[float],
scale: float | None = None,
offset: float = 0,
) -> None:
if scale is None:
# default scale is sum of kernel
scale = functools.reduce(lambda a, b: a + b, kernel)
Expand Down Expand Up @@ -194,10 +201,8 @@ class BoxBlur(MultibandFilter):

name = "BoxBlur"

def __init__(self, radius):
xy = radius
if not isinstance(xy, (tuple, list)):
xy = (xy, xy)
def __init__(self, radius: float | Sequence[float]) -> None:
xy = radius if isinstance(radius, (tuple, list)) else (radius, radius)
if xy[0] < 0 or xy[1] < 0:
msg = "radius must be >= 0"
raise ValueError(msg)
Expand Down Expand Up @@ -381,7 +386,9 @@ class Color3DLUT(MultibandFilter):

name = "Color 3D LUT"

def __init__(self, size, table, channels=3, target_mode=None, **kwargs):
def __init__(
self, size, table, channels: int = 3, target_mode: str | None = None, **kwargs
):
if channels not in (3, 4):
msg = "Only 3 or 4 output channels are supported"
raise ValueError(msg)
Expand All @@ -395,7 +402,7 @@ def __init__(self, size, table, channels=3, target_mode=None, **kwargs):
items = size[0] * size[1] * size[2]
wrong_size = False

numpy = None
numpy: ModuleType | None = None
if hasattr(table, "shape"):
try:
import numpy
Expand Down Expand Up @@ -442,7 +449,7 @@ def __init__(self, size, table, channels=3, target_mode=None, **kwargs):
self.table = table

@staticmethod
def _check_size(size):
def _check_size(size: Any) -> list[int]:
try:
_, _, _ = size
except ValueError as e:
Expand Down
6 changes: 3 additions & 3 deletions src/PIL/ImageMorph.py
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,7 @@ def __init__(
elif patterns is not None:
self.lut = LutBuilder(patterns=patterns).build_lut()

def apply(self, image: Image.Image):
def apply(self, image: Image.Image) -> tuple[int, Image.Image]:
"""Run a single morphological operation on an image

Returns a tuple of the number of changed pixels and the
Expand All @@ -216,7 +216,7 @@ def apply(self, image: Image.Image):
count = _imagingmorph.apply(bytes(self.lut), image.im.id, outimage.im.id)
return count, outimage

def match(self, image: Image.Image):
def match(self, image: Image.Image) -> list[tuple[int, int]]:
"""Get a list of coordinates matching the morphological operation on
an image.

Expand All @@ -231,7 +231,7 @@ def match(self, image: Image.Image):
raise ValueError(msg)
return _imagingmorph.match(bytes(self.lut), image.im.id)

def get_on_pixels(self, image: Image.Image):
def get_on_pixels(self, image: Image.Image) -> list[tuple[int, int]]:
"""Get a list of all turned on pixels in a binary image

Returns a list of tuples of (x,y) coordinates
Expand Down
6 changes: 3 additions & 3 deletions src/PIL/Jpeg2KImagePlugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ def __init__(self, fp, length=-1):
self.length = length
self.remaining_in_box = -1

def _can_read(self, num_bytes):
def _can_read(self, num_bytes: int) -> bool:
if self.has_length and self.fp.tell() + num_bytes > self.length:
# Outside box: ensure we don't read past the known file length
return False
Expand All @@ -44,7 +44,7 @@ def _can_read(self, num_bytes):
else:
return True # No length known, just read

def _read_bytes(self, num_bytes):
def _read_bytes(self, num_bytes: int) -> bytes:
if not self._can_read(num_bytes):
msg = "Not enough data in header"
raise SyntaxError(msg)
Expand Down Expand Up @@ -74,7 +74,7 @@ def has_next_box(self) -> bool:
else:
return True

def next_box_type(self):
def next_box_type(self) -> bytes:
# Skip the rest of the box if it has not been read
if self.remaining_in_box > 0:
self.fp.seek(self.remaining_in_box, os.SEEK_CUR)
Expand Down
2 changes: 1 addition & 1 deletion src/PIL/PaletteFile.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,5 +48,5 @@ def __init__(self, fp):

self.palette = b"".join(self.palette)

def getpalette(self):
def getpalette(self) -> tuple[bytes, str]:
return self.palette, self.rawmode
2 changes: 1 addition & 1 deletion src/PIL/QoiImagePlugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ def _open(self) -> None:
class QoiDecoder(ImageFile.PyDecoder):
_pulls_fd = True

def _add_to_previous_pixels(self, value):
def _add_to_previous_pixels(self, value: bytes | bytearray) -> None:
self._previous_pixel = value

r, g, b, a = value
Expand Down
2 changes: 1 addition & 1 deletion src/PIL/SpiderImagePlugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -233,7 +233,7 @@ def loadImageSeries(filelist=None):
# For saving images in Spider format


def makeSpiderHeader(im):
def makeSpiderHeader(im: Image.Image) -> list[bytes]:
nsam, nrow = im.size
lenbyt = nsam * 4 # There are labrec records in the header
labrec = int(1024 / lenbyt)
Expand Down
2 changes: 1 addition & 1 deletion src/PIL/WebPImagePlugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ def seek(self, frame: int) -> None:
# Set logical frame to requested position
self.__logical_frame = frame

def _reset(self, reset=True):
def _reset(self, reset: bool = True) -> None:
if reset:
self._decoder.reset()
self.__physical_frame = 0
Expand Down
Loading