Lint fixes

This commit is contained in:
Andrew Murray 2019-02-15 23:25:56 +11:00
parent 45752d2a28
commit 14e7f8a6ed
8 changed files with 84 additions and 77 deletions

View File

@ -34,7 +34,7 @@ if False:
from . import ImagePalette from . import ImagePalette
from .ImageFilter import Filter from .ImageFilter import Filter
from .ImageFile import PyDecoder from .ImageFile import PyDecoder
PyEncoder = Any ## FIXME TYPING: PyEncoder is not defined anywhere? Needs stub/class? PyEncoder = Any # FIXME TYPING: PyEncoder is not defined anywhere? Needs stub/class?
from ._imaging import ImagingCore from ._imaging import ImagingCore
from . import PyAccess, ImageFile from . import PyAccess, ImageFile
@ -118,7 +118,7 @@ try:
__version__)) __version__))
except ImportError as v: except ImportError as v:
core = _imaging_not_installed() # type: ignore core = _imaging_not_installed() # type: ignore
# Explanations for ways that we know we might have an import error # Explanations for ways that we know we might have an import error
if str(v).startswith("Module use of python"): if str(v).startswith("Module use of python"):
# The _imaging C module is present, but not compiled for # The _imaging C module is present, but not compiled for
@ -567,22 +567,22 @@ class Image(object):
* :py:func:`~PIL.Image.new` * :py:func:`~PIL.Image.new`
* :py:func:`~PIL.Image.frombytes` * :py:func:`~PIL.Image.frombytes`
""" """
format = None # type: Optional[Text] format = None # type: Optional[Text]
format_description = None # type: Optional[Text] format_description = None # type: Optional[Text]
_close_exclusive_fp_after_loading = True _close_exclusive_fp_after_loading = True
def __init__(self): def __init__(self):
# type: () -> None # type: () -> None
# FIXME: take "new" parameters / other image? # FIXME: take "new" parameters / other image?
# FIXME: turn mode and size into delegating properties? # FIXME: turn mode and size into delegating properties?
self.im = None # type: Optional[ImagingCore] self.im = None # type: Optional[ImagingCore]
self.mode = "" # type: Mode self.mode = "" # type: Mode
self._size = (0, 0) # type: Size self._size = (0, 0) # type: Size
self.palette = None # type: Optional[ImagePalette.ImagePalette] self.palette = None # type: Optional[ImagePalette.ImagePalette]
self.info = {} # type: Dict[Text, Any] self.info = {} # type: Dict[Text, Any]
self.category = NORMAL self.category = NORMAL
self.readonly = 0 # type: int self.readonly = 0 # type: int
self.pyaccess = None # type: Optional[PyAccess.PyAccess] self.pyaccess = None # type: Optional[PyAccess.PyAccess]
@property @property
def width(self): def width(self):
@ -638,7 +638,7 @@ class Image(object):
# Instead of simply setting to None, we're setting up a # Instead of simply setting to None, we're setting up a
# deferred error that will better explain that the core image # deferred error that will better explain that the core image
# object is gone. # object is gone.
self.im = deferred_error(ValueError("Operation on closed image")) # type: ignore self.im = deferred_error(ValueError("Operation on closed image")) # type: ignore
def _copy(self): def _copy(self):
# type: () -> None # type: () -> None
@ -657,7 +657,7 @@ class Image(object):
# type: (Optional[Text], Optional[Text], **Any) -> Text # type: (Optional[Text], Optional[Text], **Any) -> Text
import tempfile import tempfile
suffix = '' # type: Text suffix = '' # type: Text
if format: if format:
suffix = '.'+format suffix = '.'+format
@ -718,7 +718,7 @@ class Image(object):
def __array_interface__(self): def __array_interface__(self):
# type: () -> ArrayInterfaceStruct # type: () -> ArrayInterfaceStruct
# numpy array interface support # numpy array interface support
new = {} # type: ArrayInterfaceStruct new = {} # type: ArrayInterfaceStruct
shape, typestr = _conv_type_shape(self) shape, typestr = _conv_type_shape(self)
new['shape'] = shape new['shape'] = shape
new['typestr'] = typestr new['typestr'] = typestr
@ -772,7 +772,7 @@ class Image(object):
or individual arguments or individual arguments
:rtype: A bytes object. :rtype: A bytes object.
""" """
encoder_args = args # type: Union[str, Tuple[Any,...], List[Any]] encoder_args = args # type: Union[str, Tuple[Any,...], List[Any]]
# may pass tuple instead of argument list # may pass tuple instead of argument list
if len(args) == 1 and isinstance(args[0], tuple): if len(args) == 1 and isinstance(args[0], tuple):
@ -836,7 +836,7 @@ class Image(object):
but loads data into this image instead of creating a new image object. but loads data into this image instead of creating a new image object.
""" """
decoder_args = args # type: Union[str, Tuple[Any,...], List[Any]] decoder_args = args # type: Union[str, Tuple[Any,...], List[Any]]
# may pass tuple instead of argument list # may pass tuple instead of argument list
if len(args) == 1 and isinstance(args[0], tuple): if len(args) == 1 and isinstance(args[0], tuple):
decoder_args = args[0] decoder_args = args[0]
@ -1239,7 +1239,7 @@ class Image(object):
self.load() self.load()
if callable(kernel): if callable(kernel):
image_filter = kernel() # type: Filter image_filter = kernel() # type: Filter
else: else:
image_filter = kernel image_filter = kernel
if not hasattr(image_filter, "filter"): if not hasattr(image_filter, "filter"):
@ -1296,7 +1296,7 @@ class Image(object):
self.load() self.load()
if self.mode in ("1", "L", "P"): if self.mode in ("1", "L", "P"):
h = self.im.histogram() h = self.im.histogram()
out = [] # type: List[Tuple[int, Color]] out = [] # type: List[Tuple[int, Color]]
for i in range(256): for i in range(256):
if h[i]: if h[i]:
out.append((h[i], i)) out.append((h[i], i))
@ -1344,7 +1344,7 @@ class Image(object):
if self.im.bands > 1: if self.im.bands > 1:
extrema = [] extrema = []
for i in range(self.im.bands): for i in range(self.im.bands):
ex = self.im.getband(i).getextrema() # type: MultiChannelExtrema ex = self.im.getband(i).getextrema() # type: MultiChannelExtrema
extrema.append(ex) extrema.append(ex)
return tuple(extrema) return tuple(extrema)
return self.im.getextrema() return self.im.getextrema()
@ -1372,7 +1372,7 @@ class Image(object):
self.load() self.load()
try: try:
if py3: if py3:
return list(self.im.getpalette()) # type: ignore return list(self.im.getpalette()) # type: ignore
else: else:
return [i8(c) for c in self.im.getpalette()] return [i8(c) for c in self.im.getpalette()]
except ValueError: except ValueError:
@ -1485,16 +1485,16 @@ class Image(object):
:param mask: An optional mask image. :param mask: An optional mask image.
""" """
mask_img = None # type: Optional[Image] mask_img = None # type: Optional[Image]
box_lurd = None # type: Optional[LURD] box_lurd = None # type: Optional[LURD]
box_coord = None # type: Optional[Coord] box_coord = None # type: Optional[Coord]
paste_color = None # type: Optional[Color] paste_color = None # type: Optional[Color]
paste_imcore = None # type: Optional[ImagingCore] paste_imcore = None # type: Optional[ImagingCore]
paste_im = None # type: Optional[Image] paste_im = None # type: Optional[Image]
if isImageType(box) and mask is None: if isImageType(box) and mask is None:
# abbreviated paste(im, mask) syntax # abbreviated paste(im, mask) syntax
mask_img = box # type: ignore mask_img = box # type: ignore
box = None box = None
if box is None: if box is None:
@ -1520,10 +1520,10 @@ class Image(object):
raise ValueError("Incorrect Paste specification") raise ValueError("Incorrect Paste specification")
if len(box) == 4: if len(box) == 4:
box_lurd = box # type: ignore box_lurd = box # type: ignore
elif len(box) == 2: elif len(box) == 2:
# upper left corner given; get size from image or mask # upper left corner given; get size from image or mask
box_coord = box # type: ignore box_coord = box # type: ignore
if paste_im: if paste_im:
size = paste_im.size size = paste_im.size
elif mask_img: elif mask_img:
@ -1533,7 +1533,7 @@ class Image(object):
raise ValueError( raise ValueError(
"cannot determine region size; use 4-item box" "cannot determine region size; use 4-item box"
) )
box_lurd = box_coord + (box_coord[0]+size[0], box_coord[1]+size[1]) # type: ignore box_lurd = box_coord + (box_coord[0]+size[0], box_coord[1]+size[1]) # type: ignore
else: else:
raise ValueError("Incorrect Box specification") raise ValueError("Incorrect Box specification")
@ -1573,22 +1573,22 @@ class Image(object):
if min(dest) < 0: if min(dest) < 0:
raise ValueError("Destination must be non-negative") raise ValueError("Destination must be non-negative")
source_lurd = None # type: LURD source_lurd = None # type: LURD
if len(source) == 2: if len(source) == 2:
source_lurd = source + im.size # type: ignore source_lurd = source + im.size # type: ignore
else: else:
source_lurd = source # type: ignore source_lurd = source # type: ignore
# over image, crop if it's not the whole thing. # over image, crop if it's not the whole thing.
if source_lurd == (0,0) + im.size: if source_lurd == (0, 0) + im.size:
overlay = im overlay = im
else: else:
overlay = im.crop(source_lurd) overlay = im.crop(source_lurd)
# target for the paste # target for the paste
box = None # type: LURD box = None # type: LURD
box = dest + (dest[0] + overlay.width, dest[1] + overlay.height) # type: ignore box = dest + (dest[0] + overlay.width, dest[1] + overlay.height) # type: ignore
# destination image. don't copy if we're using the whole image. # destination image. don't copy if we're using the whole image.
if box == (0, 0) + self.size: if box == (0, 0) + self.size:
@ -1675,10 +1675,10 @@ class Image(object):
else: else:
band = 3 band = 3
alpha_img = None # type: Image alpha_img = None # type: Image
if isImageType(alpha): if isImageType(alpha):
# alpha layer # alpha layer
alpha_img = alpha # type: ignore alpha_img = alpha # type: ignore
if alpha_img.mode not in ("1", "L"): if alpha_img.mode not in ("1", "L"):
raise ValueError("illegal image mode") raise ValueError("illegal image mode")
alpha_img.load() alpha_img.load()
@ -1687,8 +1687,8 @@ class Image(object):
else: else:
# constant alpha # constant alpha
try: try:
alpha_int = None # type: int alpha_int = None # type: int
alpha_int = alpha # type: ignore alpha_int = alpha # type: ignore
self.im.fillband(band, alpha_int) self.im.fillband(band, alpha_int)
except (AttributeError, ValueError): except (AttributeError, ValueError):
# do things the hard way # do things the hard way
@ -1741,7 +1741,7 @@ class Image(object):
if py3: if py3:
data = bytes(data) data = bytes(data)
else: else:
data = "".join(chr(x) for x in data) # type: ignore data = "".join(chr(x) for x in data) # type: ignore
palette = ImagePalette.raw(rawmode, data) palette = ImagePalette.raw(rawmode, data)
self.mode = "P" self.mode = "P"
self.palette = palette self.palette = palette
@ -1888,15 +1888,15 @@ class Image(object):
): ):
raise ValueError("unknown resampling filter") raise ValueError("unknown resampling filter")
size = tuple(size) # type: ignore size = tuple(size) # type: ignore
# Typing note -- historically we've allowed Iterables of # Typing note -- historically we've allowed Iterables of
# len==2 as sizes, but technically they're supposed to be # len==2 as sizes, but technically they're supposed to be
# 2-tuples. # 2-tuples.
if box is None: if box is None:
box = (0, 0) + self.size # type: ignore box = (0, 0) + self.size # type: ignore
else: else:
box = tuple(box) # type: ignore box = tuple(box) # type: ignore
if self.size == size and box == (0, 0) + self.size: if self.size == size and box == (0, 0) + self.size:
return self.copy() return self.copy()
@ -2057,16 +2057,16 @@ class Image(object):
filename = "" filename = ""
open_fp = False open_fp = False
_fp = None # type: BinaryIO _fp = None # type: BinaryIO
if isPath(fp) or (HAS_PATHLIB and isinstance(fp, Path)): if isPath(fp) or (HAS_PATHLIB and isinstance(fp, Path)):
filename = str(fp) filename = str(fp)
open_fp = True open_fp = True
else: else:
_fp = fp # type: ignore _fp = fp # type: ignore
if not filename and hasattr(_fp, "name") and isPath(_fp.name): if not filename and hasattr(_fp, "name") and isPath(_fp.name):
# only set the name for metadata purposes # only set the name for metadata purposes
filename = _fp.name filename = _fp.name
# may mutate self! # may mutate self!
self.load() self.load()
@ -2199,7 +2199,7 @@ class Image(object):
raise ValueError( raise ValueError(
'The image has no channel "{}"'.format(channel)) 'The image has no channel "{}"'.format(channel))
else: else:
channel_int = channel # type: ignore channel_int = channel # type: ignore
return self._new(self.im.getband(channel_int)) return self._new(self.im.getband(channel_int))
@ -2321,7 +2321,7 @@ class Image(object):
if hasattr(method, "getdata"): if hasattr(method, "getdata"):
# compatibility w. old-style transform objects # compatibility w. old-style transform objects
# ignoring for typing, this is old compatibility # ignoring for typing, this is old compatibility
method, data = method.getdata() # type: ignore method, data = method.getdata() # type: ignore
if data is None: if data is None:
raise ValueError("missing method data") raise ValueError("missing method data")
@ -2329,14 +2329,14 @@ class Image(object):
im = new(self.mode, size, fillcolor) im = new(self.mode, size, fillcolor)
if method == MESH: if method == MESH:
# list of quads # list of quads
data_mesh = None # type: List[Tuple[LURD,LURD]] data_mesh = None # type: List[Tuple[LURD,LURD]]
data_mesh = data # type: ignore data_mesh = data # type: ignore
for box, quad in data_mesh: for box, quad in data_mesh:
im.__transformer(box, self, QUAD, quad, resample, im.__transformer(box, self, QUAD, quad, resample,
fillcolor is None) fillcolor is None)
else: else:
box_lurd = None # type: LURD box_lurd = None # type: LURD
box_lurd = (0, 0)+size # type: ignore box_lurd = (0, 0)+size # type: ignore
im.__transformer(box_lurd, self, method, data, im.__transformer(box_lurd, self, method, data,
resample, fillcolor is None) resample, fillcolor is None)
@ -2344,7 +2344,8 @@ class Image(object):
def __transformer(self, box, image, method, data, def __transformer(self, box, image, method, data,
resample=NEAREST, fill=1): resample=NEAREST, fill=1):
# type: (LURD, Image, int, Any, int, Any) -> None # FIXME TYPING: What are Any here? # type: (LURD, Image, int, Any, int, Any) -> None
# FIXME TYPING: What are Any here?
w = box[2] - box[0] w = box[2] - box[0]
h = box[3] - box[1] h = box[3] - box[1]
@ -2443,6 +2444,7 @@ class ImagePointHandler(object):
# type (T) -> T # type (T) -> T
return s return s
class ImageTransformHandler(object): class ImageTransformHandler(object):
# used as a mixin by geometry transforms (for use with im.transform) # used as a mixin by geometry transforms (for use with im.transform)
pass pass
@ -2539,7 +2541,7 @@ def frombytes(mode, size, data, decoder_name="raw", *args):
_check_size(size) _check_size(size)
decoder_args = args # type: Union[str, Tuple[Any,...], List[Any]] decoder_args = args # type: Union[str, Tuple[Any,...], List[Any]]
# may pass tuple instead of argument list # may pass tuple instead of argument list
if len(args) == 1 and isinstance(args[0], tuple): if len(args) == 1 and isinstance(args[0], tuple):
decoder_args = args[0] decoder_args = args[0]
@ -2615,7 +2617,7 @@ def frombuffer(mode, size, data, decoder_name="raw", *args):
# typing -- Getting this to cleanly realize that args is a # typing -- Getting this to cleanly realize that args is a
# correctly formatted tuple is harder than it's worth # correctly formatted tuple is harder than it's worth
im = im._new( im = im._new(
core.map_buffer(data, size, decoder_name, None, 0, args)) # type: ignore core.map_buffer(data, size, decoder_name, None, 0, args)) # type: ignore
im.readonly = 1 im.readonly = 1
return im return im
@ -2672,7 +2674,7 @@ def fromarray(obj, mode=None):
size = shape[1], shape[0] size = shape[1], shape[0]
obj_bytes = None # type: bytes obj_bytes = None # type: bytes
if strides is not None: if strides is not None:
if hasattr(obj, 'tobytes'): if hasattr(obj, 'tobytes'):
obj_bytes = obj.tobytes() obj_bytes = obj.tobytes()
@ -2683,7 +2685,7 @@ def fromarray(obj, mode=None):
# and obj_bytes, if it exists, is a bytes exporting a buffer interface. # and obj_bytes, if it exists, is a bytes exporting a buffer interface.
# Unfortunately at this point, there's no protocol for the buffer interface # Unfortunately at this point, there's no protocol for the buffer interface
# and due to it's c-level implementation, I don't see how to make one. # and due to it's c-level implementation, I don't see how to make one.
return frombuffer(mode, size, obj_bytes or obj, "raw", rawmode, 0, 1) # type: ignore return frombuffer(mode, size, obj_bytes or obj, "raw", rawmode, 0, 1) # type: ignore
def fromqimage(im): def fromqimage(im):
@ -2779,7 +2781,7 @@ def open(fp, mode="r"):
exclusive_fp = False exclusive_fp = False
filename = "" filename = ""
_fp = None # type: BinaryIO _fp = None # type: BinaryIO
if isPath(fp): if isPath(fp):
filename = str(fp) filename = str(fp)
elif HAS_PATHLIB and isinstance(fp, Path): elif HAS_PATHLIB and isinstance(fp, Path):
@ -2789,7 +2791,7 @@ def open(fp, mode="r"):
_fp = builtins.open(filename, "rb") _fp = builtins.open(filename, "rb")
exclusive_fp = True exclusive_fp = True
else: else:
_fp = fp # type: ignore _fp = fp # type: ignore
try: try:
_fp.seek(0) _fp.seek(0)

View File

@ -89,7 +89,7 @@ class ImageFile(Image.Image):
self.decoderconfig = () self.decoderconfig = ()
self.decodermaxblock = MAXBLOCK self.decodermaxblock = MAXBLOCK
self.fp = None # type: Optional[file] self.fp = None # type: Optional[file]
if isPath(fp): if isPath(fp):
# filename # filename
@ -121,8 +121,8 @@ class ImageFile(Image.Image):
if sys.version_info >= (3, 4, 0): if sys.version_info >= (3, 4, 0):
def __del__(self): def __del__(self):
# type: () -> None # type: () -> None
if (hasattr(self, 'fp') and hasattr(self, '_exclusive_fp') if hasattr(self, 'fp') and hasattr(self, '_exclusive_fp') and \
and self.fp and self._exclusive_fp): self.fp and self._exclusive_fp:
self.fp.close() self.fp.close()
self.fp = None self.fp = None

View File

@ -29,6 +29,7 @@ class Filter(object):
def filter(self, image): def filter(self, image):
return image.im return image.im
class MultibandFilter(Filter): class MultibandFilter(Filter):
pass pass

View File

@ -81,8 +81,8 @@ class Viewer(object):
# hook methods # hook methods
format = None # type: str format = None # type: str
options = {} # type: Dict[Any, Any] options = {} # type: Dict[Any, Any]
def get_format(self, image): def get_format(self, image):
"""Return format name, or None to save as PGM/PPM""" """Return format name, or None to save as PGM/PPM"""

View File

@ -855,8 +855,8 @@ class ImageFileDirectory_v2(MutableMapping):
return offset return offset
ImageFileDirectory_v2._load_dispatch = _load_dispatch # type: ignore ImageFileDirectory_v2._load_dispatch = _load_dispatch # type: ignore
ImageFileDirectory_v2._write_dispatch = _write_dispatch # type: ignore ImageFileDirectory_v2._write_dispatch = _write_dispatch # type: ignore
for idx, name in TYPES.items(): for idx, name in TYPES.items():
name = name.replace(" ", "_") name = name.replace(" ", "_")
setattr(ImageFileDirectory_v2, "load_" + name, _load_dispatch[idx][1]) setattr(ImageFileDirectory_v2, "load_" + name, _load_dispatch[idx][1])

View File

@ -22,8 +22,9 @@ from collections import namedtuple
if False: if False:
from typing import Dict, List, Text from typing import Dict, List, Text
class TagInfo(namedtuple("_TagInfo", "value name type length enum")): class TagInfo(namedtuple("_TagInfo", "value name type length enum")):
__slots__ = [] # type: List[Text] __slots__ = [] # type: List[Text]
def __new__(cls, value=None, name="unknown", def __new__(cls, value=None, name="unknown",
type=None, length=None, enum=None): type=None, length=None, enum=None):
@ -370,7 +371,7 @@ _populate()
## ##
# Map type numbers to type names -- defined in ImageFileDirectory. # Map type numbers to type names -- defined in ImageFileDirectory.
TYPES = {} # type: Dict[int, Text] TYPES = {} # type: Dict[int, Text]
# was: # was:
# TYPES = { # TYPES = {

View File

@ -7,17 +7,20 @@ XY = Tuple[int, int]
Coord = XY Coord = XY
Size = XY # NOTE: All XY aliases will be interchangeable Size = XY # NOTE: All XY aliases will be interchangeable
Matrix4 = Tuple[float, float, float, float] Matrix4 = Tuple[float, float, float, float]
Matrix12 = Tuple[float, float, float, float, float, float, float, float, float, float, float, float] Matrix12 = Tuple[float, float, float, float, float, float,
float, float, float, float, float, float]
Mode = str Mode = str
SingleChannelExtrema = Union[Tuple[float, float], Tuple[int, int]] SingleChannelExtrema = Union[Tuple[float, float], Tuple[int, int]]
MultiChannelExtrema = SingleChannelExtrema # Note: currently only a Tuple[int,int] MultiChannelExtrema = SingleChannelExtrema # Note: currently only a Tuple[int,int]
Extrema = Union[SingleChannelExtrema, Tuple[MultiChannelExtrema, ...]] Extrema = Union[SingleChannelExtrema, Tuple[MultiChannelExtrema, ...]]
Color = Union[int, float, Tuple[int, int], Tuple[int, int, int], Tuple[int, int, int, int]] Color = Union[int, float, Tuple[int, int], Tuple[int, int, int],
Tuple[int, int, int, int]]
ArrayInterfaceStruct = Dict[unicode, Any] ArrayInterfaceStruct = Dict[unicode, Any]
class SupportsArrayInterface(Protocol): class SupportsArrayInterface(Protocol):
@abstractproperty @abstractproperty
def __array_interface__(self): def __array_interface__(self):