Skip to content

Commit

Permalink
Merge pull request #8117 from radarhere/type_hint
Browse files Browse the repository at this point in the history
  • Loading branch information
hugovk committed Jun 9, 2024
2 parents 0a45381 + 56c79b6 commit 53e82e4
Show file tree
Hide file tree
Showing 8 changed files with 53 additions and 31 deletions.
15 changes: 11 additions & 4 deletions src/PIL/GifImagePlugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -558,7 +558,11 @@ def _normalize_palette(im, palette, info):
return im


def _write_single_frame(im, fp, palette):
def _write_single_frame(
im: Image.Image,
fp: IO[bytes],
palette: bytes | bytearray | list[int] | ImagePalette.ImagePalette,
) -> None:
im_out = _normalize_mode(im)
for k, v in im_out.info.items():
im.encoderinfo.setdefault(k, v)
Expand All @@ -579,7 +583,9 @@ def _write_single_frame(im, fp, palette):
fp.write(b"\0") # end of image data


def _getbbox(base_im, im_frame):
def _getbbox(
base_im: Image.Image, im_frame: Image.Image
) -> tuple[Image.Image, tuple[int, int, int, int]]:
if _get_palette_bytes(im_frame) != _get_palette_bytes(base_im):
im_frame = im_frame.convert("RGBA")
base_im = base_im.convert("RGBA")
Expand Down Expand Up @@ -790,7 +796,7 @@ def _write_local_header(fp, im, offset, flags):
fp.write(o8(8)) # bits


def _save_netpbm(im, fp, filename):
def _save_netpbm(im: Image.Image, fp: IO[bytes], filename: str) -> None:
# Unused by default.
# To use, uncomment the register_save call at the end of the file.
#
Expand Down Expand Up @@ -821,6 +827,7 @@ def _save_netpbm(im, fp, filename):
)

# Allow ppmquant to receive SIGPIPE if ppmtogif exits
assert quant_proc.stdout is not None
quant_proc.stdout.close()

retcode = quant_proc.wait()
Expand Down Expand Up @@ -1080,7 +1087,7 @@ def getdata(im, offset=(0, 0), **params):
class Collector:
data = []

def write(self, data):
def write(self, data: bytes) -> None:
self.data.append(data)

im.load() # make sure raster data is available
Expand Down
38 changes: 25 additions & 13 deletions src/PIL/GimpGradientFile.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,15 @@
from __future__ import annotations

from math import log, pi, sin, sqrt
from typing import IO, Callable

from ._binary import o8

EPSILON = 1e-10
"""""" # Enable auto-doc for data member


def linear(middle, pos):
def linear(middle: float, pos: float) -> float:
if pos <= middle:
if middle < EPSILON:
return 0.0
Expand All @@ -43,19 +44,19 @@ def linear(middle, pos):
return 0.5 + 0.5 * pos / middle


def curved(middle, pos):
def curved(middle: float, pos: float) -> float:
return pos ** (log(0.5) / log(max(middle, EPSILON)))


def sine(middle, pos):
def sine(middle: float, pos: float) -> float:
return (sin((-pi / 2.0) + pi * linear(middle, pos)) + 1.0) / 2.0


def sphere_increasing(middle, pos):
def sphere_increasing(middle: float, pos: float) -> float:
return sqrt(1.0 - (linear(middle, pos) - 1.0) ** 2)


def sphere_decreasing(middle, pos):
def sphere_decreasing(middle: float, pos: float) -> float:
return 1.0 - sqrt(1.0 - linear(middle, pos) ** 2)


Expand All @@ -64,9 +65,22 @@ def sphere_decreasing(middle, pos):


class GradientFile:
gradient = None

def getpalette(self, entries=256):
gradient: (
list[
tuple[
float,
float,
float,
list[float],
list[float],
Callable[[float, float], float],
]
]
| None
) = None

def getpalette(self, entries: int = 256) -> tuple[bytes, str]:
assert self.gradient is not None
palette = []

ix = 0
Expand Down Expand Up @@ -101,7 +115,7 @@ def getpalette(self, entries=256):
class GimpGradientFile(GradientFile):
"""File handler for GIMP's gradient format."""

def __init__(self, fp):
def __init__(self, fp: IO[bytes]) -> None:
if fp.readline()[:13] != b"GIMP Gradient":
msg = "not a GIMP gradient file"
raise SyntaxError(msg)
Expand All @@ -114,7 +128,7 @@ def __init__(self, fp):

count = int(line)

gradient = []
self.gradient = []

for i in range(count):
s = fp.readline().split()
Expand All @@ -132,6 +146,4 @@ def __init__(self, fp):
msg = "cannot handle HSV colour space"
raise OSError(msg)

gradient.append((x0, x1, xm, rgb0, rgb1, segment))

self.gradient = gradient
self.gradient.append((x0, x1, xm, rgb0, rgb1, segment))
2 changes: 1 addition & 1 deletion src/PIL/Image.py
Original file line number Diff line number Diff line change
Expand Up @@ -2470,7 +2470,7 @@ def save(

save_all = params.pop("save_all", False)
self.encoderinfo = params
self.encoderconfig = ()
self.encoderconfig: tuple[Any, ...] = ()

preinit()

Expand Down
6 changes: 3 additions & 3 deletions src/PIL/ImageDraw2.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,15 +30,15 @@
class Pen:
"""Stores an outline color and width."""

def __init__(self, color, width=1, opacity=255):
def __init__(self, color: str, width: int = 1, opacity: int = 255) -> None:
self.color = ImageColor.getrgb(color)
self.width = width


class Brush:
"""Stores a fill color"""

def __init__(self, color, opacity=255):
def __init__(self, color: str, opacity: int = 255) -> None:
self.color = ImageColor.getrgb(color)


Expand All @@ -63,7 +63,7 @@ def __init__(self, image, size=None, color=None):
self.image = image
self.transform = None

def flush(self):
def flush(self) -> Image.Image:
return self.image

def render(self, op, xy, pen, brush=None):
Expand Down
6 changes: 3 additions & 3 deletions src/PIL/ImageTk.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@
_pilbitmap_ok = None


def _pilbitmap_check():
def _pilbitmap_check() -> int:
global _pilbitmap_ok
if _pilbitmap_ok is None:
try:
Expand Down Expand Up @@ -162,7 +162,7 @@ def height(self) -> int:
"""
return self.__size[1]

def paste(self, im):
def paste(self, im: Image.Image) -> None:
"""
Paste a PIL image into the photo image. Note that this can
be very slow if the photo image is displayed.
Expand Down Expand Up @@ -254,7 +254,7 @@ def __str__(self) -> str:
return str(self.__photo)


def getimage(photo):
def getimage(photo: PhotoImage) -> Image.Image:
"""Copies the contents of a PhotoImage to a PIL image memory."""
im = Image.new("RGBA", (photo.width(), photo.height()))
block = im.im
Expand Down
3 changes: 2 additions & 1 deletion src/PIL/Jpeg2KImagePlugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import io
import os
import struct
from typing import IO

from . import Image, ImageFile, ImagePalette, _binary

Expand Down Expand Up @@ -328,7 +329,7 @@ def _accept(prefix: bytes) -> bool:
# Save support


def _save(im, fp, filename):
def _save(im: Image.Image, fp: IO[bytes], filename: str) -> None:
# Get the keyword arguments
info = im.encoderinfo

Expand Down
10 changes: 6 additions & 4 deletions src/PIL/PaletteFile.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
#
from __future__ import annotations

from typing import IO

from ._binary import o8


Expand All @@ -22,8 +24,8 @@ class PaletteFile:

rawmode = "RGB"

def __init__(self, fp):
self.palette = [(i, i, i) for i in range(256)]
def __init__(self, fp: IO[bytes]) -> None:
palette = [o8(i) * 3 for i in range(256)]

while True:
s = fp.readline()
Expand All @@ -44,9 +46,9 @@ def __init__(self, fp):
g = b = r

if 0 <= i <= 255:
self.palette[i] = o8(r) + o8(g) + o8(b)
palette[i] = o8(r) + o8(g) + o8(b)

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

def getpalette(self) -> tuple[bytes, str]:
return self.palette, self.rawmode
4 changes: 2 additions & 2 deletions src/PIL/TiffImagePlugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@
from collections.abc import MutableMapping
from fractions import Fraction
from numbers import Number, Rational
from typing import TYPE_CHECKING, Any, Callable
from typing import IO, TYPE_CHECKING, Any, Callable

from . import ExifTags, Image, ImageFile, ImageOps, ImagePalette, TiffTags
from ._binary import i16be as i16
Expand Down Expand Up @@ -2149,7 +2149,7 @@ def fixOffsets(self, count, isShort=False, isLong=False):
self.rewriteLastLong(offset)


def _save_all(im, fp, filename):
def _save_all(im: Image.Image, fp: IO[bytes], filename: str) -> None:
encoderinfo = im.encoderinfo.copy()
encoderconfig = im.encoderconfig
append_images = list(encoderinfo.get("append_images", []))
Expand Down

0 comments on commit 53e82e4

Please sign in to comment.