From d1c182cadcf903b347c89f5e2a0796167e726c87 Mon Sep 17 00:00:00 2001
From: Andrew Murray <radarhere@gmail.com>
Date: Fri, 24 Apr 2015 09:26:52 +1000
Subject: [PATCH 1/3] Various Flake8 fixes

---
 PIL/FitsStubImagePlugin.py       |   3 +
 PIL/FpxImagePlugin.py            |   4 +-
 PIL/Image.py                     |   4 +-
 PIL/ImageEnhance.py              |   1 +
 PIL/ImageQt.py                   |   3 +-
 PIL/JpegImagePlugin.py           |   2 +-
 PIL/JpegPresets.py               |  18 ++--
 PIL/OleFileIO.py                 | 151 +++++++++++++------------------
 PIL/PcxImagePlugin.py            |  10 +-
 PIL/PngImagePlugin.py            |   1 +
 PIL/PyAccess.py                  |   2 +-
 PIL/TiffImagePlugin.py           |  22 ++---
 Tests/bench_cffi_access.py       |   2 +-
 Tests/check_imaging_leaks.py     |   2 +-
 Tests/check_jpeg_leaks.py        |   7 +-
 Tests/check_png_dos.py           |  11 ++-
 Tests/check_webp_leaks.py        |   2 +-
 Tests/helper.py                  |   2 +-
 Tests/test_binary.py             |   7 +-
 Tests/test_file_eps.py           |  26 +++---
 Tests/test_file_icns.py          |   8 +-
 Tests/test_file_ico.py           |   9 +-
 Tests/test_file_jpeg.py          |  11 +--
 Tests/test_file_libtiff.py       |  14 +--
 Tests/test_file_png.py           |   3 +-
 Tests/test_file_tiff.py          |  12 +--
 Tests/test_file_tiff_metadata.py |   2 +-
 Tests/test_file_webp_metadata.py |   1 -
 Tests/test_file_xpm.py           |   2 +-
 Tests/test_image_putdata.py      |   6 +-
 Tests/test_image_resize.py       |   6 +-
 Tests/test_image_transpose.py    |   2 +-
 Tests/test_imagecms.py           |   5 +-
 Tests/test_imagedraw.py          |   8 +-
 Tests/test_imageenhance.py       |  15 ++-
 Tests/test_imagefile.py          |   2 +-
 Tests/test_imagefont_bitmap.py   |   7 +-
 Tests/test_imagesequence.py      |   8 +-
 Tests/test_numpy.py              |   4 +-
 Tests/test_scipy.py              |  26 +++---
 40 files changed, 201 insertions(+), 230 deletions(-)

diff --git a/PIL/FitsStubImagePlugin.py b/PIL/FitsStubImagePlugin.py
index 0b851ae59..7aefff212 100644
--- a/PIL/FitsStubImagePlugin.py
+++ b/PIL/FitsStubImagePlugin.py
@@ -18,6 +18,7 @@ _handler = None
 #
 # @param handler Handler object.
 
+
 def register_handler(handler):
     global _handler
     _handler = handler
@@ -25,9 +26,11 @@ def register_handler(handler):
 # --------------------------------------------------------------------
 # Image adapter
 
+
 def _accept(prefix):
     return prefix[:6] == b"SIMPLE"
 
+
 class FITSStubImageFile(ImageFile.StubImageFile):
 
     format = "FITS"
diff --git a/PIL/FpxImagePlugin.py b/PIL/FpxImagePlugin.py
index ed0c20c4e..9d338d9da 100644
--- a/PIL/FpxImagePlugin.py
+++ b/PIL/FpxImagePlugin.py
@@ -136,9 +136,9 @@ class FpxImageFile(ImageFile.ImageFile):
         s = fp.read(36)
 
         size = i32(s, 4), i32(s, 8)
-        #tilecount = i32(s, 12)
+        # tilecount = i32(s, 12)
         tilesize = i32(s, 16), i32(s, 20)
-        #channels = i32(s, 24)
+        # channels = i32(s, 24)
         offset = i32(s, 28)
         length = i32(s, 32)
 
diff --git a/PIL/Image.py b/PIL/Image.py
index 7cfa72e6f..9c459dfb1 100644
--- a/PIL/Image.py
+++ b/PIL/Image.py
@@ -387,7 +387,7 @@ def init():
     for plugin in _plugins:
         try:
             if DEBUG:
-                print ("Importing %s" % plugin)
+                print("Importing %s" % plugin)
             __import__("PIL.%s" % plugin, globals(), locals(), [])
         except ImportError:
             if DEBUG:
@@ -546,7 +546,7 @@ class Image:
             self.fp.close()
         except Exception as msg:
             if DEBUG:
-                print ("Error closing: %s" % msg)
+                print("Error closing: %s" % msg)
 
         # Instead of simply setting to None, we're setting up a
         # deferred error that will better explain that the core image
diff --git a/PIL/ImageEnhance.py b/PIL/ImageEnhance.py
index a196d5b09..8c0f166f3 100644
--- a/PIL/ImageEnhance.py
+++ b/PIL/ImageEnhance.py
@@ -53,6 +53,7 @@ class Color(_Enhance):
 
         self.degenerate = image.convert(self.intermediate_mode).convert(image.mode)
 
+
 class Contrast(_Enhance):
     """Adjust image contrast.
 
diff --git a/PIL/ImageQt.py b/PIL/ImageQt.py
index 22ee2ea8f..1723e3226 100644
--- a/PIL/ImageQt.py
+++ b/PIL/ImageQt.py
@@ -29,12 +29,13 @@ if 'PyQt4.QtGui' not in sys.modules:
         except:
             from PySide.QtGui import QImage, qRgba
 
-else: #PyQt4 is used
+else:  #PyQt4 is used
     from PyQt4.QtGui import QImage, qRgba
 
 ##
 # (Internal) Turns an RGB color into a Qt compatible color integer.
 
+
 def rgb(r, g, b, a=255):
     # use qRgb to pack the colors, and then turn the resulting long
     # into a negative integer with the same bitpattern.
diff --git a/PIL/JpegImagePlugin.py b/PIL/JpegImagePlugin.py
index 8c20f5863..0ecc902e4 100644
--- a/PIL/JpegImagePlugin.py
+++ b/PIL/JpegImagePlugin.py
@@ -684,7 +684,7 @@ def _save(im, fp, filename):
     # https://github.com/jdriscoll/django-imagekit/issues/50
     bufsize = 0
     if "optimize" in info or "progressive" in info or "progression" in info:
-        # keep sets quality to 0, but the actual value may be high. 
+        # keep sets quality to 0, but the actual value may be high.
         if quality >= 95 or quality == 0:
             bufsize = 2 * im.size[0] * im.size[1]
         else:
diff --git a/PIL/JpegPresets.py b/PIL/JpegPresets.py
index 6ca46d0cd..67af9ac9a 100644
--- a/PIL/JpegPresets.py
+++ b/PIL/JpegPresets.py
@@ -67,7 +67,7 @@ Libjpeg ref.: http://www.jpegcameras.com/libjpeg/libjpeg-3.html
 """
 
 presets = {
-            'web_low':      {'subsampling':  2, # "4:1:1"
+            'web_low':      {'subsampling':  2,  # "4:1:1"
                             'quantization': [
                                [20, 16, 25, 39, 50, 46, 62, 68,
                                 16, 18, 23, 38, 38, 53, 65, 68,
@@ -86,7 +86,7 @@ presets = {
                                 68, 68, 68, 68, 68, 68, 68, 68,
                                 68, 68, 68, 68, 68, 68, 68, 68]
                             ]},
-            'web_medium':   {'subsampling':  2, # "4:1:1"
+            'web_medium':   {'subsampling':  2,  # "4:1:1"
                             'quantization': [
                                [16, 11, 11, 16, 23, 27, 31, 30,
                                 11, 12, 12, 15, 20, 23, 23, 30,
@@ -105,7 +105,7 @@ presets = {
                                 38, 35, 46, 53, 64, 64, 64, 64,
                                 48, 43, 53, 64, 64, 64, 64, 64]
                             ]},
-            'web_high':     {'subsampling':  0, # "4:4:4"
+            'web_high':     {'subsampling':  0,  # "4:4:4"
                             'quantization': [
                                [ 6,  4,  4,  6,  9, 11, 12, 16,
                                  4,  5,  5,  6,  8, 10, 12, 12,
@@ -124,7 +124,7 @@ presets = {
                                 31, 31, 31, 31, 31, 31, 31, 31,
                                 31, 31, 31, 31, 31, 31, 31, 31]
                             ]},
-            'web_very_high': {'subsampling':  0, # "4:4:4"
+            'web_very_high': {'subsampling':  0,  # "4:4:4"
                             'quantization': [
                                [ 2,  2,  2,  2,  3,  4,  5,  6,
                                  2,  2,  2,  2,  3,  4,  5,  6,
@@ -143,7 +143,7 @@ presets = {
                                 15, 12, 12, 12, 12, 12, 12, 12,
                                 15, 12, 12, 12, 12, 12, 12, 12]
                             ]},
-            'web_maximum':  {'subsampling':  0, # "4:4:4"
+            'web_maximum':  {'subsampling':  0,  # "4:4:4"
                             'quantization': [
                                [ 1,  1,  1,  1,  1,  1,  1,  1,
                                  1,  1,  1,  1,  1,  1,  1,  1,
@@ -162,7 +162,7 @@ presets = {
                                  3,  3,  3,  3,  3,  3,  3,  3,
                                  3,  3,  3,  3,  3,  3,  3,  3]
                             ]},
-            'low':          {'subsampling':  2, # "4:1:1"
+            'low':          {'subsampling':  2,  # "4:1:1"
                             'quantization': [
                                [18, 14, 14, 21, 30, 35, 34, 17,
                                 14, 16, 16, 19, 26, 23, 12, 12,
@@ -181,7 +181,7 @@ presets = {
                                 17, 12, 12, 12, 12, 12, 12, 12,
                                 17, 12, 12, 12, 12, 12, 12, 12]
                             ]},
-            'medium':       {'subsampling':  2, # "4:1:1"
+            'medium':       {'subsampling':  2,  # "4:1:1"
                             'quantization': [
                                [12,  8,  8, 12, 17, 21, 24, 17,
                                  8,  9,  9, 11, 15, 19, 12, 12,
@@ -200,7 +200,7 @@ presets = {
                                 17, 12, 12, 12, 12, 12, 12, 12,
                                 17, 12, 12, 12, 12, 12, 12, 12]
                             ]},
-            'high':         {'subsampling':  0, # "4:4:4"
+            'high':         {'subsampling':  0,  # "4:4:4"
                             'quantization': [
                                [ 6,  4,  4,  6,  9, 11, 12, 16,
                                  4,  5,  5,  6,  8, 10, 12, 12,
@@ -219,7 +219,7 @@ presets = {
                                 17, 12, 12, 12, 12, 12, 12, 12,
                                 17, 12, 12, 12, 12, 12, 12, 12]
                             ]},
-            'maximum':      {'subsampling':  0, # "4:4:4"
+            'maximum':      {'subsampling':  0,  # "4:4:4"
                             'quantization': [
                                [ 2,  2,  2,  2,  3,  4,  5,  6,
                                  2,  2,  2,  2,  3,  4,  5,  6,
diff --git a/PIL/OleFileIO.py b/PIL/OleFileIO.py
index a08ae0ee3..a94b760c8 100755
--- a/PIL/OleFileIO.py
+++ b/PIL/OleFileIO.py
@@ -28,7 +28,7 @@
 # This import enables print() as a function rather than a keyword
 # (main requirement to be compatible with Python 3.x)
 # The comment on the line below should be printed on Python 2.5 or older:
-from __future__ import print_function # This version of OleFileIO_PL requires Python 2.6+ or 3.x.
+from __future__ import print_function  # This version of OleFileIO_PL requires Python 2.6+ or 3.x.
 
 
 __author__  = "Philippe Lagadec, Fredrik Lundh (Secret Labs AB)"
@@ -234,7 +234,10 @@ __version__ = '0.30'
 
 import io
 import sys
-import struct, array, os.path, datetime
+import struct
+import array
+import os.path
+import datetime
 
 #[PL] Define explicitly the public API to avoid private objects in pydoc:
 __all__ = ['OleFileIO', 'isOleFile', 'MAGIC']
@@ -283,12 +286,17 @@ KEEP_UNICODE_NAMES = False
 #[PL] DEBUG display mode: False by default, use set_debug_mode() or "-d" on
 # command line to change it.
 DEBUG_MODE = False
+
+
 def debug_print(msg):
     print(msg)
+
+
 def debug_pass(msg):
     pass
 debug = debug_pass
 
+
 def set_debug_mode(debug_mode):
     """
     Set debug mode on or off, to control display of debugging messages.
@@ -303,24 +311,24 @@ def set_debug_mode(debug_mode):
 
 MAGIC = b'\xD0\xCF\x11\xE0\xA1\xB1\x1A\xE1'
 
-#[PL]: added constants for Sector IDs (from AAF specifications)
+# [PL]: added constants for Sector IDs (from AAF specifications)
 MAXREGSECT = 0xFFFFFFFA; # maximum SECT
 DIFSECT    = 0xFFFFFFFC; # (-4) denotes a DIFAT sector in a FAT
 FATSECT    = 0xFFFFFFFD; # (-3) denotes a FAT sector in a FAT
 ENDOFCHAIN = 0xFFFFFFFE; # (-2) end of a virtual stream chain
 FREESECT   = 0xFFFFFFFF; # (-1) unallocated sector
 
-#[PL]: added constants for Directory Entry IDs (from AAF specifications)
+# [PL]: added constants for Directory Entry IDs (from AAF specifications)
 MAXREGSID  = 0xFFFFFFFA; # maximum directory entry ID
 NOSTREAM   = 0xFFFFFFFF; # (-1) unallocated directory entry
 
-#[PL] object types in storage (from AAF specifications)
-STGTY_EMPTY     = 0 # empty directory entry (according to OpenOffice.org doc)
-STGTY_STORAGE   = 1 # element is a storage object
-STGTY_STREAM    = 2 # element is a stream object
-STGTY_LOCKBYTES = 3 # element is an ILockBytes object
-STGTY_PROPERTY  = 4 # element is an IPropertyStorage object
-STGTY_ROOT      = 5 # element is a root storage
+# [PL] object types in storage (from AAF specifications)
+STGTY_EMPTY     = 0  # empty directory entry (according to OpenOffice.org doc)
+STGTY_STORAGE   = 1  # element is a storage object
+STGTY_STREAM    = 2  # element is a stream object
+STGTY_LOCKBYTES = 3  # element is an ILockBytes object
+STGTY_PROPERTY  = 4  # element is an IPropertyStorage object
+STGTY_ROOT      = 5  # element is a root storage
 
 
 #
@@ -370,7 +378,7 @@ for key in list(vars().keys()):
 def isOleFile (filename):
     """
     Test if file is an OLE container (according to its header).
-    
+
     :param filename: file name or path (str, unicode)
     :returns: True if OLE, False otherwise.
     """
@@ -433,7 +441,6 @@ def _clsid(clsid):
             tuple(map(i8, clsid[8:16]))))
 
 
-
 # UNICODE support:
 # (necessary to handle storages/streams names which use Unicode)
 
@@ -471,7 +478,6 @@ def filetime2datetime(filetime):
         return _FILETIME_null_date + datetime.timedelta(microseconds=filetime//10)
 
 
-
 #=== CLASSES ==================================================================
 
 class OleMetadata:
@@ -579,7 +585,6 @@ class OleMetadata:
         self.language = None
         self.doc_version = None
 
-
     def parse_properties(self, olefile):
         """
         Parse standard properties of an OLE file, from the streams
@@ -663,7 +668,7 @@ class _OleStream(io.BytesIO):
         """
         debug('_OleStream.__init__:')
         debug('  sect=%d (%X), size=%d, offset=%d, sectorsize=%d, len(fat)=%d, fp=%s'
-            %(sect,sect,size,offset,sectorsize,len(fat), repr(fp)))
+            %(sect, sect, size, offset, sectorsize, len(fat), repr(fp)))
         #[PL] To detect malformed documents with FAT loops, we compute the
         # expected number of sectors in the stream:
         unknown_size = False
@@ -789,7 +794,6 @@ class _OleDirectoryEntry:
     DIRENTRY_SIZE = 128
     assert struct.calcsize(STRUCT_DIRENTRY) == DIRENTRY_SIZE
 
-
     def __init__(self, entry, sid, olefile):
         """
         Constructor for an _OleDirectoryEntry object.
@@ -882,8 +886,6 @@ class _OleDirectoryEntry:
                 minifat = False
             olefile._check_duplicate_stream(self.isectStart, minifat)
 
-
-
     def build_storage_tree(self):
         """
         Read and build the red-black tree attached to this _OleDirectoryEntry
@@ -907,7 +909,6 @@ class _OleDirectoryEntry:
             # (see rich comparison methods in this class)
             self.kids.sort()
 
-
     def append_kids(self, child_sid):
         """
         Walk through red-black tree of children of this directory entry to add
@@ -916,7 +917,7 @@ class _OleDirectoryEntry:
         child_sid : index of child directory entry to use, or None when called
                     first time for the root. (only used during recursion)
         """
-        #[PL] this method was added to use simple recursion instead of a complex
+        # [PL] this method was added to use simple recursion instead of a complex
         # algorithm.
         # if this is not a storage or a leaf of the tree, nothing to do:
         if child_sid == NOSTREAM:
@@ -951,7 +952,6 @@ class _OleDirectoryEntry:
         # Afterwards build kid's own tree if it's also a storage:
         child.build_storage_tree()
 
-
     def __eq__(self, other):
         "Compare entries by name"
         return self.name == other.name
@@ -971,7 +971,6 @@ class _OleDirectoryEntry:
     #TODO: replace by the same function as MS implementation ?
     # (order by name length first, then case-insensitive order)
 
-
     def dump(self, tab = 0):
         "Dump this entry, and all its subentries (for debug purposes only)"
         TYPES = ["(invalid)", "(storage)", "(stream)", "(lockbytes)",
@@ -986,7 +985,6 @@ class _OleDirectoryEntry:
         for kid in self.kids:
             kid.dump(tab + 2)
 
-
     def getmtime(self):
         """
         Return modification time of a directory entry.
@@ -1000,7 +998,6 @@ class _OleDirectoryEntry:
             return None
         return filetime2datetime(self.modifyTime)
 
-
     def getctime(self):
         """
         Return creation time of a directory entry.
@@ -1064,7 +1061,6 @@ class OleFileIO:
         if filename:
             self.open(filename)
 
-
     def _raise_defect(self, defect_level, message, exception_type=IOError):
         """
         This method should be called for any defect found during file parsing.
@@ -1086,7 +1082,6 @@ class OleFileIO:
             # just record the issue, no exception raised:
             self.parsing_issues.append((exception_type, message))
 
-
     def open(self, filename):
         """
         Open an OLE2 file.
@@ -1189,7 +1184,7 @@ class OleFileIO:
             self.sectDifStart,
             self.csectDif
         ) = struct.unpack(fmt_header, header1)
-        debug( struct.unpack(fmt_header,    header1))
+        debug(struct.unpack(fmt_header, header1))
 
         if self.Sig != MAGIC:
             # OLE signature should always be present
@@ -1231,11 +1226,11 @@ class OleFileIO:
         # rule => only a potential defect:
         if self.signature != 0:
             self._raise_defect(DEFECT_POTENTIAL, "incorrect OLE header (signature>0)")
-        debug( "MiniSectorCutoff = %d" % self.MiniSectorCutoff )
-        debug( "MiniFatStart     = %X" % self.MiniFatStart )
-        debug( "csectMiniFat     = %d" % self.csectMiniFat )
-        debug( "sectDifStart     = %X" % self.sectDifStart )
-        debug( "csectDif         = %d" % self.csectDif )
+        debug("MiniSectorCutoff = %d" % self.MiniSectorCutoff)
+        debug("MiniFatStart     = %X" % self.MiniFatStart)
+        debug("csectMiniFat     = %d" % self.csectMiniFat)
+        debug("sectDifStart     = %X" % self.sectDifStart)
+        debug("csectDif         = %d" % self.csectDif)
 
         # calculate the number of sectors in the file
         # (-1 because header doesn't count)
@@ -1266,14 +1261,12 @@ class OleFileIO:
         self.ministream = None
         self.minifatsect = self.MiniFatStart #i32(header, 60)
 
-
     def close(self):
         """
         close the OLE file, to release the file object
         """
         self.fp.close()
 
-
     def _check_duplicate_stream(self, first_sect, minifat=False):
         """
         Checks if a stream has not been already referenced elsewhere.
@@ -1298,7 +1291,6 @@ class OleFileIO:
         else:
             used_streams.append(first_sect)
 
-
     def dumpfat(self, fat, firstindex=0):
         "Displays a part of FAT in human-readable form for debugging purpose"
         # [PL] added only for debug
@@ -1335,7 +1327,6 @@ class OleFileIO:
                 print(nom, end=" ")
             print()
 
-
     def dumpsect(self, sector, firstindex=0):
         "Displays a sector in a human-readable form, for debugging purpose."
         if not DEBUG_MODE:
@@ -1370,11 +1361,10 @@ class OleFileIO:
             a.byteswap()
         return a
 
-
     def loadfat_sect(self, sect):
         """
         Adds the indexes of the given sector to the FAT
-        
+
         :param sect: string containing the first FAT sector, or array of long integers
         :returns: index of last FAT sector.
         """
@@ -1400,7 +1390,6 @@ class OleFileIO:
             self.fat = self.fat + nextfat
         return isect
 
-
     def loadfat(self, header):
         """
         Load the FAT table.
@@ -1436,16 +1425,16 @@ class OleFileIO:
             if self.sectDifStart >= self.nb_sect:
                 # initial DIFAT block index must be valid
                 self._raise_defect(DEFECT_FATAL, 'incorrect DIFAT, first index out of range')
-            debug( "DIFAT analysis..." )
+            debug("DIFAT analysis...")
             # We compute the necessary number of DIFAT sectors :
             # (each DIFAT sector = 127 pointers + 1 towards next DIFAT sector)
             nb_difat = (self.csectFat-109 + 126)//127
-            debug( "nb_difat = %d" % nb_difat )
+            debug("nb_difat = %d" % nb_difat)
             if self.csectDif != nb_difat:
                 raise IOError('incorrect DIFAT')
             isect_difat = self.sectDifStart
             for i in iterrange(nb_difat):
-                debug( "DIFAT block %d, sector %X" % (i, isect_difat) )
+                debug("DIFAT block %d, sector %X" % (i, isect_difat))
                 #TODO: check if corresponding FAT SID = DIFSECT
                 sector_difat = self.getsect(isect_difat)
                 difat = self.sect2array(sector_difat)
@@ -1453,7 +1442,7 @@ class OleFileIO:
                 self.loadfat_sect(difat[:127])
                 # last DIFAT pointer is next DIFAT sector:
                 isect_difat = difat[127]
-                debug( "next DIFAT sector: %X" % isect_difat )
+                debug("next DIFAT sector: %X" % isect_difat)
             # checks:
             if isect_difat not in [ENDOFCHAIN, FREESECT]:
                 # last DIFAT pointer value must be ENDOFCHAIN or FREESECT
@@ -1471,7 +1460,6 @@ class OleFileIO:
         debug('\nFAT:')
         self.dumpfat(self.fat)
 
-
     def loadminifat(self):
         """
         Load the MiniFAT table.
@@ -1509,7 +1497,7 @@ class OleFileIO:
     def getsect(self, sect):
         """
         Read given sector from file on disk.
-        
+
         :param sect: sector index
         :returns: a string containing the sector data.
         """
@@ -1531,11 +1519,10 @@ class OleFileIO:
             self._raise_defect(DEFECT_FATAL, 'incomplete OLE sector')
         return sector
 
-
     def loaddirectory(self, sect):
         """
         Load the directory.
-        
+
         :param sect: sector index of directory stream.
         """
         # The directory is  stored in a standard
@@ -1567,7 +1554,6 @@ class OleFileIO:
         # read and build all storage trees, starting from the root:
         self.root.build_storage_tree()
 
-
     def _load_direntry (self, sid):
         """
         Load a directory entry from the directory.
@@ -1592,14 +1578,12 @@ class OleFileIO:
         self.direntries[sid] = _OleDirectoryEntry(entry, sid, self)
         return self.direntries[sid]
 
-
     def dumpdirectory(self):
         """
         Dump directory (for debugging only)
         """
         self.root.dump()
 
-
     def _open(self, start, size = 0x7FFFFFFF, force_FAT=False):
         """
         Open a stream, either in FAT or MiniFAT according to its size.
@@ -1633,7 +1617,6 @@ class OleFileIO:
             return _OleStream(self.fp, start, size, 512,
                               self.sectorsize, self.fat, self._filesize)
 
-
     def _list(self, files, prefix, node, streams=True, storages=False):
         """
         (listdir helper)
@@ -1659,7 +1642,6 @@ class OleFileIO:
                     # add it to the list
                     files.append(prefix[1:] + [entry.name])
 
-
     def listdir(self, streams=True, storages=False):
         """
         Return a list of streams stored in this file
@@ -1672,14 +1654,13 @@ class OleFileIO:
         self._list(files, [], self.root, streams, storages)
         return files
 
-
     def _find(self, filename):
         """
         Returns directory entry of given filename. (openstream helper)
         Note: this method is case-insensitive.
 
         :param filename: path of stream in storage tree (except root entry), either:
-        
+
             - a string using Unix path syntax, for example:
               'storage_1/storage_1.2/stream'
             - a list of storage filenames, path to the desired stream/storage.
@@ -1703,18 +1684,17 @@ class OleFileIO:
             node = kid
         return node.sid
 
-
     def openstream(self, filename):
         """
         Open a stream as a read-only file object (BytesIO).
 
         :param filename: path of stream in storage tree (except root entry), either:
-        
+
             - a string using Unix path syntax, for example:
               'storage_1/storage_1.2/stream'
             - a list of storage filenames, path to the desired stream/storage.
               Example: ['storage_1', 'storage_1.2', 'stream']
-              
+
         :returns: file object (read-only)
         :exception IOError: if filename not found, or if this is not a stream.
         """
@@ -1724,7 +1704,6 @@ class OleFileIO:
             raise IOError("this file is not a stream")
         return self._open(entry.isectStart, entry.size)
 
-
     def get_type(self, filename):
         """
         Test if given filename exists as a stream or a storage in the OLE
@@ -1732,7 +1711,7 @@ class OleFileIO:
 
         :param filename: path of stream in storage tree. (see openstream for syntax)
         :returns: False if object does not exist, its entry type (>0) otherwise:
-        
+
             - STGTY_STREAM: a stream
             - STGTY_STORAGE: a storage
             - STGTY_ROOT: the root entry
@@ -1744,7 +1723,6 @@ class OleFileIO:
         except:
             return False
 
-
     def getmtime(self, filename):
         """
         Return modification time of a stream/storage.
@@ -1760,7 +1738,6 @@ class OleFileIO:
         entry = self.direntries[sid]
         return entry.getmtime()
 
-
     def getctime(self, filename):
         """
         Return creation time of a stream/storage.
@@ -1776,7 +1753,6 @@ class OleFileIO:
         entry = self.direntries[sid]
         return entry.getctime()
 
-
     def exists(self, filename):
         """
         Test if given filename exists as a stream or a storage in the OLE
@@ -1791,7 +1767,6 @@ class OleFileIO:
         except:
             return False
 
-
     def get_size(self, filename):
         """
         Return size of a stream in the OLE container, in bytes.
@@ -1808,7 +1783,6 @@ class OleFileIO:
             raise TypeError('object is not an OLE stream')
         return entry.size
 
-
     def get_rootentry_name(self):
         """
         Return root entry name. Should usually be 'Root Entry' or 'R' in most
@@ -1816,7 +1790,6 @@ class OleFileIO:
         """
         return self.root.name
 
-
     def getproperties(self, filename, convert_time=False, no_conversion=None):
         """
         Return properties described in substream.
@@ -1828,7 +1801,7 @@ class OleFileIO:
         :returns: a dictionary of values indexed by id (integer)
         """
         # make sure no_conversion is a list, just to simplify code below:
-        if no_conversion == None:
+        if no_conversion is None:
             no_conversion = []
         # stream path as a string to report exceptions:
         streampath = filename
@@ -1842,11 +1815,11 @@ class OleFileIO:
         try:
             # header
             s = fp.read(28)
-            #clsid = _clsid(s[8:24])
+            # clsid = _clsid(s[8:24])
 
             # format id
             s = fp.read(20)
-            #fmtid = _clsid(s[:16])
+            # fmtid = _clsid(s[:16])
             fp.seek(i32(s, 16))
 
             # get section
@@ -1864,34 +1837,34 @@ class OleFileIO:
 
         for i in range(num_props):
             try:
-                id = 0 # just in case of an exception
+                id = 0  # just in case of an exception
                 id = i32(s, 8+i*8)
                 offset = i32(s, 12+i*8)
                 type = i32(s, offset)
 
-                debug ('property id=%d: type=%d offset=%X' % (id, type, offset))
+                debug('property id=%d: type=%d offset=%X' % (id, type, offset))
 
                 # test for common types first (should perhaps use
                 # a dictionary instead?)
 
-                if type == VT_I2: # 16-bit signed integer
+                if type == VT_I2:  # 16-bit signed integer
                     value = i16(s, offset+4)
                     if value >= 32768:
                         value = value - 65536
-                elif type == VT_UI2: # 2-byte unsigned integer
+                elif type == VT_UI2:  # 2-byte unsigned integer
                     value = i16(s, offset+4)
                 elif type in (VT_I4, VT_INT, VT_ERROR):
                     # VT_I4: 32-bit signed integer
                     # VT_ERROR: HRESULT, similar to 32-bit signed integer,
                     # see http://msdn.microsoft.com/en-us/library/cc230330.aspx
                     value = i32(s, offset+4)
-                elif type in (VT_UI4, VT_UINT): # 4-byte unsigned integer
-                    value = i32(s, offset+4) # FIXME
+                elif type in (VT_UI4, VT_UINT):  # 4-byte unsigned integer
+                    value = i32(s, offset+4)  # FIXME
                 elif type in (VT_BSTR, VT_LPSTR):
                     # CodePageString, see http://msdn.microsoft.com/en-us/library/dd942354.aspx
                     # size is a 32 bits integer, including the null terminator, and
                     # possibly trailing or embedded null chars
-                    #TODO: if codepage is unicode, the string should be converted as such
+                    # TODO: if codepage is unicode, the string should be converted as such
                     count = i32(s, offset+4)
                     value = s[offset+8:offset+8+count-1]
                     # remove all null chars:
@@ -1909,7 +1882,7 @@ class OleFileIO:
                     count = i32(s, offset+4)
                     value = _unicode(s[offset+8:offset+8+count*2])
                 elif type == VT_FILETIME:
-                    value = long(i32(s, offset+4)) + (long(i32(s, offset+8))<<32)
+                    value = long(i32(s, offset+4)) + (long(i32(s, offset+8)) << 32)
                     # FILETIME is a 64-bit int: "number of 100ns periods
                     # since Jan 1,1601".
                     if convert_time and id not in no_conversion:
@@ -1923,8 +1896,8 @@ class OleFileIO:
                     else:
                         # legacy code kept for backward compatibility: returns a
                         # number of seconds since Jan 1,1601
-                        value = value // 10000000 # seconds
-                elif type == VT_UI1: # 1-byte unsigned integer
+                        value = value // 10000000  # seconds
+                elif type == VT_UI1:  # 1-byte unsigned integer
                     value = i8(s[offset+4])
                 elif type == VT_CLSID:
                     value = _clsid(s[offset+4:offset+20])
@@ -1938,8 +1911,8 @@ class OleFileIO:
                     # see http://msdn.microsoft.com/en-us/library/cc237864.aspx
                     value = bool(i16(s, offset+4))
                 else:
-                    value = None # everything else yields "None"
-                    debug ('property id=%d: type=%d not implemented in parser yet' % (id, type))
+                    value = None  # everything else yields "None"
+                    debug('property id=%d: type=%d not implemented in parser yet' % (id, type))
 
                 # missing: VT_EMPTY, VT_NULL, VT_R4, VT_R8, VT_CY, VT_DATE,
                 # VT_DECIMAL, VT_I1, VT_I8, VT_UI8,
@@ -1951,8 +1924,8 @@ class OleFileIO:
                 # type of items, e.g. VT_VECTOR|VT_BSTR
                 # see http://msdn.microsoft.com/en-us/library/dd942011.aspx
 
-                #print("%08x" % id, repr(value), end=" ")
-                #print("(%s)" % VT[i32(s, offset) & 0xFFF])
+                # print("%08x" % id, repr(value), end=" ")
+                # print("(%s)" % VT[i32(s, offset) & 0xFFF])
 
                 data[id] = value
             except BaseException as exc:
@@ -1999,7 +1972,7 @@ Options:
 
     check_streams = False
     for filename in sys.argv[1:]:
-        #try:
+        # try:
         # OPTIONS:
         if filename == '-d':
             # option to switch debug mode on:
@@ -2010,7 +1983,7 @@ Options:
             check_streams = True
             continue
 
-        ole = OleFileIO(filename)#, raise_defects=DEFECT_INCORRECT)
+        ole = OleFileIO(filename)  #, raise_defects=DEFECT_INCORRECT)
         print("-" * 68)
         print(filename)
         print("-" * 68)
@@ -2027,8 +2000,8 @@ Options:
                             v = v[:50]
                     if isinstance(v, bytes):
                         # quick and dirty binary check:
-                        for c in (1,2,3,4,5,6,7,11,12,14,15,16,17,18,19,20,
-                            21,22,23,24,25,26,27,28,29,30,31):
+                        for c in (1, 2, 3, 4, 5, 6, 7, 11, 12, 14, 15, 16, 17, 18, 19, 20,
+                            21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31):
                             if c in bytearray(v):
                                 v = '(binary data)'
                                 break
@@ -2039,7 +2012,7 @@ Options:
             print('\nChecking streams...')
             for streamname in ole.listdir():
                 # print name using repr() to convert binary chars to \xNN:
-                print('-', repr('/'.join(streamname)),'-', end=' ')
+                print('-', repr('/'.join(streamname)), '-', end=' ')
                 st_type = ole.get_type(streamname)
                 if st_type == STGTY_STREAM:
                     print('size %d' % ole.get_size(streamname))
@@ -2066,7 +2039,7 @@ Options:
         meta = ole.get_metadata()
         meta.dump()
         print()
-        #[PL] Test a few new methods:
+        # [PL] Test a few new methods:
         root = ole.get_rootentry_name()
         print('Root entry name: "%s"' % root)
         if ole.exists('worddocument'):
diff --git a/PIL/PcxImagePlugin.py b/PIL/PcxImagePlugin.py
index 0765f099e..8eac6a594 100644
--- a/PIL/PcxImagePlugin.py
+++ b/PIL/PcxImagePlugin.py
@@ -58,7 +58,7 @@ class PcxImageFile(ImageFile.ImageFile):
         if bbox[2] <= bbox[0] or bbox[3] <= bbox[1]:
             raise SyntaxError("bad PCX image size")
         if Image.DEBUG:
-            print ("BBox: %s %s %s %s" % bbox)
+            print("BBox: %s %s %s %s" % bbox)
 
         # format
         version = i8(s[1])
@@ -66,8 +66,8 @@ class PcxImageFile(ImageFile.ImageFile):
         planes = i8(s[65])
         stride = i16(s, 66)
         if Image.DEBUG:
-            print ("PCX version %s, bits %s, planes %s, stride %s" %
-                   (version, bits, planes, stride))
+            print("PCX version %s, bits %s, planes %s, stride %s" %
+                  (version, bits, planes, stride))
 
         self.info["dpi"] = i16(s, 12), i16(s, 14)
 
@@ -106,7 +106,7 @@ class PcxImageFile(ImageFile.ImageFile):
 
         bbox = (0, 0) + self.size
         if Image.DEBUG:
-            print ("size: %sx%s" % self.size)
+            print("size: %sx%s" % self.size)
 
         self.tile = [("pcx", bbox, self.fp.tell(), (rawmode, planes * stride))]
 
@@ -143,7 +143,7 @@ def _save(im, fp, filename, check=0):
     # gets overwritten.
 
     if Image.DEBUG:
-        print ("PcxImagePlugin._save: xwidth: %d, bits: %d, stride: %d" % (
+        print("PcxImagePlugin._save: xwidth: %d, bits: %d, stride: %d" % (
             im.size[0], bits, stride))
 
     # under windows, we could determine the current screen size with
diff --git a/PIL/PngImagePlugin.py b/PIL/PngImagePlugin.py
index d8593f90d..398a01f33 100644
--- a/PIL/PngImagePlugin.py
+++ b/PIL/PngImagePlugin.py
@@ -78,6 +78,7 @@ MAX_TEXT_CHUNK = ImageFile.SAFEBLOCK
 # Set the maximum total text chunk size.
 MAX_TEXT_MEMORY = 64 * MAX_TEXT_CHUNK
 
+
 def _safe_zlib_decompress(s):
     dobj = zlib.decompressobj()
     plaintext = dobj.decompress(s, MAX_TEXT_CHUNK)
diff --git a/PIL/PyAccess.py b/PIL/PyAccess.py
index a3f1c3909..87a6d4915 100644
--- a/PIL/PyAccess.py
+++ b/PIL/PyAccess.py
@@ -51,7 +51,7 @@ class PyAccess(object):
         self.ysize = vals['ysize']
 
         if DEBUG:
-            print (vals)
+            print(vals)
         self._post_init()
 
     def _post_init(self):
diff --git a/PIL/TiffImagePlugin.py b/PIL/TiffImagePlugin.py
index d7291e87c..e4028fdbb 100644
--- a/PIL/TiffImagePlugin.py
+++ b/PIL/TiffImagePlugin.py
@@ -506,7 +506,7 @@ class ImageFileDirectory(collections.MutableMapping):
                 typ = self.tagtype[tag]
 
             if Image.DEBUG:
-                print ("Tag %s, Type: %s, Value: %s" % (tag, typ, value))
+                print("Tag %s, Type: %s, Value: %s" % (tag, typ, value))
 
             if typ == 1:
                 # byte data
@@ -638,9 +638,9 @@ class TiffImageFile(ImageFile.ImageFile):
         self.__fp = self.fp
 
         if Image.DEBUG:
-            print ("*** TiffImageFile._open ***")
-            print ("- __first:", self.__first)
-            print ("- ifh: ", ifh)
+            print("*** TiffImageFile._open ***")
+            print("- __first:", self.__first)
+            print("- ifh: ", ifh)
 
         # and load the first frame
         self._seek(0)
@@ -751,19 +751,19 @@ class TiffImageFile(ImageFile.ImageFile):
             # that returns an IOError if there's no underlying fp. Easier to
             # dea. with here by reordering.
             if Image.DEBUG:
-                print ("have getvalue. just sending in a string from getvalue")
+                print("have getvalue. just sending in a string from getvalue")
             n, err = decoder.decode(self.fp.getvalue())
         elif hasattr(self.fp, "fileno"):
             # we've got a actual file on disk, pass in the fp.
             if Image.DEBUG:
-                print ("have fileno, calling fileno version of the decoder.")
+                print("have fileno, calling fileno version of the decoder.")
             self.fp.seek(0)
             # 4 bytes, otherwise the trace might error out
             n, err = decoder.decode(b"fpfp")
         else:
             # we have something else.
             if Image.DEBUG:
-                print ("don't have fileno or getvalue. just reading")
+                print("don't have fileno or getvalue. just reading")
             # UNDONE -- so much for that buffer size thing.
             n, err = decoder.decode(self.fp.read())
 
@@ -943,7 +943,7 @@ class TiffImageFile(ImageFile.ImageFile):
                             (0, min(y, ysize), w, min(y+h, ysize)),
                             offsets[i], a))
                     if Image.DEBUG:
-                        print ("tiles: ", self.tile)
+                        print("tiles: ", self.tile)
                     y = y + h
                     if y >= self.size[1]:
                         x = y = 0
@@ -1128,8 +1128,8 @@ def _save(im, fp, filename):
 
     if libtiff:
         if Image.DEBUG:
-            print ("Saving using libtiff encoder")
-            print (ifd.items())
+            print("Saving using libtiff encoder")
+            print(ifd.items())
         _fp = 0
         if hasattr(fp, "fileno"):
             try:
@@ -1186,7 +1186,7 @@ def _save(im, fp, filename):
                     atts[k] = v
 
         if Image.DEBUG:
-            print (atts)
+            print(atts)
 
         # libtiff always expects the bytes in native order.
         # we're storing image byte order. So, if the rawmode
diff --git a/Tests/bench_cffi_access.py b/Tests/bench_cffi_access.py
index 769396f53..5b64813e4 100644
--- a/Tests/bench_cffi_access.py
+++ b/Tests/bench_cffi_access.py
@@ -47,7 +47,7 @@ class BenchCffiAccess(PillowTestCase):
 
         self.assertEqual(caccess[(0, 0)], access[(0, 0)])
 
-        print ("Size: %sx%s" % im.size)
+        print("Size: %sx%s" % im.size)
         timer(iterate_get, 'PyAccess - get', im.size, access)
         timer(iterate_set, 'PyAccess - set', im.size, access)
         timer(iterate_get, 'C-api - get', im.size, caccess)
diff --git a/Tests/check_imaging_leaks.py b/Tests/check_imaging_leaks.py
index 3a7dcaa2b..c6d99b8d1 100644
--- a/Tests/check_imaging_leaks.py
+++ b/Tests/check_imaging_leaks.py
@@ -8,6 +8,7 @@ from PIL import Image, ImageFilter
 min_iterations = 100
 max_iterations = 10000
 
+
 @unittest.skipIf(sys.platform.startswith('win32'), "requires Unix or MacOS")
 class TestImagingLeaks(PillowTestCase):
 
@@ -40,4 +41,3 @@ class TestImagingLeaks(PillowTestCase):
 
 if __name__ == '__main__':
     unittest.main()
-
diff --git a/Tests/check_jpeg_leaks.py b/Tests/check_jpeg_leaks.py
index adf7652cf..290bac4d8 100644
--- a/Tests/check_jpeg_leaks.py
+++ b/Tests/check_jpeg_leaks.py
@@ -71,9 +71,8 @@ post-patch:
      | :@:@@: :#:::@ :::@::::@ : :: : @ :::::: :@:: ::: :::: @:: @:::::::@::::
    0 +----------------------------------------------------------------------->Gi
      0                                                                   8.421
- 
-"""
 
+"""
 
     def test_qtables_leak(self):
         im = hopper('RGB')
@@ -103,7 +102,6 @@ post-patch:
         qtables = [standard_l_qtable,
                    standard_chrominance_qtable]
 
-        
         for count in range(iterations):
             test_output = BytesIO()
             im.save(test_output, "JPEG", qtables=qtables)
@@ -135,7 +133,7 @@ pre patch:
    0 +----------------------------------------------------------------------->Gi
      0                                                                   11.37
 
-    
+
 post patch:
 
     MB
@@ -172,7 +170,6 @@ post patch:
             test_output = BytesIO()
             im.save(test_output, "JPEG", exif=exif)
 
-
     """
 base case:
     MB
diff --git a/Tests/check_png_dos.py b/Tests/check_png_dos.py
index c74990a8c..762c9607a 100644
--- a/Tests/check_png_dos.py
+++ b/Tests/check_png_dos.py
@@ -5,6 +5,7 @@ import zlib
 
 TEST_FILE = "Tests/images/png_decompression_dos.png"
 
+
 class TestPngDos(PillowTestCase):
     def test_dos_text(self):
 
@@ -19,19 +20,19 @@ class TestPngDos(PillowTestCase):
             self.assertLess(len(s), 1024*1024, "Text chunk larger than 1M")
 
     def test_dos_total_memory(self):
-        im = Image.new('L',(1,1))
+        im = Image.new('L', (1, 1))
         compressed_data = zlib.compress('a'*1024*1023)
 
         info = PngImagePlugin.PngInfo()
 
         for x in range(64):
-            info.add_text('t%s'%x, compressed_data, 1)
-            info.add_itxt('i%s'%x, compressed_data, zip=True)
+            info.add_text('t%s' % x, compressed_data, 1)
+            info.add_itxt('i%s' % x, compressed_data, zip=True)
 
         b = BytesIO()
         im.save(b, 'PNG', pnginfo=info)
         b.seek(0)
-        
+
         try:
             im2 = Image.open(b)
         except ValueError as msg:
@@ -42,6 +43,6 @@ class TestPngDos(PillowTestCase):
         for txt in im2.text.values():
             total_len += len(txt)
         self.assertLess(total_len, 64*1024*1024, "Total text chunks greater than 64M")
-        
+
 if __name__ == '__main__':
     unittest.main()
diff --git a/Tests/check_webp_leaks.py b/Tests/check_webp_leaks.py
index 95162ad4a..79e22328b 100644
--- a/Tests/check_webp_leaks.py
+++ b/Tests/check_webp_leaks.py
@@ -5,7 +5,7 @@ from PIL import Image
 from io import BytesIO
 
 # Limits for testing the leak
-mem_limit = 16 # max increase in MB
+mem_limit = 16  # max increase in MB
 iterations = 5000
 test_file = "Tests/images/hopper.webp"
 
diff --git a/Tests/helper.py b/Tests/helper.py
index c59caa2f5..1255b1819 100644
--- a/Tests/helper.py
+++ b/Tests/helper.py
@@ -130,7 +130,7 @@ class PillowTestCase(unittest.TestCase):
         # Skip if platform/travis matches, and
         # PILLOW_RUN_KNOWN_BAD is not true in the environment.
         if bool(os.environ.get('PILLOW_RUN_KNOWN_BAD', False)):
-            print (os.environ.get('PILLOW_RUN_KNOWN_BAD', False))
+            print(os.environ.get('PILLOW_RUN_KNOWN_BAD', False))
             return
 
         skip = True
diff --git a/Tests/test_binary.py b/Tests/test_binary.py
index 4d3fb5914..1e44d9641 100644
--- a/Tests/test_binary.py
+++ b/Tests/test_binary.py
@@ -2,6 +2,7 @@ from helper import unittest, PillowTestCase
 
 from PIL import _binary
 
+
 class TestBinary(PillowTestCase):
 
     def test_standard(self):
@@ -11,18 +12,18 @@ class TestBinary(PillowTestCase):
     def test_little_endian(self):
         self.assertEqual(_binary.i16le(b'\xff\xff\x00\x00'), 65535)
         self.assertEqual(_binary.i32le(b'\xff\xff\x00\x00'), 65535)
-        
+
         self.assertEqual(_binary.o16le(65535), b'\xff\xff')
         self.assertEqual(_binary.o32le(65535), b'\xff\xff\x00\x00')
 
     def test_big_endian(self):
         self.assertEqual(_binary.i16be(b'\x00\x00\xff\xff'), 0)
         self.assertEqual(_binary.i32be(b'\x00\x00\xff\xff'), 65535)
-        
+
         self.assertEqual(_binary.o16be(65535), b'\xff\xff')
         self.assertEqual(_binary.o32be(65535), b'\x00\x00\xff\xff')
 
 if __name__ == '__main__':
     unittest.main()
 
-# End of file
\ No newline at end of file
+# End of file
diff --git a/Tests/test_file_eps.py b/Tests/test_file_eps.py
index 861cf264a..f1fbac922 100644
--- a/Tests/test_file_eps.py
+++ b/Tests/test_file_eps.py
@@ -148,8 +148,8 @@ class TestFileEps(PillowTestCase):
         # open image with binary preview
         Image.open(file3)
 
-    def _test_readline(self,t, ending):
-        ending = "Failure with line ending: %s" %("".join("%s" %ord(s) for s in ending))
+    def _test_readline(self, t, ending):
+        ending = "Failure with line ending: %s" % ("".join("%s" % ord(s) for s in ending))
         self.assertEqual(t.readline().strip('\r\n'), 'something', ending)
         self.assertEqual(t.readline().strip('\r\n'), 'else', ending)
         self.assertEqual(t.readline().strip('\r\n'), 'baz', ending)
@@ -174,30 +174,30 @@ class TestFileEps(PillowTestCase):
 
     def _test_readline_file_universal(self, test_string, ending):
         f = self.tempfile('temp.txt')
-        with open(f,'wb') as w:
+        with open(f, 'wb') as w:
             if str is bytes:
                 w.write(test_string)
             else:
                 w.write(test_string.encode('UTF-8'))
 
-        with open(f,'rU') as t:
+        with open(f, 'rU') as t:
             self._test_readline(t, ending)
 
     def _test_readline_file_psfile(self, test_string, ending):
         f = self.tempfile('temp.txt')
-        with open(f,'wb') as w:
+        with open(f, 'wb') as w:
             if str is bytes:
                 w.write(test_string)
             else:
                 w.write(test_string.encode('UTF-8'))
 
-        with open(f,'rb') as r:
+        with open(f, 'rb') as r:
             t = EpsImagePlugin.PSFile(r)
             self._test_readline(t, ending)
 
     def test_readline(self):
         # check all the freaking line endings possible from the spec
-        #test_string = u'something\r\nelse\n\rbaz\rbif\n'
+        # test_string = u'something\r\nelse\n\rbaz\rbif\n'
         line_endings = ['\r\n', '\n']
         not_working_endings = ['\n\r', '\r']
         strings = ['something', 'else', 'baz', 'bif']
@@ -205,9 +205,9 @@ class TestFileEps(PillowTestCase):
         for ending in line_endings:
             s = ending.join(strings)
             # Native Python versions will pass these endings.
-            #self._test_readline_stringio(s, ending)
-            #self._test_readline_io(s, ending)
-            #self._test_readline_file_universal(s, ending)
+            # self._test_readline_stringio(s, ending)
+            # self._test_readline_io(s, ending)
+            # self._test_readline_file_universal(s, ending)
 
             self._test_readline_file_psfile(s, ending)
 
@@ -217,9 +217,9 @@ class TestFileEps(PillowTestCase):
             s = ending.join(strings)
 
             # Native Python versions may fail on these endings.
-            #self._test_readline_stringio(s, ending)
-            #self._test_readline_io(s, ending)
-            #self._test_readline_file_universal(s, ending)
+            # self._test_readline_stringio(s, ending)
+            # self._test_readline_io(s, ending)
+            # self._test_readline_file_universal(s, ending)
 
             self._test_readline_file_psfile(s, ending)
 
diff --git a/Tests/test_file_icns.py b/Tests/test_file_icns.py
index ddbed3cd2..23d22df1b 100644
--- a/Tests/test_file_icns.py
+++ b/Tests/test_file_icns.py
@@ -26,12 +26,12 @@ class TestFileIcns(PillowTestCase):
                      "requires MacOS")
     def test_save(self):
         im = Image.open(file)
-        
+
         test_file = self.tempfile("temp.icns")
         im.save(test_file)
-        
+
         reread = Image.open(test_file)
-        
+
         self.assertEqual(reread.mode, "RGBA")
         self.assertEqual(reread.size, (1024, 1024))
         self.assertEqual(reread.format, "ICNS")
@@ -87,4 +87,4 @@ class TestFileIcns(PillowTestCase):
 if __name__ == '__main__':
     unittest.main()
 
-# End of file
\ No newline at end of file
+# End of file
diff --git a/Tests/test_file_ico.py b/Tests/test_file_ico.py
index 4f53fe1c1..f7b52b124 100644
--- a/Tests/test_file_ico.py
+++ b/Tests/test_file_ico.py
@@ -25,23 +25,22 @@ class TestFileIco(PillowTestCase):
         # the default image
         output.seek(0)
         reloaded = Image.open(output)
-        self.assertEqual(reloaded.info['sizes'],set([(32, 32), (64, 64)]))
+        self.assertEqual(reloaded.info['sizes'], set([(32, 32), (64, 64)]))
 
         self.assertEqual(im.mode, reloaded.mode)
         self.assertEqual((64, 64), reloaded.size)
         self.assertEqual(reloaded.format, "ICO")
-        self.assert_image_equal(reloaded, hopper().resize((64,64), Image.LANCZOS))
+        self.assert_image_equal(reloaded, hopper().resize((64, 64), Image.LANCZOS))
 
         # the other one
         output.seek(0)
         reloaded = Image.open(output)
-        reloaded.size = (32,32)
+        reloaded.size = (32, 32)
 
         self.assertEqual(im.mode, reloaded.mode)
         self.assertEqual((32, 32), reloaded.size)
         self.assertEqual(reloaded.format, "ICO")
-        self.assert_image_equal(reloaded, hopper().resize((32,32), Image.LANCZOS))
-
+        self.assert_image_equal(reloaded, hopper().resize((32, 32), Image.LANCZOS))
 
 
 if __name__ == '__main__':
diff --git a/Tests/test_file_jpeg.py b/Tests/test_file_jpeg.py
index 64e8b74af..aa24582cc 100644
--- a/Tests/test_file_jpeg.py
+++ b/Tests/test_file_jpeg.py
@@ -301,15 +301,12 @@ class TestFileJpeg(PillowTestCase):
         # sequence wrong length
         self.assertRaises(Exception, lambda: self.roundtrip(im, qtables=[]))
         # sequence wrong length
-        self.assertRaises(Exception, lambda: self.roundtrip(im, qtables=[1,2,3,4,5]))
+        self.assertRaises(Exception, lambda: self.roundtrip(im, qtables=[1, 2, 3, 4, 5]))
 
         # qtable entry not a sequence
         self.assertRaises(Exception, lambda: self.roundtrip(im, qtables=[1]))
         # qtable entry has wrong number of items
-        self.assertRaises(Exception, lambda: self.roundtrip(im, qtables=[[1,2,3,4]]))
-        
-        
-        
+        self.assertRaises(Exception, lambda: self.roundtrip(im, qtables=[[1, 2, 3, 4]]))
 
     @unittest.skipUnless(djpeg_available(), "djpeg not available")
     def test_load_djpeg(self):
@@ -340,9 +337,9 @@ class TestFileJpeg(PillowTestCase):
             """ Generates a very hard to compress file
             :param size: tuple
             """
-            return Image.frombytes('RGB',size, os.urandom(size[0]*size[1] *3))
+            return Image.frombytes('RGB', size, os.urandom(size[0]*size[1] * 3))
 
-        im = gen_random_image((512,512))
+        im = gen_random_image((512, 512))
         f = self.tempfile("temp.jpeg")
         im.save(f, quality=100, optimize=True)
 
diff --git a/Tests/test_file_libtiff.py b/Tests/test_file_libtiff.py
index a9377bf63..07850f8cf 100644
--- a/Tests/test_file_libtiff.py
+++ b/Tests/test_file_libtiff.py
@@ -27,7 +27,7 @@ class LibTiffTestCase(PillowTestCase):
             self.assertEqual(im._compression, 'group4')
         except:
             print("No _compression")
-            print (dir(im))
+            print(dir(im))
 
         # can we write it back out, in a different form.
         out = self.tempfile("temp.png")
@@ -243,13 +243,13 @@ class TestFileLibTiff(LibTiffTestCase):
         im2 = Image.open('Tests/images/12in16bit.tif')
 
         if Image.DEBUG:
-            print (im.getpixel((0, 0)))
-            print (im.getpixel((0, 1)))
-            print (im.getpixel((0, 2)))
+            print(im.getpixel((0, 0)))
+            print(im.getpixel((0, 1)))
+            print(im.getpixel((0, 2)))
 
-            print (im2.getpixel((0, 0)))
-            print (im2.getpixel((0, 1)))
-            print (im2.getpixel((0, 2)))
+            print(im2.getpixel((0, 0)))
+            print(im2.getpixel((0, 1)))
+            print(im2.getpixel((0, 2)))
 
         self.assert_image_equal(im, im2)
 
diff --git a/Tests/test_file_png.py b/Tests/test_file_png.py
index 4cd5dc703..dbbe72afa 100644
--- a/Tests/test_file_png.py
+++ b/Tests/test_file_png.py
@@ -153,7 +153,7 @@ class TestFilePng(PillowTestCase):
 
         im = load(HEAD + chunk(b'iTXt', b'spam\0\1\0en\0Spam\0' +
                                zlib.compress(b"egg")[:1]) + TAIL)
-        self.assertEqual(im.info, {'spam':''})
+        self.assertEqual(im.info, {'spam': ''})
 
         im = load(HEAD + chunk(b'iTXt', b'spam\0\1\1en\0Spam\0' +
                                zlib.compress(b"egg")) + TAIL)
@@ -380,7 +380,6 @@ class TestFilePng(PillowTestCase):
         repr_png = Image.open(BytesIO(im._repr_png_()))
         self.assertEqual(repr_png.format, 'PNG')
         self.assert_image_equal(im, repr_png)
-        
 
 
 if __name__ == '__main__':
diff --git a/Tests/test_file_tiff.py b/Tests/test_file_tiff.py
index 32aef075e..b885780d6 100644
--- a/Tests/test_file_tiff.py
+++ b/Tests/test_file_tiff.py
@@ -121,13 +121,13 @@ class TestFileTiff(PillowTestCase):
         im2 = Image.open('Tests/images/12in16bit.tif')
 
         if Image.DEBUG:
-            print (im.getpixel((0, 0)))
-            print (im.getpixel((0, 1)))
-            print (im.getpixel((0, 2)))
+            print(im.getpixel((0, 0)))
+            print(im.getpixel((0, 1)))
+            print(im.getpixel((0, 2)))
 
-            print (im2.getpixel((0, 0)))
-            print (im2.getpixel((0, 1)))
-            print (im2.getpixel((0, 2)))
+            print(im2.getpixel((0, 0)))
+            print(im2.getpixel((0, 1)))
+            print(im2.getpixel((0, 2)))
 
         self.assert_image_equal(im, im2)
 
diff --git a/Tests/test_file_tiff_metadata.py b/Tests/test_file_tiff_metadata.py
index 2954c0879..dfc16682b 100644
--- a/Tests/test_file_tiff_metadata.py
+++ b/Tests/test_file_tiff_metadata.py
@@ -37,7 +37,7 @@ class TestFileTiffMetadata(PillowTestCase):
 
         self.assertEqual(loaded.tag[50838], (len(textdata),))
         self.assertEqual(loaded.tag[50839], textdata)
-        self.assertAlmostEqual(loaded.tag[tag_ids['RollAngle']][0], floatdata, 
+        self.assertAlmostEqual(loaded.tag[tag_ids['RollAngle']][0], floatdata,
                                places=5)
         self.assertAlmostEqual(loaded.tag[tag_ids['YawAngle']][0], doubledata)
 
diff --git a/Tests/test_file_webp_metadata.py b/Tests/test_file_webp_metadata.py
index f2f18d713..08d42d7c6 100644
--- a/Tests/test_file_webp_metadata.py
+++ b/Tests/test_file_webp_metadata.py
@@ -15,7 +15,6 @@ class TestFileWebpMetadata(PillowTestCase):
         if not _webp.HAVE_WEBPMUX:
             self.skipTest('WebPMux support not installed')
 
-
     def test_read_exif_metadata(self):
 
         file_path = "Tests/images/flower.webp"
diff --git a/Tests/test_file_xpm.py b/Tests/test_file_xpm.py
index 9a666a705..6a6817048 100644
--- a/Tests/test_file_xpm.py
+++ b/Tests/test_file_xpm.py
@@ -15,7 +15,7 @@ class TestFileXpm(PillowTestCase):
         self.assertEqual(im.size, (128, 128))
         self.assertEqual(im.format, "XPM")
 
-        #large error due to quantization->44 colors.
+        # large error due to quantization->44 colors.
         self.assert_image_similar(im.convert('RGB'), hopper('RGB'), 60)
 
     def test_load_read(self):
diff --git a/Tests/test_image_putdata.py b/Tests/test_image_putdata.py
index 3b7dc836a..b46456eba 100644
--- a/Tests/test_image_putdata.py
+++ b/Tests/test_image_putdata.py
@@ -72,8 +72,8 @@ class TestImagePutData(PillowTestCase):
         im = Image.new('L', (150, 100))
         im.putdata(arr)
 
-        self.assertEqual(len(im.getdata()),len(arr))
-        
+        self.assertEqual(len(im.getdata()), len(arr))
+
     def test_array_F(self):
         # shouldn't segfault
         # see https://github.com/python-pillow/Pillow/issues/1008
@@ -82,7 +82,7 @@ class TestImagePutData(PillowTestCase):
         arr = array('f', [0.0])*15000
         im.putdata(arr)
 
-        self.assertEqual(len(im.getdata()),len(arr))
+        self.assertEqual(len(im.getdata()), len(arr))
 
 if __name__ == '__main__':
     unittest.main()
diff --git a/Tests/test_image_resize.py b/Tests/test_image_resize.py
index 9cd85d1b1..414758529 100644
--- a/Tests/test_image_resize.py
+++ b/Tests/test_image_resize.py
@@ -17,11 +17,11 @@ class TestImagingCoreResize(PillowTestCase):
 
     def test_nearest_mode(self):
         for mode in ["1", "P", "L", "I", "F", "RGB", "RGBA", "CMYK", "YCbCr",
-                     "I;16"]: # exotic mode
+                     "I;16"]:  # exotic mode
             im = hopper(mode)
             r = self.resize(im, (15, 12), Image.NEAREST)
             self.assertEqual(r.mode, mode)
-            self.assertEqual(r.size, (15, 12) )
+            self.assertEqual(r.size, (15, 12))
             self.assertEqual(r.im.bands, im.im.bands)
 
     def test_convolution_modes(self):
@@ -35,7 +35,7 @@ class TestImagingCoreResize(PillowTestCase):
             im = hopper(mode)
             r = self.resize(im, (15, 12), Image.BILINEAR)
             self.assertEqual(r.mode, mode)
-            self.assertEqual(r.size, (15, 12) )
+            self.assertEqual(r.size, (15, 12))
             self.assertEqual(r.im.bands, im.im.bands)
 
     def test_reduce_filters(self):
diff --git a/Tests/test_image_transpose.py b/Tests/test_image_transpose.py
index 3183ceadd..3069df61c 100644
--- a/Tests/test_image_transpose.py
+++ b/Tests/test_image_transpose.py
@@ -1,7 +1,7 @@
 from helper import unittest, PillowTestCase, hopper
 
 from PIL.Image import (FLIP_LEFT_RIGHT, FLIP_TOP_BOTTOM, ROTATE_90, ROTATE_180,
-    ROTATE_270, TRANSPOSE)
+                       ROTATE_270, TRANSPOSE)
 
 
 class TestImageTranspose(PillowTestCase):
diff --git a/Tests/test_imagecms.py b/Tests/test_imagecms.py
index 93bdda44c..7a2a57151 100644
--- a/Tests/test_imagecms.py
+++ b/Tests/test_imagecms.py
@@ -4,7 +4,7 @@ from PIL import Image
 
 from io import BytesIO
 import os
-        
+
 try:
     from PIL import ImageCms
     from PIL.ImageCms import ImageCmsProfile
@@ -17,6 +17,7 @@ except ImportError as v:
 SRGB = "Tests/icc/sRGB_IEC61966-2-1_black_scaled.icc"
 HAVE_PROFILE = os.path.exists(SRGB)
 
+
 class TestImageCms(PillowTestCase):
 
     def setUp(self):
@@ -32,7 +33,7 @@ class TestImageCms(PillowTestCase):
             self.skipTest("SRGB profile not available")
 
     def test_sanity(self):
-        
+
         # basic smoke test.
         # this mostly follows the cms_test outline.
 
diff --git a/Tests/test_imagedraw.py b/Tests/test_imagedraw.py
index 6adc6c1f2..3b9919834 100644
--- a/Tests/test_imagedraw.py
+++ b/Tests/test_imagedraw.py
@@ -64,7 +64,7 @@ class TestImageDraw(PillowTestCase):
 
         # Assert
         self.assert_image_similar(
-            im, Image.open("Tests/images/imagedraw_arc.png"),1)
+            im, Image.open("Tests/images/imagedraw_arc.png"), 1)
 
     def test_arc1(self):
         self.helper_arc(BBOX1)
@@ -97,7 +97,7 @@ class TestImageDraw(PillowTestCase):
 
         # Assert
         self.assert_image_similar(
-            im, Image.open("Tests/images/imagedraw_chord.png"),1)
+            im, Image.open("Tests/images/imagedraw_chord.png"), 1)
 
     def test_chord1(self):
         self.helper_chord(BBOX1)
@@ -116,7 +116,7 @@ class TestImageDraw(PillowTestCase):
 
         # Assert
         self.assert_image_similar(
-            im, Image.open("Tests/images/imagedraw_ellipse.png"),1)
+            im, Image.open("Tests/images/imagedraw_ellipse.png"), 1)
 
     def test_ellipse1(self):
         self.helper_ellipse(BBOX1)
@@ -154,7 +154,7 @@ class TestImageDraw(PillowTestCase):
 
         # Assert
         self.assert_image_similar(
-            im, Image.open("Tests/images/imagedraw_pieslice.png"),1)
+            im, Image.open("Tests/images/imagedraw_pieslice.png"), 1)
 
     def test_pieslice1(self):
         self.helper_pieslice(BBOX1)
diff --git a/Tests/test_imageenhance.py b/Tests/test_imageenhance.py
index 58042db85..82ba2e5db 100644
--- a/Tests/test_imageenhance.py
+++ b/Tests/test_imageenhance.py
@@ -21,23 +21,22 @@ class TestImageEnhance(PillowTestCase):
         im = Image.new("RGB", (1, 1))
         ImageEnhance.Sharpness(im).enhance(0.5)
 
-
     def _half_transparent_image(self):
         # returns an image, half transparent, half solid
         im = hopper('RGB')
-        
+
         transparent = Image.new('L', im.size, 0)
         solid = Image.new('L', (im.size[0]//2, im.size[1]), 255)
-        transparent.paste(solid, (0,0))
+        transparent.paste(solid, (0, 0))
         im.putalpha(transparent)
 
         return im
 
-    def _check_alpha(self,im, original, op, amount):
+    def _check_alpha(self, im, original, op, amount):
         self.assertEqual(im.getbands(), original.getbands())
         self.assert_image_equal(im.split()[-1], original.split()[-1],
                                 "Diff on %s: %s" % (op, amount))
-    
+
     def test_alpha(self):
         # Issue https://github.com/python-pillow/Pillow/issues/899
         # Is alpha preserved through image enhancement?
@@ -45,10 +44,10 @@ class TestImageEnhance(PillowTestCase):
         original = self._half_transparent_image()
 
         for op in ['Color', 'Brightness', 'Contrast', 'Sharpness']:
-            for amount in [0,0.5,1.0]:
-                self._check_alpha(getattr(ImageEnhance,op)(original).enhance(amount),
+            for amount in [0, 0.5, 1.0]:
+                self._check_alpha(getattr(ImageEnhance, op)(original).enhance(amount),
                                   original, op, amount)
-                
+
 
 if __name__ == '__main__':
     unittest.main()
diff --git a/Tests/test_imagefile.py b/Tests/test_imagefile.py
index 662a3bfb0..01503dff7 100644
--- a/Tests/test_imagefile.py
+++ b/Tests/test_imagefile.py
@@ -58,7 +58,7 @@ class TestImageFile(PillowTestCase):
             # This test fails on Ubuntu 12.04, PPC (Bigendian) It
             # appears to be a ghostscript 9.05 bug, since the
             # ghostscript rendering is wonky and the file is identical
-            # to that written on ubuntu 12.04 x64 
+            # to that written on ubuntu 12.04 x64
             # md5sum: ba974835ff2d6f3f2fd0053a23521d4a
 
             # EPS comes back in RGB:
diff --git a/Tests/test_imagefont_bitmap.py b/Tests/test_imagefont_bitmap.py
index 9da3d1776..27141f4b3 100644
--- a/Tests/test_imagefont_bitmap.py
+++ b/Tests/test_imagefont_bitmap.py
@@ -1,6 +1,7 @@
 from helper import unittest, PillowTestCase
 from PIL import Image, ImageFont, ImageDraw
 
+
 class TestImageFontBitmap(PillowTestCase):
     def test_similar(self):
         text = 'EmbeddedBitmap'
@@ -13,10 +14,10 @@ class TestImageFontBitmap(PillowTestCase):
         draw_bitmap, draw_outline = ImageDraw.Draw(im_bitmap), ImageDraw.Draw(im_outline)
 
         # Metrics are different on the bitmap and ttf fonts, more so on some platforms
-        # and versions of freetype than others. Mac has a 1px difference, linux doesn't. 
-        draw_bitmap.text((0, size_final[1] - size_bitmap[1]), 
+        # and versions of freetype than others. Mac has a 1px difference, linux doesn't.
+        draw_bitmap.text((0, size_final[1] - size_bitmap[1]),
                          text, fill=(0, 0, 0), font=font_bitmap)
-        draw_outline.text((0, size_final[1] - size_outline[1]), 
+        draw_outline.text((0, size_final[1] - size_outline[1]),
                           text, fill=(0, 0, 0), font=font_outline)
         self.assert_image_similar(im_bitmap, im_outline, 20)
 
diff --git a/Tests/test_imagesequence.py b/Tests/test_imagesequence.py
index 62a83cda6..459a053d8 100644
--- a/Tests/test_imagesequence.py
+++ b/Tests/test_imagesequence.py
@@ -24,16 +24,16 @@ class TestImageSequence(PillowTestCase):
 
     def _test_multipage_tiff(self, dbg=False):
         # debug had side effect of calling fp.tell.
-        Image.DEBUG=dbg
+        Image.DEBUG = dbg
         im = Image.open('Tests/images/multipage.tiff')
         for index, frame in enumerate(ImageSequence.Iterator(im)):
             frame.load()
             self.assertEqual(index, im.tell())
             frame.convert('RGB')
-        Image.DEBUG=False
+        Image.DEBUG = False
 
     def test_tiff(self):
-        #self._test_multipage_tiff(True)
+        # self._test_multipage_tiff(True)
         self._test_multipage_tiff(False)
 
     def test_libtiff(self):
@@ -43,7 +43,7 @@ class TestImageSequence(PillowTestCase):
             self.skipTest("tiff support not available")
 
         TiffImagePlugin.READ_LIBTIFF = True
-        #self._test_multipage_tiff(True)
+        # self._test_multipage_tiff(True)
         self._test_multipage_tiff(False)
         TiffImagePlugin.READ_LIBTIFF = False
 
diff --git a/Tests/test_numpy.py b/Tests/test_numpy.py
index 7b6f22b2b..f010e0df5 100644
--- a/Tests/test_numpy.py
+++ b/Tests/test_numpy.py
@@ -129,8 +129,8 @@ class TestNumpy(PillowTestCase):
         arr = numpy.zeros((15000,), numpy.float32)
         im.putdata(arr)
 
-        self.assertEqual(len(im.getdata()),len(arr))
-   
+        self.assertEqual(len(im.getdata()), len(arr))
+
 
 if __name__ == '__main__':
     unittest.main()
diff --git a/Tests/test_scipy.py b/Tests/test_scipy.py
index 926bbb186..60f1a1b1e 100644
--- a/Tests/test_scipy.py
+++ b/Tests/test_scipy.py
@@ -8,12 +8,12 @@ try:
     HAS_SCIPY = True
 except:
     HAS_SCIPY = False
-    
+
 
 class Test_scipy_resize(PillowTestCase):
     """ Tests for scipy regression in 2.6.0
 
-    Tests from https://github.com/scipy/scipy/blob/master/scipy/misc/pilutil.py 
+    Tests from https://github.com/scipy/scipy/blob/master/scipy/misc/pilutil.py
     """
 
     def setUp(self):
@@ -21,25 +21,23 @@ class Test_scipy_resize(PillowTestCase):
             self.skipTest("Scipy Required")
 
     def test_imresize(self):
-        im = np.random.random((10,20))
+        im = np.random.random((10, 20))
         for T in np.sctypes['float'] + [float]:
             # 1.1 rounds to below 1.1 for float16, 1.101 works
-            im1 = misc.imresize(im,T(1.101))
-            self.assertEqual(im1.shape,(11,22))
+            im1 = misc.imresize(im, T(1.101))
+            self.assertEqual(im1.shape, (11, 22))
 
     def test_imresize4(self):
-        im = np.array([[1,2],
-                       [3,4]])
-        res = np.array([[ 1.  ,  1.25,  1.75,  2.  ],
-                        [ 1.5 ,  1.75,  2.25,  2.5 ],
-                        [ 2.5 ,  2.75,  3.25,  3.5 ],
-                        [ 3.  ,  3.25,  3.75,  4.  ]], dtype=np.float32)
+        im = np.array([[1, 2],
+                       [3, 4]])
+        res = np.array([[1. ,  1.25,  1.75,  2. ],
+                        [1.5,  1.75,  2.25,  2.5],
+                        [2.5,  2.75,  3.25,  3.5],
+                        [3. ,  3.25,  3.75,  4. ]], dtype=np.float32)
         # Check that resizing by target size, float and int are the same
-        im2 = misc.imresize(im, (4,4), mode='F')  # output size
+        im2 = misc.imresize(im, (4, 4), mode='F')  # output size
         im3 = misc.imresize(im, 2., mode='F')  # fraction
         im4 = misc.imresize(im, 200, mode='F')  # percentage
         assert_equal(im2, res)
         assert_equal(im3, res)
         assert_equal(im4, res)
-
-

From 86be744d1fe75726c461d7d8cffa726bebb874e2 Mon Sep 17 00:00:00 2001
From: Andrew Murray <radarhere@gmail.com>
Date: Fri, 24 Apr 2015 09:41:33 +1000
Subject: [PATCH 2/3] Various Flake8 Scripts fixes

---
 Scripts/enhancer.py    |  3 ++-
 Scripts/explode.py     |  6 ++++--
 Scripts/gifmaker.py    |  8 ++++++--
 Scripts/painter.py     |  5 +++--
 Scripts/pilconvert.py  |  7 +++++--
 Scripts/pildriver.py   |  3 ++-
 Scripts/pilfile.py     |  5 ++++-
 Scripts/pilfont.py     |  3 ++-
 Scripts/pilprint.py    | 11 +++++++----
 Scripts/player.py      |  4 ++--
 Scripts/thresholder.py |  9 +++++----
 Scripts/viewer.py      |  1 +
 12 files changed, 43 insertions(+), 22 deletions(-)

diff --git a/Scripts/enhancer.py b/Scripts/enhancer.py
index fe250c9f8..34becf873 100644
--- a/Scripts/enhancer.py
+++ b/Scripts/enhancer.py
@@ -18,6 +18,7 @@ import sys
 #
 # enhancer widget
 
+
 class Enhance(Frame):
     def __init__(self, master, image, name, enhancer, lo, hi):
         Frame.__init__(self, master)
@@ -25,7 +26,7 @@ class Enhance(Frame):
         # set up the image
         self.tkim = ImageTk.PhotoImage(image.mode, image.size)
         self.enhancer = enhancer(image)
-        self.update("1.0") # normalize
+        self.update("1.0")  # normalize
 
         # image window
         Label(self, image=self.tkim).pack()
diff --git a/Scripts/explode.py b/Scripts/explode.py
index b8680f631..0460fa020 100644
--- a/Scripts/explode.py
+++ b/Scripts/explode.py
@@ -9,11 +9,13 @@
 from __future__ import print_function
 
 from PIL import Image
-import os, sys
+import os
+import sys
+
 
 class Interval:
 
-    def __init__(self, interval = "0"):
+    def __init__(self, interval="0"):
 
         self.setinterval(interval)
 
diff --git a/Scripts/gifmaker.py b/Scripts/gifmaker.py
index bd4de99c1..8777f74f6 100644
--- a/Scripts/gifmaker.py
+++ b/Scripts/gifmaker.py
@@ -49,20 +49,23 @@ from PIL.GifImagePlugin import getheader, getdata
 # --------------------------------------------------------------------
 # sequence iterator
 
+
 class image_sequence:
     def __init__(self, im):
         self.im = im
+
     def __getitem__(self, ix):
         try:
             if ix:
                 self.im.seek(ix)
             return self.im
         except EOFError:
-            raise IndexError # end of sequence
+            raise IndexError  # end of sequence
 
 # --------------------------------------------------------------------
 # straightforward delta encoding
 
+
 def makedelta(fp, sequence):
     """Convert list of image frames to a GIF animation file"""
 
@@ -91,7 +94,7 @@ def makedelta(fp, sequence):
             if bbox:
 
                 # compress difference
-                for s in getdata(im.crop(bbox), offset = bbox[:2]):
+                for s in getdata(im.crop(bbox), offset=bbox[:2]):
                     fp.write(s)
 
             else:
@@ -109,6 +112,7 @@ def makedelta(fp, sequence):
 # --------------------------------------------------------------------
 # main hack
 
+
 def compress(infile, outfile):
 
     # open input image, and force loading of first frame
diff --git a/Scripts/painter.py b/Scripts/painter.py
index 80c4db6a0..6f1c19484 100644
--- a/Scripts/painter.py
+++ b/Scripts/painter.py
@@ -20,6 +20,7 @@ import sys
 #
 # painter widget
 
+
 class PaintCanvas(Canvas):
     def __init__(self, master, image):
         Canvas.__init__(self, master, width=image.size[0], height=image.size[1])
@@ -33,7 +34,7 @@ class PaintCanvas(Canvas):
                 box = x, y, min(xsize, x+tilesize), min(ysize, y+tilesize)
                 tile = ImageTk.PhotoImage(image.crop(box))
                 self.create_image(x, y, image=tile, anchor=NW)
-                self.tile[(x,y)] = box, tile
+                self.tile[(x, y)] = box, tile
 
         self.image = image
 
@@ -59,7 +60,7 @@ class PaintCanvas(Canvas):
                     xy, tile = self.tile[(x, y)]
                     tile.paste(self.image.crop(xy))
                 except KeyError:
-                    pass # outside the image
+                    pass  # outside the image
         self.update_idletasks()
 
 #
diff --git a/Scripts/pilconvert.py b/Scripts/pilconvert.py
index 0341994c9..66b2e5ac2 100644
--- a/Scripts/pilconvert.py
+++ b/Scripts/pilconvert.py
@@ -15,10 +15,13 @@
 
 from __future__ import print_function
 
-import getopt, string, sys
+import getopt
+import string
+import sys
 
 from PIL import Image
 
+
 def usage():
     print("PIL Convert 0.5/1998-12-30 -- convert image files")
     print("Usage: pilconvert [option] infile outfile")
@@ -49,7 +52,7 @@ except getopt.error as v:
 format = None
 convert = None
 
-options = { }
+options = {}
 
 for o, a in opt:
 
diff --git a/Scripts/pildriver.py b/Scripts/pildriver.py
index e45b05008..ba2a8c66f 100644
--- a/Scripts/pildriver.py
+++ b/Scripts/pildriver.py
@@ -52,6 +52,7 @@ from __future__ import print_function
 
 from PIL import Image
 
+
 class PILDriver:
 
     verbose = 0
@@ -500,7 +501,7 @@ if __name__ == '__main__':
     try:
         import readline
     except ImportError:
-        pass # not available on all platforms
+        pass  # not available on all platforms
 
     # If we see command-line arguments, interpret them as a stack state
     # and execute.  Otherwise go interactive.
diff --git a/Scripts/pilfile.py b/Scripts/pilfile.py
index 1b77b0e78..b4fe4942c 100644
--- a/Scripts/pilfile.py
+++ b/Scripts/pilfile.py
@@ -20,7 +20,9 @@
 from __future__ import print_function
 
 import site
-import getopt, glob, sys
+import getopt
+import glob
+import sys
 
 from PIL import Image
 
@@ -59,6 +61,7 @@ for o, a in opt:
     elif o == "-D":
         Image.DEBUG += 1
 
+
 def globfix(files):
     # expand wildcards where necessary
     if sys.platform == "win32":
diff --git a/Scripts/pilfont.py b/Scripts/pilfont.py
index ec25e7a71..4425c072c 100644
--- a/Scripts/pilfont.py
+++ b/Scripts/pilfont.py
@@ -14,7 +14,8 @@ from __future__ import print_function
 
 VERSION = "0.4"
 
-import glob, sys
+import glob
+import sys
 
 # drivers
 from PIL import BdfFontFile
diff --git a/Scripts/pilprint.py b/Scripts/pilprint.py
index 889944de7..d13a2a526 100644
--- a/Scripts/pilprint.py
+++ b/Scripts/pilprint.py
@@ -12,14 +12,17 @@
 #
 
 from __future__ import print_function
-import getopt, os, sys
+import getopt
+import os
+import sys
 
 VERSION = "pilprint 0.3/2003-05-05"
 
 from PIL import Image
 from PIL import PSDraw
 
-letter = ( 1.0*72, 1.0*72, 7.5*72, 10.0*72 )
+letter = (1.0*72, 1.0*72, 7.5*72, 10.0*72)
+
 
 def description(file, image):
     title = os.path.splitext(os.path.split(file)[1])[0]
@@ -43,8 +46,8 @@ except getopt.error as v:
     print(v)
     sys.exit(1)
 
-printer = None # print to stdout
-monochrome = 1 # reduce file size for most common case
+printer = None  # print to stdout
+monochrome = 1  # reduce file size for most common case
 
 for o, a in opt:
     if o == "-d":
diff --git a/Scripts/player.py b/Scripts/player.py
index 0c90286c5..43877415a 100644
--- a/Scripts/player.py
+++ b/Scripts/player.py
@@ -56,7 +56,7 @@ class UI(Label):
                 del self.im[0]
                 self.image.paste(im)
             except IndexError:
-                return # end of list
+                return  # end of list
 
         else:
 
@@ -65,7 +65,7 @@ class UI(Label):
                 im.seek(im.tell() + 1)
                 self.image.paste(im)
             except EOFError:
-                return # end of file
+                return  # end of file
 
         try:
             duration = im.info["duration"]
diff --git a/Scripts/thresholder.py b/Scripts/thresholder.py
index 29d4592d9..1e55c5a32 100644
--- a/Scripts/thresholder.py
+++ b/Scripts/thresholder.py
@@ -18,8 +18,9 @@ import sys
 #
 # an image viewer
 
+
 class UI(Frame):
-    def __init__(self, master, im, value = 128):
+    def __init__(self, master, im, value=128):
         Frame.__init__(self, master)
 
         self.image = im
@@ -45,16 +46,16 @@ class UI(Frame):
 
         self.redraw()
 
-    def redraw(self, event = None):
+    def redraw(self, event=None):
 
         # create overlay (note the explicit conversion to mode "1")
-        im = self.image.point(lambda v,t=self.value: v>=t, "1")
+        im = self.image.point(lambda v, t=self.value: v >= t, "1")
         self.overlay = ImageTk.BitmapImage(im, foreground="green")
 
         # update canvas
         self.canvas.delete("overlay")
         self.canvas.create_image(0, 0, image=self.overlay, anchor=NW,
-                tags="overlay")
+                                 tags="overlay")
 
 # --------------------------------------------------------------------
 # main
diff --git a/Scripts/viewer.py b/Scripts/viewer.py
index 86b2526cd..c0fc59d96 100644
--- a/Scripts/viewer.py
+++ b/Scripts/viewer.py
@@ -16,6 +16,7 @@ from PIL import Image, ImageTk
 #
 # an image viewer
 
+
 class UI(Label):
 
     def __init__(self, master, im):

From 87c4c6a72d9103373386a9103a18d88289444c0e Mon Sep 17 00:00:00 2001
From: Andrew Murray <radarhere@gmail.com>
Date: Fri, 24 Apr 2015 10:15:14 +1000
Subject: [PATCH 3/3] Various Flake8 fixes to base scripts

---
 mp_compile.py | 5 +++--
 setup.py      | 4 ++--
 2 files changed, 5 insertions(+), 4 deletions(-)

diff --git a/mp_compile.py b/mp_compile.py
index 955cd9c1b..892452558 100644
--- a/mp_compile.py
+++ b/mp_compile.py
@@ -3,7 +3,8 @@
 
 from multiprocessing import Pool, cpu_count
 from distutils.ccompiler import CCompiler
-import os, sys
+import os
+import sys
 
 try:
     MAX_PROCS = int(os.environ.get('MAX_CONCURRENCY', min(4, cpu_count())))
@@ -38,7 +39,7 @@ def _mp_compile(self, sources, output_dir=None, macros=None,
 
     pool = Pool(MAX_PROCS)
     try:
-        print ("Building using %d processes" % pool._processes)
+        print("Building using %d processes" % pool._processes)
     except:
         pass
     arr = [(self, obj, build, cc_args, extra_postargs, pp_opts)
diff --git a/setup.py b/setup.py
index 5886de07b..216322ec2 100644
--- a/setup.py
+++ b/setup.py
@@ -570,7 +570,7 @@ class pil_build_ext(build_ext):
             if feature.webpmux:
                 defs.append(("HAVE_WEBPMUX", None))
                 libs.append(feature.webpmux)
-                libs.append(feature.webpmux.replace('pmux','pdemux'))
+                libs.append(feature.webpmux.replace('pmux', 'pdemux'))
 
             exts.append(Extension(
                 "PIL._webp", ["_webp.c"], libraries=libs, define_macros=defs))
@@ -757,6 +757,6 @@ setup(
     test_suite='nose.collector',
     keywords=["Imaging", ],
     license='Standard PIL License',
-    zip_safe= not debug_build(),
+    zip_safe=not debug_build(),
 )
 # End of file