Upgrade Python syntax with pyupgrade --py3-plus

This commit is contained in:
Hugo 2019-09-30 17:56:31 +03:00
parent af770a6c55
commit 538d9e2e5d
108 changed files with 287 additions and 357 deletions

View File

@ -1,7 +1,4 @@
#!/usr/bin/env python #!/usr/bin/env python
from __future__ import division
import sys import sys
from PIL import Image from PIL import Image

View File

@ -1,6 +1,4 @@
#!/usr/bin/env python #!/usr/bin/env python
from __future__ import print_function
import base64 import base64
import os import os

View File

@ -1,7 +1,6 @@
""" """
Helper functions. Helper functions.
""" """
from __future__ import print_function
import logging import logging
import os import os
@ -77,10 +76,13 @@ class PillowTestCase(unittest.TestCase):
def assert_deep_equal(self, a, b, msg=None): def assert_deep_equal(self, a, b, msg=None):
try: try:
self.assertEqual( self.assertEqual(
len(a), len(b), msg or "got length %s, expected %s" % (len(a), len(b)) len(a),
len(b),
msg or "got length {}, expected {}".format(len(a), len(b)),
) )
self.assertTrue( self.assertTrue(
all(x == y for x, y in zip(a, b)), msg or "got %s, expected %s" % (a, b) all(x == y for x, y in zip(a, b)),
msg or "got {}, expected {}".format(a, b),
) )
except Exception: except Exception:
self.assertEqual(a, b, msg) self.assertEqual(a, b, msg)
@ -88,20 +90,24 @@ class PillowTestCase(unittest.TestCase):
def assert_image(self, im, mode, size, msg=None): def assert_image(self, im, mode, size, msg=None):
if mode is not None: if mode is not None:
self.assertEqual( self.assertEqual(
im.mode, mode, msg or "got mode %r, expected %r" % (im.mode, mode) im.mode,
mode,
msg or "got mode {!r}, expected {!r}".format(im.mode, mode),
) )
if size is not None: if size is not None:
self.assertEqual( self.assertEqual(
im.size, size, msg or "got size %r, expected %r" % (im.size, size) im.size,
size,
msg or "got size {!r}, expected {!r}".format(im.size, size),
) )
def assert_image_equal(self, a, b, msg=None): def assert_image_equal(self, a, b, msg=None):
self.assertEqual( self.assertEqual(
a.mode, b.mode, msg or "got mode %r, expected %r" % (a.mode, b.mode) a.mode, b.mode, msg or "got mode {!r}, expected {!r}".format(a.mode, b.mode)
) )
self.assertEqual( self.assertEqual(
a.size, b.size, msg or "got size %r, expected %r" % (a.size, b.size) a.size, b.size, msg or "got size {!r}, expected {!r}".format(a.size, b.size)
) )
if a.tobytes() != b.tobytes(): if a.tobytes() != b.tobytes():
if HAS_UPLOADER: if HAS_UPLOADER:
@ -122,10 +128,10 @@ class PillowTestCase(unittest.TestCase):
def assert_image_similar(self, a, b, epsilon, msg=None): def assert_image_similar(self, a, b, epsilon, msg=None):
epsilon = float(epsilon) epsilon = float(epsilon)
self.assertEqual( self.assertEqual(
a.mode, b.mode, msg or "got mode %r, expected %r" % (a.mode, b.mode) a.mode, b.mode, msg or "got mode {!r}, expected {!r}".format(a.mode, b.mode)
) )
self.assertEqual( self.assertEqual(
a.size, b.size, msg or "got size %r, expected %r" % (a.size, b.size) a.size, b.size, msg or "got size {!r}, expected {!r}".format(a.size, b.size)
) )
a, b = convert_to_comparable(a, b) a, b = convert_to_comparable(a, b)
@ -228,12 +234,12 @@ class PillowTestCase(unittest.TestCase):
def open_withImagemagick(self, f): def open_withImagemagick(self, f):
if not imagemagick_available(): if not imagemagick_available():
raise IOError() raise OSError()
outfile = self.tempfile("temp.png") outfile = self.tempfile("temp.png")
if command_succeeds([IMCONVERT, f, outfile]): if command_succeeds([IMCONVERT, f, outfile]):
return Image.open(outfile) return Image.open(outfile)
raise IOError() raise OSError()
@unittest.skipIf(sys.platform.startswith("win32"), "requires Unix or macOS") @unittest.skipIf(sys.platform.startswith("win32"), "requires Unix or macOS")
@ -371,7 +377,7 @@ def distro():
return line.strip().split("=")[1] return line.strip().split("=")[1]
class cached_property(object): class cached_property:
def __init__(self, func): def __init__(self, func):
self.func = func self.func = func

View File

@ -1,5 +1,3 @@
from __future__ import print_function
import glob import glob
import os import os
import sys import sys

View File

@ -1,7 +1,5 @@
# brute-force search for access descriptor hash table # brute-force search for access descriptor hash table
from __future__ import print_function
modes = [ modes = [
"1", "1",
"L", "L",

View File

@ -1,5 +1,3 @@
from __future__ import print_function
import os import os
from PIL import Image from PIL import Image
@ -109,4 +107,4 @@ class TestBmpReference(PillowTestCase):
os.path.join(base, "g", "pal4rle.bmp"), os.path.join(base, "g", "pal4rle.bmp"),
) )
if f not in unsupported: if f not in unsupported:
self.fail("Unsupported Image %s: %s" % (f, msg)) self.fail("Unsupported Image {}: {}".format(f, msg))

View File

@ -1,5 +1,3 @@
from __future__ import division
from array import array from array import array
from PIL import Image, ImageFilter from PIL import Image, ImageFilter

View File

@ -1,5 +1,3 @@
from __future__ import division, print_function
import sys import sys
from PIL import Image from PIL import Image

View File

@ -1,5 +1,3 @@
from __future__ import unicode_literals
import io import io
from PIL import features from PIL import features

View File

@ -92,7 +92,7 @@ class TestFileEps(PillowTestCase):
def test_iobase_object(self): def test_iobase_object(self):
# issue 479 # issue 479
image1 = Image.open(file1) image1 = Image.open(file1)
with io.open(self.tempfile("temp_iobase.eps"), "wb") as fh: with open(self.tempfile("temp_iobase.eps"), "wb") as fh:
image1.save(fh, "EPS") image1.save(fh, "EPS")
@unittest.skipUnless(HAS_GHOSTSCRIPT, "Ghostscript not available") @unittest.skipUnless(HAS_GHOSTSCRIPT, "Ghostscript not available")

View File

@ -610,8 +610,7 @@ class TestFileGif(PillowTestCase):
# Tests appending using a generator # Tests appending using a generator
def imGenerator(ims): def imGenerator(ims):
for im in ims: yield from ims
yield im
im.save(out, save_all=True, append_images=imGenerator(ims)) im.save(out, save_all=True, append_images=imGenerator(ims))

View File

@ -1,5 +1,3 @@
from __future__ import print_function
import distutils.version import distutils.version
import io import io
import itertools import itertools
@ -262,7 +260,7 @@ class TestFileLibTiff(LibTiffTestCase):
tc(4.25, TiffTags.FLOAT, True), tc(4.25, TiffTags.FLOAT, True),
tc(4.25, TiffTags.DOUBLE, True), tc(4.25, TiffTags.DOUBLE, True),
tc("custom tag value", TiffTags.ASCII, True), tc("custom tag value", TiffTags.ASCII, True),
tc(u"custom tag value", TiffTags.ASCII, True), tc("custom tag value", TiffTags.ASCII, True),
tc(b"custom tag value", TiffTags.BYTE, True), tc(b"custom tag value", TiffTags.BYTE, True),
tc((4, 5, 6), TiffTags.SHORT, True), tc((4, 5, 6), TiffTags.SHORT, True),
tc((123456789, 9, 34, 234, 219387, 92432323), TiffTags.LONG, True), tc((123456789, 9, 34, 234, 219387, 92432323), TiffTags.LONG, True),

View File

@ -99,8 +99,7 @@ class TestFilePdf(PillowTestCase):
# Test appending using a generator # Test appending using a generator
def imGenerator(ims): def imGenerator(ims):
for im in ims: yield from ims
yield im
im.save(outfile, save_all=True, append_images=imGenerator(ims)) im.save(outfile, save_all=True, append_images=imGenerator(ims))
@ -207,7 +206,7 @@ class TestFilePdf(PillowTestCase):
# append some info # append some info
pdf.info.Title = "abc" pdf.info.Title = "abc"
pdf.info.Author = "def" pdf.info.Author = "def"
pdf.info.Subject = u"ghi\uABCD" pdf.info.Subject = "ghi\uABCD"
pdf.info.Keywords = "qw)e\\r(ty" pdf.info.Keywords = "qw)e\\r(ty"
pdf.info.Creator = "hopper()" pdf.info.Creator = "hopper()"
pdf.start_writing() pdf.start_writing()
@ -235,7 +234,7 @@ class TestFilePdf(PillowTestCase):
self.assertEqual(pdf.info.Title, "abc") self.assertEqual(pdf.info.Title, "abc")
self.assertEqual(pdf.info.Producer, "PdfParser") self.assertEqual(pdf.info.Producer, "PdfParser")
self.assertEqual(pdf.info.Keywords, "qw)e\\r(ty") self.assertEqual(pdf.info.Keywords, "qw)e\\r(ty")
self.assertEqual(pdf.info.Subject, u"ghi\uABCD") self.assertEqual(pdf.info.Subject, "ghi\uABCD")
self.assertIn(b"CreationDate", pdf.info) self.assertIn(b"CreationDate", pdf.info)
self.assertIn(b"ModDate", pdf.info) self.assertIn(b"ModDate", pdf.info)
self.check_pdf_pages_consistency(pdf) self.check_pdf_pages_consistency(pdf)

View File

@ -518,8 +518,7 @@ class TestFileTiff(PillowTestCase):
# Test appending using a generator # Test appending using a generator
def imGenerator(ims): def imGenerator(ims):
for im in ims: yield from ims
yield im
mp = io.BytesIO() mp = io.BytesIO()
im.save(mp, format="TIFF", save_all=True, append_images=imGenerator(ims)) im.save(mp, format="TIFF", save_all=True, append_images=imGenerator(ims))

View File

@ -157,13 +157,13 @@ class TestFileTiffMetadata(PillowTestCase):
self.assert_deep_equal( self.assert_deep_equal(
original[tag], original[tag],
value, value,
"%s didn't roundtrip, %s, %s" % (tag, original[tag], value), "{} didn't roundtrip, {}, {}".format(tag, original[tag], value),
) )
else: else:
self.assertEqual( self.assertEqual(
original[tag], original[tag],
value, value,
"%s didn't roundtrip, %s, %s" % (tag, original[tag], value), "{} didn't roundtrip, {}, {}".format(tag, original[tag], value),
) )
for tag, value in original.items(): for tag, value in original.items():

View File

@ -91,8 +91,7 @@ class TestFileWebpAnimation(PillowTestCase):
# Tests appending using a generator # Tests appending using a generator
def imGenerator(ims): def imGenerator(ims):
for im in ims: yield from ims
yield im
temp_file2 = self.tempfile("temp_generator.webp") temp_file2 = self.tempfile("temp_generator.webp")
frame1.copy().save( frame1.copy().save(

View File

@ -114,9 +114,9 @@ class TestFileWebpMetadata(PillowTestCase):
if not _webp.HAVE_WEBPANIM: if not _webp.HAVE_WEBPANIM:
self.skipTest("WebP animation support not available") self.skipTest("WebP animation support not available")
iccp_data = "<iccp_data>".encode("utf-8") iccp_data = b"<iccp_data>"
exif_data = "<exif_data>".encode("utf-8") exif_data = b"<exif_data>"
xmp_data = "<xmp_data>".encode("utf-8") xmp_data = b"<xmp_data>"
temp_file = self.tempfile("temp.webp") temp_file = self.tempfile("temp.webp")
frame1 = Image.open("Tests/images/anim_frame1.webp") frame1 = Image.open("Tests/images/anim_frame1.webp")

View File

@ -1,5 +1,3 @@
from __future__ import division
import sys import sys
from PIL import Image, ImageDraw, ImageFont, features from PIL import Image, ImageDraw, ImageFont, features

View File

@ -106,7 +106,7 @@ class TestImage(PillowTestCase):
def test_fp_name(self): def test_fp_name(self):
temp_file = self.tempfile("temp.jpg") temp_file = self.tempfile("temp.jpg")
class FP(object): class FP:
def write(a, b): def write(a, b):
pass pass
@ -588,11 +588,11 @@ class TestImage(PillowTestCase):
try: try:
im.load() im.load()
self.assertFail() self.assertFail()
except IOError as e: except OSError as e:
self.assertEqual(str(e), "buffer overrun when reading image file") self.assertEqual(str(e), "buffer overrun when reading image file")
class MockEncoder(object): class MockEncoder:
pass pass

View File

@ -122,7 +122,7 @@ class TestImageGetPixel(AccessTest):
self.assertEqual( self.assertEqual(
im.getpixel((0, 0)), im.getpixel((0, 0)),
c, c,
"put/getpixel roundtrip failed for mode %s, color %s" % (mode, c), "put/getpixel roundtrip failed for mode {}, color {}".format(mode, c),
) )
# check putpixel negative index # check putpixel negative index
@ -151,7 +151,7 @@ class TestImageGetPixel(AccessTest):
self.assertEqual( self.assertEqual(
im.getpixel((0, 0)), im.getpixel((0, 0)),
c, c,
"initial color failed for mode %s, color %s " % (mode, c), "initial color failed for mode {}, color {} ".format(mode, c),
) )
# check initial color negative index # check initial color negative index
self.assertEqual( self.assertEqual(

View File

@ -25,7 +25,7 @@ class TestImageArray(PillowTestCase):
self.assertEqual(test("RGBX"), (3, (100, 128, 4), "|u1", 51200)) self.assertEqual(test("RGBX"), (3, (100, 128, 4), "|u1", 51200))
def test_fromarray(self): def test_fromarray(self):
class Wrapper(object): class Wrapper:
""" Class with API matching Image.fromarray """ """ Class with API matching Image.fromarray """
def __init__(self, img, arr_params): def __init__(self, img, arr_params):

View File

@ -1,5 +1,3 @@
from __future__ import division, print_function
from contextlib import contextmanager from contextlib import contextmanager
from PIL import Image, ImageDraw from PIL import Image, ImageDraw

View File

@ -35,7 +35,7 @@ class TestImageEnhance(PillowTestCase):
self.assert_image_equal( self.assert_image_equal(
im.getchannel("A"), im.getchannel("A"),
original.getchannel("A"), original.getchannel("A"),
"Diff on %s: %s" % (op, amount), "Diff on {}: {}".format(op, amount),
) )
def test_alpha(self): def test_alpha(self):

View File

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
import copy import copy
import distutils.version import distutils.version
import os import os
@ -20,7 +19,7 @@ HAS_FREETYPE = features.check("freetype2")
HAS_RAQM = features.check("raqm") HAS_RAQM = features.check("raqm")
class SimplePatcher(object): class SimplePatcher:
def __init__(self, parent_obj, attr_name, value): def __init__(self, parent_obj, attr_name, value):
self._parent_obj = parent_obj self._parent_obj = parent_obj
self._attr_name = attr_name self._attr_name = attr_name
@ -462,7 +461,7 @@ class TestImageFont(PillowTestCase):
# issue #2826 # issue #2826
font = ImageFont.load_default() font = ImageFont.load_default()
with self.assertRaises(UnicodeEncodeError): with self.assertRaises(UnicodeEncodeError):
font.getsize(u"") font.getsize("")
@unittest.skipIf( @unittest.skipIf(
sys.version.startswith("2") or hasattr(sys, "pypy_translation_info"), sys.version.startswith("2") or hasattr(sys, "pypy_translation_info"),
@ -470,7 +469,7 @@ class TestImageFont(PillowTestCase):
) )
def test_unicode_extended(self): def test_unicode_extended(self):
# issue #3777 # issue #3777
text = u"A\u278A\U0001F12B" text = "A\u278A\U0001F12B"
target = "Tests/images/unicode_extended.png" target = "Tests/images/unicode_extended.png"
ttf = ImageFont.truetype( ttf = ImageFont.truetype(

View File

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
from PIL import Image, ImageDraw, ImageFont, features from PIL import Image, ImageDraw, ImageFont, features
from .helper import PillowTestCase, unittest from .helper import PillowTestCase, unittest

View File

@ -1,5 +1,3 @@
from __future__ import print_function
from PIL import Image, ImageMath from PIL import Image, ImageMath
from .helper import PillowTestCase from .helper import PillowTestCase
@ -7,7 +5,7 @@ from .helper import PillowTestCase
def pixel(im): def pixel(im):
if hasattr(im, "im"): if hasattr(im, "im"):
return "%s %r" % (im.mode, im.getpixel((0, 0))) return "{} {!r}".format(im.mode, im.getpixel((0, 0)))
else: else:
if isinstance(im, int): if isinstance(im, int):
return int(im) # hack to deal with booleans return int(im) # hack to deal with booleans

View File

@ -11,7 +11,7 @@ except ImportError:
class TestImageOps(PillowTestCase): class TestImageOps(PillowTestCase):
class Deformer(object): class Deformer:
def getmesh(self, im): def getmesh(self, im):
x, y = im.size x, y = im.size
return [((0, 0, x, y), (0, 0, x, 0, x, y, y, 0))] return [((0, 0, x, y), (0, 0, x, 0, x, y, y, 0))]

View File

@ -15,7 +15,7 @@ else:
test_case.skipTest("Qt bindings are not installed") test_case.skipTest("Qt bindings are not installed")
class PillowQtTestCase(object): class PillowQtTestCase:
def setUp(self): def setUp(self):
skip_if_qt_is_not_installed(self) skip_if_qt_is_not_installed(self)

View File

@ -1,5 +1,3 @@
from __future__ import print_function
import locale import locale
from PIL import Image from PIL import Image

View File

@ -1,5 +1,3 @@
from __future__ import unicode_literals
import os import os
import subprocess import subprocess
import sys import sys

View File

@ -20,7 +20,11 @@ class TestModeI16(PillowTestCase):
self.assertEqual( self.assertEqual(
p1, p1,
p2, p2,
("got %r from mode %s at %s, expected %r" % (p1, im1.mode, xy, p2)), (
"got {!r} from mode {} at {}, expected {!r}".format(
p1, im1.mode, xy, p2
)
),
) )
def test_basic(self): def test_basic(self):

View File

@ -1,5 +1,3 @@
from __future__ import print_function
from PIL import Image from PIL import Image
from .helper import PillowTestCase, hopper, unittest from .helper import PillowTestCase, hopper, unittest

View File

@ -22,7 +22,7 @@ class TestPdfParser(PillowTestCase):
self.assertEqual(encode_text("abc"), b"\xFE\xFF\x00a\x00b\x00c") self.assertEqual(encode_text("abc"), b"\xFE\xFF\x00a\x00b\x00c")
self.assertEqual(decode_text(b"\xFE\xFF\x00a\x00b\x00c"), "abc") self.assertEqual(decode_text(b"\xFE\xFF\x00a\x00b\x00c"), "abc")
self.assertEqual(decode_text(b"abc"), "abc") self.assertEqual(decode_text(b"abc"), "abc")
self.assertEqual(decode_text(b"\x1B a \x1C"), u"\u02D9 a \u02DD") self.assertEqual(decode_text(b"\x1B a \x1C"), "\u02D9 a \u02DD")
def test_indirect_refs(self): def test_indirect_refs(self):
self.assertEqual(IndirectReference(1, 2), IndirectReference(1, 2)) self.assertEqual(IndirectReference(1, 2), IndirectReference(1, 2))

View File

@ -57,7 +57,7 @@ if ImageQt.qt_is_installed:
class Example(QWidget): class Example(QWidget):
def __init__(self): def __init__(self):
super(Example, self).__init__() super().__init__()
img = hopper().resize((1000, 1000)) img = hopper().resize((1000, 1000))

View File

@ -1,5 +1,3 @@
from __future__ import print_function
import io import io
import queue import queue
import sys import sys

View File

@ -1,5 +1,3 @@
from __future__ import print_function
from PIL import Image from PIL import Image

View File

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# #
# Pillow (PIL Fork) documentation build configuration file, created by # Pillow (PIL Fork) documentation build configuration file, created by
# sphinx-quickstart on Sat Apr 4 07:54:11 2015. # sphinx-quickstart on Sat Apr 4 07:54:11 2015.
@ -42,9 +41,9 @@ source_suffix = ".rst"
master_doc = "index" master_doc = "index"
# General information about the project. # General information about the project.
project = u"Pillow (PIL Fork)" project = "Pillow (PIL Fork)"
copyright = u"1995-2011 Fredrik Lundh, 2010-2019 Alex Clark and Contributors" copyright = "1995-2011 Fredrik Lundh, 2010-2019 Alex Clark and Contributors"
author = u"Fredrik Lundh, Alex Clark and Contributors" author = "Fredrik Lundh, Alex Clark and Contributors"
# The version info for the project you're documenting, acts as replacement for # The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the # |version| and |release|, also used in various other places throughout the
@ -220,8 +219,8 @@ latex_documents = [
( (
master_doc, master_doc,
"PillowPILFork.tex", "PillowPILFork.tex",
u"Pillow (PIL Fork) Documentation", "Pillow (PIL Fork) Documentation",
u"Alex Clark", "Alex Clark",
"manual", "manual",
) )
] ]
@ -252,7 +251,7 @@ latex_documents = [
# One entry per manual page. List of tuples # One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section). # (source start file, name, description, authors, manual section).
man_pages = [ man_pages = [
(master_doc, "pillowpilfork", u"Pillow (PIL Fork) Documentation", [author], 1) (master_doc, "pillowpilfork", "Pillow (PIL Fork) Documentation", [author], 1)
] ]
# If true, show URL addresses after external links. # If true, show URL addresses after external links.
@ -268,7 +267,7 @@ texinfo_documents = [
( (
master_doc, master_doc,
"PillowPILFork", "PillowPILFork",
u"Pillow (PIL Fork) Documentation", "Pillow (PIL Fork) Documentation",
author, author,
"PillowPILFork", "PillowPILFork",
"Pillow is the friendly PIL fork by Alex Clark and Contributors.", "Pillow is the friendly PIL fork by Alex Clark and Contributors.",

View File

@ -212,10 +212,10 @@ class DdsImageFile(ImageFile.ImageFile):
def _open(self): def _open(self):
magic, header_size = struct.unpack("<II", self.fp.read(8)) magic, header_size = struct.unpack("<II", self.fp.read(8))
if header_size != 124: if header_size != 124:
raise IOError("Unsupported header size %r" % (header_size)) raise OSError("Unsupported header size %r" % (header_size))
header_bytes = self.fp.read(header_size - 4) header_bytes = self.fp.read(header_size - 4)
if len(header_bytes) != 120: if len(header_bytes) != 120:
raise IOError("Incomplete header: %s bytes" % len(header_bytes)) raise OSError("Incomplete header: %s bytes" % len(header_bytes))
header = BytesIO(header_bytes) header = BytesIO(header_bytes)
flags, height, width = struct.unpack("<3I", header.read(12)) flags, height, width = struct.unpack("<3I", header.read(12))
@ -250,7 +250,7 @@ class DXT1Decoder(ImageFile.PyDecoder):
try: try:
self.set_as_raw(_dxt1(self.fd, self.state.xsize, self.state.ysize)) self.set_as_raw(_dxt1(self.fd, self.state.xsize, self.state.ysize))
except struct.error: except struct.error:
raise IOError("Truncated DDS file") raise OSError("Truncated DDS file")
return 0, 0 return 0, 0
@ -261,7 +261,7 @@ class DXT5Decoder(ImageFile.PyDecoder):
try: try:
self.set_as_raw(_dxt5(self.fd, self.state.xsize, self.state.ysize)) self.set_as_raw(_dxt5(self.fd, self.state.xsize, self.state.ysize))
except struct.error: except struct.error:
raise IOError("Truncated DDS file") raise OSError("Truncated DDS file")
return 0, 0 return 0, 0

View File

@ -1,6 +1,5 @@
#!/usr/bin/env python #!/usr/bin/env python
# minimal sanity check # minimal sanity check
from __future__ import print_function
import os import os
import sys import sys

View File

@ -7,7 +7,6 @@
# Final rating: 10/10 # Final rating: 10/10
# Your cheese is so fresh most people think it's a cream: Mascarpone # Your cheese is so fresh most people think it's a cream: Mascarpone
# ------------------------------ # ------------------------------
from __future__ import print_function
import os import os
import re import re
@ -299,8 +298,7 @@ class pil_build_ext(build_ext):
return getattr(self, feat) is None return getattr(self, feat) is None
def __iter__(self): def __iter__(self):
for x in self.features: yield from self.features
yield x
feature = feature() feature = feature()
@ -335,7 +333,7 @@ class pil_build_ext(build_ext):
_dbg("Disabling %s", x) _dbg("Disabling %s", x)
if getattr(self, "enable_%s" % x): if getattr(self, "enable_%s" % x):
raise ValueError( raise ValueError(
"Conflicting options: --enable-%s and --disable-%s" % (x, x) "Conflicting options: --enable-{} and --disable-{}".format(x, x)
) )
if getattr(self, "enable_%s" % x): if getattr(self, "enable_%s" % x):
_dbg("Requiring %s", x) _dbg("Requiring %s", x)
@ -707,7 +705,7 @@ class pil_build_ext(build_ext):
defs.append(("HAVE_LIBTIFF", None)) defs.append(("HAVE_LIBTIFF", None))
if sys.platform == "win32": if sys.platform == "win32":
libs.extend(["kernel32", "user32", "gdi32"]) libs.extend(["kernel32", "user32", "gdi32"])
if struct.unpack("h", "\0\1".encode("ascii"))[0] == 1: if struct.unpack("h", b"\0\1")[0] == 1:
defs.append(("WORDS_BIGENDIAN", None)) defs.append(("WORDS_BIGENDIAN", None))
if sys.platform == "win32" and not (PLATFORM_PYPY or PLATFORM_MINGW): if sys.platform == "win32" and not (PLATFORM_PYPY or PLATFORM_MINGW):
@ -788,7 +786,7 @@ class pil_build_ext(build_ext):
print("-" * 68) print("-" * 68)
print("version Pillow %s" % PILLOW_VERSION) print("version Pillow %s" % PILLOW_VERSION)
v = sys.version.split("[") v = sys.version.split("[")
print("platform %s %s" % (sys.platform, v[0].strip())) print("platform {} {}".format(sys.platform, v[0].strip()))
for v in v[1:]: for v in v[1:]:
print(" [%s" % v.strip()) print(" [%s" % v.strip())
print("-" * 68) print("-" * 68)
@ -811,7 +809,7 @@ class pil_build_ext(build_ext):
version = "" version = ""
if len(option) >= 3 and option[2]: if len(option) >= 3 and option[2]:
version = " (%s)" % option[2] version = " (%s)" % option[2]
print("--- %s support available%s" % (option[1], version)) print("--- {} support available{}".format(option[1], version))
else: else:
print("*** %s support not available" % option[1]) print("*** %s support not available" % option[1])
all = 0 all = 0

View File

@ -17,7 +17,6 @@
# See the README file for information on usage and redistribution. # See the README file for information on usage and redistribution.
# #
from __future__ import print_function
from . import FontFile, Image from . import FontFile, Image

View File

@ -283,7 +283,7 @@ class _BLPBaseDecoder(ImageFile.PyDecoder):
self._read_blp_header() self._read_blp_header()
self._load() self._load()
except struct.error: except struct.error:
raise IOError("Truncated Blp file") raise OSError("Truncated Blp file")
return 0, 0 return 0, 0
def _read_palette(self): def _read_palette(self):

View File

@ -148,7 +148,7 @@ class BmpImageFile(ImageFile.ImageFile):
file_info["a_mask"], file_info["a_mask"],
) )
else: else:
raise IOError("Unsupported BMP header type (%d)" % file_info["header_size"]) raise OSError("Unsupported BMP header type (%d)" % file_info["header_size"])
# ------------------ Special case : header is reported 40, which # ------------------ Special case : header is reported 40, which
# ---------------------- is shorter than real size for bpp >= 16 # ---------------------- is shorter than real size for bpp >= 16
@ -163,12 +163,12 @@ class BmpImageFile(ImageFile.ImageFile):
# ------------------------------- Check abnormal values for DOS attacks # ------------------------------- Check abnormal values for DOS attacks
if file_info["width"] * file_info["height"] > 2 ** 31: if file_info["width"] * file_info["height"] > 2 ** 31:
raise IOError("Unsupported BMP Size: (%dx%d)" % self.size) raise OSError("Unsupported BMP Size: (%dx%d)" % self.size)
# ---------------------- Check bit depth for unusual unsupported values # ---------------------- Check bit depth for unusual unsupported values
self.mode, raw_mode = BIT2MODE.get(file_info["bits"], (None, None)) self.mode, raw_mode = BIT2MODE.get(file_info["bits"], (None, None))
if self.mode is None: if self.mode is None:
raise IOError("Unsupported BMP pixel depth (%d)" % file_info["bits"]) raise OSError("Unsupported BMP pixel depth (%d)" % file_info["bits"])
# ---------------- Process BMP with Bitfields compression (not palette) # ---------------- Process BMP with Bitfields compression (not palette)
if file_info["compression"] == self.BITFIELDS: if file_info["compression"] == self.BITFIELDS:
@ -206,21 +206,21 @@ class BmpImageFile(ImageFile.ImageFile):
): ):
raw_mode = MASK_MODES[(file_info["bits"], file_info["rgb_mask"])] raw_mode = MASK_MODES[(file_info["bits"], file_info["rgb_mask"])]
else: else:
raise IOError("Unsupported BMP bitfields layout") raise OSError("Unsupported BMP bitfields layout")
else: else:
raise IOError("Unsupported BMP bitfields layout") raise OSError("Unsupported BMP bitfields layout")
elif file_info["compression"] == self.RAW: elif file_info["compression"] == self.RAW:
if file_info["bits"] == 32 and header == 22: # 32-bit .cur offset if file_info["bits"] == 32 and header == 22: # 32-bit .cur offset
raw_mode, self.mode = "BGRA", "RGBA" raw_mode, self.mode = "BGRA", "RGBA"
else: else:
raise IOError("Unsupported BMP compression (%d)" % file_info["compression"]) raise OSError("Unsupported BMP compression (%d)" % file_info["compression"])
# --------------- Once the header is processed, process the palette/LUT # --------------- Once the header is processed, process the palette/LUT
if self.mode == "P": # Paletted for 1, 4 and 8 bit images if self.mode == "P": # Paletted for 1, 4 and 8 bit images
# ---------------------------------------------------- 1-bit images # ---------------------------------------------------- 1-bit images
if not (0 < file_info["colors"] <= 65536): if not (0 < file_info["colors"] <= 65536):
raise IOError("Unsupported BMP Palette size (%d)" % file_info["colors"]) raise OSError("Unsupported BMP Palette size (%d)" % file_info["colors"])
else: else:
padding = file_info["palette_padding"] padding = file_info["palette_padding"]
palette = read(padding * file_info["colors"]) palette = read(padding * file_info["colors"])
@ -309,7 +309,7 @@ def _save(im, fp, filename, bitmap_header=True):
try: try:
rawmode, bits, colors = SAVE[im.mode] rawmode, bits, colors = SAVE[im.mode]
except KeyError: except KeyError:
raise IOError("cannot write mode %s as BMP" % im.mode) raise OSError("cannot write mode %s as BMP" % im.mode)
info = im.encoderinfo info = im.encoderinfo

View File

@ -60,7 +60,7 @@ class BufrStubImageFile(ImageFile.StubImageFile):
def _save(im, fp, filename): def _save(im, fp, filename):
if _handler is None or not hasattr("_handler", "save"): if _handler is None or not hasattr("_handler", "save"):
raise IOError("BUFR save handler not installed") raise OSError("BUFR save handler not installed")
_handler.save(im, fp, filename) _handler.save(im, fp, filename)

View File

@ -21,7 +21,7 @@
import io import io
class ContainerIO(object): class ContainerIO:
def __init__(self, file, offset, length): def __init__(self, file, offset, length):
""" """
Create file object. Create file object.

View File

@ -15,9 +15,6 @@
# #
# See the README file for information on usage and redistribution. # See the README file for information on usage and redistribution.
# #
from __future__ import print_function
from . import BmpImagePlugin, Image from . import BmpImagePlugin, Image
from ._binary import i8, i16le as i16, i32le as i32 from ._binary import i8, i16le as i16, i32le as i32

View File

@ -106,10 +106,10 @@ class DdsImageFile(ImageFile.ImageFile):
def _open(self): def _open(self):
magic, header_size = struct.unpack("<II", self.fp.read(8)) magic, header_size = struct.unpack("<II", self.fp.read(8))
if header_size != 124: if header_size != 124:
raise IOError("Unsupported header size %r" % (header_size)) raise OSError("Unsupported header size %r" % (header_size))
header_bytes = self.fp.read(header_size - 4) header_bytes = self.fp.read(header_size - 4)
if len(header_bytes) != 120: if len(header_bytes) != 120:
raise IOError("Incomplete header: %s bytes" % len(header_bytes)) raise OSError("Incomplete header: %s bytes" % len(header_bytes))
header = BytesIO(header_bytes) header = BytesIO(header_bytes)
flags, height, width = struct.unpack("<3I", header.read(12)) flags, height, width = struct.unpack("<3I", header.read(12))

View File

@ -139,7 +139,7 @@ def Ghostscript(tile, size, fp, scale=1):
if gs_windows_binary is not None: if gs_windows_binary is not None:
if not gs_windows_binary: if not gs_windows_binary:
raise WindowsError("Unable to locate Ghostscript on paths") raise OSError("Unable to locate Ghostscript on paths")
command[0] = gs_windows_binary command[0] = gs_windows_binary
# push data through Ghostscript # push data through Ghostscript
@ -162,7 +162,7 @@ def Ghostscript(tile, size, fp, scale=1):
return im.im.copy() return im.im.copy()
class PSFile(object): class PSFile:
""" """
Wrapper for bytesio object that treats either CR or LF as end of line. Wrapper for bytesio object that treats either CR or LF as end of line.
""" """
@ -272,7 +272,7 @@ class EpsImageFile(ImageFile.ImageFile):
# tools mistakenly put in the Comments section # tools mistakenly put in the Comments section
pass pass
else: else:
raise IOError("bad EPS header") raise OSError("bad EPS header")
s_raw = fp.readline() s_raw = fp.readline()
s = s_raw.strip("\r\n") s = s_raw.strip("\r\n")
@ -307,7 +307,7 @@ class EpsImageFile(ImageFile.ImageFile):
break break
if not box: if not box:
raise IOError("cannot determine EPS bounding box") raise OSError("cannot determine EPS bounding box")
def _find_offset(self, fp): def _find_offset(self, fp):

View File

@ -63,7 +63,7 @@ class FITSStubImageFile(ImageFile.StubImageFile):
def _save(im, fp, filename): def _save(im, fp, filename):
if _handler is None or not hasattr("_handler", "save"): if _handler is None or not hasattr("_handler", "save"):
raise IOError("FITS save handler not installed") raise OSError("FITS save handler not installed")
_handler.save(im, fp, filename) _handler.save(im, fp, filename)

View File

@ -14,7 +14,6 @@
# See the README file for information on usage and redistribution. # See the README file for information on usage and redistribution.
# #
from __future__ import print_function
import os import os
@ -35,7 +34,7 @@ def puti16(fp, values):
# Base class for raster font file handlers. # Base class for raster font file handlers.
class FontFile(object): class FontFile:
bitmap = None bitmap = None

View File

@ -14,9 +14,6 @@
# #
# See the README file for information on usage and redistribution. # See the README file for information on usage and redistribution.
# #
from __future__ import print_function
import olefile import olefile
from . import Image, ImageFile from . import Image, ImageFile
@ -66,7 +63,7 @@ class FpxImageFile(ImageFile.ImageFile):
try: try:
self.ole = olefile.OleFileIO(self.fp) self.ole = olefile.OleFileIO(self.fp)
except IOError: except OSError:
raise SyntaxError("not an FPX file; invalid OLE file") raise SyntaxError("not an FPX file; invalid OLE file")
if self.ole.root.clsid != "56616700-C154-11CE-8553-00AA00A1F95B": if self.ole.root.clsid != "56616700-C154-11CE-8553-00AA00A1F95B":
@ -145,7 +142,7 @@ class FpxImageFile(ImageFile.ImageFile):
length = i32(s, 32) length = i32(s, 32)
if size != self.size: if size != self.size:
raise IOError("subimage mismatch") raise OSError("subimage mismatch")
# get tile descriptors # get tile descriptors
fp.seek(28 + offset) fp.seek(28 + offset)
@ -218,7 +215,7 @@ class FpxImageFile(ImageFile.ImageFile):
self.tile_prefix = self.jpeg[jpeg_tables] self.tile_prefix = self.jpeg[jpeg_tables]
else: else:
raise IOError("unknown/invalid compression") raise OSError("unknown/invalid compression")
x = x + xtile x = x + xtile
if x >= xsize: if x >= xsize:

View File

@ -87,4 +87,4 @@ def open(fp, mode="r"):
try: try:
return GdImageFile(fp) return GdImageFile(fp)
except SyntaxError: except SyntaxError:
raise IOError("cannot identify this image file") raise OSError("cannot identify this image file")

View File

@ -853,7 +853,7 @@ def getdata(im, offset=(0, 0), **params):
""" """
class Collector(object): class Collector:
data = [] data = []
def write(self, data): def write(self, data):

View File

@ -60,7 +60,7 @@ def sphere_decreasing(middle, pos):
SEGMENTS = [linear, curved, sine, sphere_increasing, sphere_decreasing] SEGMENTS = [linear, curved, sine, sphere_increasing, sphere_decreasing]
class GradientFile(object): class GradientFile:
gradient = None gradient = None
@ -132,7 +132,7 @@ class GimpGradientFile(GradientFile):
cspace = int(s[12]) cspace = int(s[12])
if cspace != 0: if cspace != 0:
raise IOError("cannot handle HSV colour space") raise OSError("cannot handle HSV colour space")
gradient.append((x0, x1, xm, rgb0, rgb1, segment)) gradient.append((x0, x1, xm, rgb0, rgb1, segment))

View File

@ -22,7 +22,7 @@ from ._binary import o8
# File handler for GIMP's palette format. # File handler for GIMP's palette format.
class GimpPaletteFile(object): class GimpPaletteFile:
rawmode = "RGB" rawmode = "RGB"

View File

@ -61,7 +61,7 @@ class GribStubImageFile(ImageFile.StubImageFile):
def _save(im, fp, filename): def _save(im, fp, filename):
if _handler is None or not hasattr("_handler", "save"): if _handler is None or not hasattr("_handler", "save"):
raise IOError("GRIB save handler not installed") raise OSError("GRIB save handler not installed")
_handler.save(im, fp, filename) _handler.save(im, fp, filename)

View File

@ -60,7 +60,7 @@ class HDF5StubImageFile(ImageFile.StubImageFile):
def _save(im, fp, filename): def _save(im, fp, filename):
if _handler is None or not hasattr("_handler", "save"): if _handler is None or not hasattr("_handler", "save"):
raise IOError("HDF5 save handler not installed") raise OSError("HDF5 save handler not installed")
_handler.save(im, fp, filename) _handler.save(im, fp, filename)

View File

@ -128,7 +128,7 @@ def read_png_or_jpeg2000(fobj, start_length, size):
raise ValueError("Unsupported icon subimage format") raise ValueError("Unsupported icon subimage format")
class IcnsFile(object): class IcnsFile:
SIZES = { SIZES = {
(512, 512, 2): [(b"ic10", read_png_or_jpeg2000)], (512, 512, 2): [(b"ic10", read_png_or_jpeg2000)],

View File

@ -86,7 +86,7 @@ def _accept(prefix):
return prefix[:4] == _MAGIC return prefix[:4] == _MAGIC
class IcoFile(object): class IcoFile:
def __init__(self, buf): def __init__(self, buf):
""" """
Parse image from file-like object containing ico file data Parse image from file-like object containing ico file data

View File

@ -55,7 +55,7 @@ class DecompressionBombError(Exception):
pass pass
class _imaging_not_installed(object): class _imaging_not_installed:
# module placeholder # module placeholder
def __getattr__(self, id): def __getattr__(self, id):
raise ImportError("The _imaging C module is not installed") raise ImportError("The _imaging C module is not installed")
@ -427,7 +427,7 @@ def _getdecoder(mode, decoder_name, args, extra=()):
decoder = getattr(core, decoder_name + "_decoder") decoder = getattr(core, decoder_name + "_decoder")
return decoder(mode, *args + extra) return decoder(mode, *args + extra)
except AttributeError: except AttributeError:
raise IOError("decoder %s not available" % decoder_name) raise OSError("decoder %s not available" % decoder_name)
def _getencoder(mode, encoder_name, args, extra=()): def _getencoder(mode, encoder_name, args, extra=()):
@ -448,7 +448,7 @@ def _getencoder(mode, encoder_name, args, extra=()):
encoder = getattr(core, encoder_name + "_encoder") encoder = getattr(core, encoder_name + "_encoder")
return encoder(mode, *args + extra) return encoder(mode, *args + extra)
except AttributeError: except AttributeError:
raise IOError("encoder %s not available" % encoder_name) raise OSError("encoder %s not available" % encoder_name)
# -------------------------------------------------------------------- # --------------------------------------------------------------------
@ -459,7 +459,7 @@ def coerce_e(value):
return value if isinstance(value, _E) else _E(value) return value if isinstance(value, _E) else _E(value)
class _E(object): class _E:
def __init__(self, data): def __init__(self, data):
self.data = data self.data = data
@ -500,7 +500,7 @@ def _getscaleoffset(expr):
# Implementation wrapper # Implementation wrapper
class Image(object): class Image:
""" """
This class represents an image object. To create This class represents an image object. To create
:py:class:`~PIL.Image.Image` objects, use the appropriate factory :py:class:`~PIL.Image.Image` objects, use the appropriate factory
@ -2389,12 +2389,12 @@ class Image(object):
# Abstract handlers. # Abstract handlers.
class ImagePointHandler(object): class ImagePointHandler:
# used as a mixin by point transforms (for use with im.point) # used as a mixin by point transforms (for use with im.point)
pass pass
class ImageTransformHandler(object): class ImageTransformHandler:
# 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
@ -2772,7 +2772,7 @@ def open(fp, mode="r"):
fp.close() fp.close()
for message in accept_warnings: for message in accept_warnings:
warnings.warn(message) warnings.warn(message)
raise IOError("cannot identify image file %r" % (filename if filename else fp)) raise OSError("cannot identify image file %r" % (filename if filename else fp))
# #

View File

@ -15,8 +15,6 @@
# See the README file for information on usage and redistribution. See # See the README file for information on usage and redistribution. See
# below for the original description. # below for the original description.
from __future__ import print_function
import sys import sys
from PIL import Image from PIL import Image
@ -152,7 +150,7 @@ for flag in FLAGS.values():
# Profile. # Profile.
class ImageCmsProfile(object): class ImageCmsProfile:
def __init__(self, profile): def __init__(self, profile):
""" """
:param profile: Either a string representing a filename, :param profile: Either a string representing a filename,
@ -374,7 +372,7 @@ def profileToProfile(
imOut = None imOut = None
else: else:
imOut = transform.apply(im) imOut = transform.apply(im)
except (IOError, TypeError, ValueError) as v: except (OSError, TypeError, ValueError) as v:
raise PyCMSError(v) raise PyCMSError(v)
return imOut return imOut
@ -398,7 +396,7 @@ def getOpenProfile(profileFilename):
try: try:
return ImageCmsProfile(profileFilename) return ImageCmsProfile(profileFilename)
except (IOError, TypeError, ValueError) as v: except (OSError, TypeError, ValueError) as v:
raise PyCMSError(v) raise PyCMSError(v)
@ -479,7 +477,7 @@ def buildTransform(
return ImageCmsTransform( return ImageCmsTransform(
inputProfile, outputProfile, inMode, outMode, renderingIntent, flags=flags inputProfile, outputProfile, inMode, outMode, renderingIntent, flags=flags
) )
except (IOError, TypeError, ValueError) as v: except (OSError, TypeError, ValueError) as v:
raise PyCMSError(v) raise PyCMSError(v)
@ -590,7 +588,7 @@ def buildProofTransform(
proofRenderingIntent, proofRenderingIntent,
flags, flags,
) )
except (IOError, TypeError, ValueError) as v: except (OSError, TypeError, ValueError) as v:
raise PyCMSError(v) raise PyCMSError(v)
@ -733,9 +731,9 @@ def getProfileName(profile):
return (profile.profile.profile_description or "") + "\n" return (profile.profile.profile_description or "") + "\n"
if not manufacturer or len(model) > 30: if not manufacturer or len(model) > 30:
return model + "\n" return model + "\n"
return "%s - %s\n" % (model, manufacturer) return "{} - {}\n".format(model, manufacturer)
except (AttributeError, IOError, TypeError, ValueError) as v: except (AttributeError, OSError, TypeError, ValueError) as v:
raise PyCMSError(v) raise PyCMSError(v)
@ -775,7 +773,7 @@ def getProfileInfo(profile):
arr.append(elt) arr.append(elt)
return "\r\n\r\n".join(arr) + "\r\n\r\n" return "\r\n\r\n".join(arr) + "\r\n\r\n"
except (AttributeError, IOError, TypeError, ValueError) as v: except (AttributeError, OSError, TypeError, ValueError) as v:
raise PyCMSError(v) raise PyCMSError(v)
@ -803,7 +801,7 @@ def getProfileCopyright(profile):
if not isinstance(profile, ImageCmsProfile): if not isinstance(profile, ImageCmsProfile):
profile = ImageCmsProfile(profile) profile = ImageCmsProfile(profile)
return (profile.profile.copyright or "") + "\n" return (profile.profile.copyright or "") + "\n"
except (AttributeError, IOError, TypeError, ValueError) as v: except (AttributeError, OSError, TypeError, ValueError) as v:
raise PyCMSError(v) raise PyCMSError(v)
@ -831,7 +829,7 @@ def getProfileManufacturer(profile):
if not isinstance(profile, ImageCmsProfile): if not isinstance(profile, ImageCmsProfile):
profile = ImageCmsProfile(profile) profile = ImageCmsProfile(profile)
return (profile.profile.manufacturer or "") + "\n" return (profile.profile.manufacturer or "") + "\n"
except (AttributeError, IOError, TypeError, ValueError) as v: except (AttributeError, OSError, TypeError, ValueError) as v:
raise PyCMSError(v) raise PyCMSError(v)
@ -860,7 +858,7 @@ def getProfileModel(profile):
if not isinstance(profile, ImageCmsProfile): if not isinstance(profile, ImageCmsProfile):
profile = ImageCmsProfile(profile) profile = ImageCmsProfile(profile)
return (profile.profile.model or "") + "\n" return (profile.profile.model or "") + "\n"
except (AttributeError, IOError, TypeError, ValueError) as v: except (AttributeError, OSError, TypeError, ValueError) as v:
raise PyCMSError(v) raise PyCMSError(v)
@ -889,7 +887,7 @@ def getProfileDescription(profile):
if not isinstance(profile, ImageCmsProfile): if not isinstance(profile, ImageCmsProfile):
profile = ImageCmsProfile(profile) profile = ImageCmsProfile(profile)
return (profile.profile.profile_description or "") + "\n" return (profile.profile.profile_description or "") + "\n"
except (AttributeError, IOError, TypeError, ValueError) as v: except (AttributeError, OSError, TypeError, ValueError) as v:
raise PyCMSError(v) raise PyCMSError(v)
@ -928,7 +926,7 @@ def getDefaultIntent(profile):
if not isinstance(profile, ImageCmsProfile): if not isinstance(profile, ImageCmsProfile):
profile = ImageCmsProfile(profile) profile = ImageCmsProfile(profile)
return profile.profile.rendering_intent return profile.profile.rendering_intent
except (AttributeError, IOError, TypeError, ValueError) as v: except (AttributeError, OSError, TypeError, ValueError) as v:
raise PyCMSError(v) raise PyCMSError(v)
@ -979,7 +977,7 @@ def isIntentSupported(profile, intent, direction):
return 1 return 1
else: else:
return -1 return -1
except (AttributeError, IOError, TypeError, ValueError) as v: except (AttributeError, OSError, TypeError, ValueError) as v:
raise PyCMSError(v) raise PyCMSError(v)

View File

@ -45,7 +45,7 @@ directly.
""" """
class ImageDraw(object): class ImageDraw:
def __init__(self, im, mode=None): def __init__(self, im, mode=None):
""" """
Create a drawing instance. Create a drawing instance.

View File

@ -19,25 +19,25 @@
from . import Image, ImageColor, ImageDraw, ImageFont, ImagePath from . import Image, ImageColor, ImageDraw, ImageFont, ImagePath
class Pen(object): class Pen:
def __init__(self, color, width=1, opacity=255): def __init__(self, color, width=1, opacity=255):
self.color = ImageColor.getrgb(color) self.color = ImageColor.getrgb(color)
self.width = width self.width = width
class Brush(object): class Brush:
def __init__(self, color, opacity=255): def __init__(self, color, opacity=255):
self.color = ImageColor.getrgb(color) self.color = ImageColor.getrgb(color)
class Font(object): class Font:
def __init__(self, color, file, size=12): def __init__(self, color, file, size=12):
# FIXME: add support for bitmap fonts # FIXME: add support for bitmap fonts
self.color = ImageColor.getrgb(color) self.color = ImageColor.getrgb(color)
self.font = ImageFont.truetype(file, size) self.font = ImageFont.truetype(file, size)
class Draw(object): class Draw:
def __init__(self, image, size=None, color=None): def __init__(self, image, size=None, color=None):
if not hasattr(image, "im"): if not hasattr(image, "im"):
image = Image.new(image, size, color) image = Image.new(image, size, color)

View File

@ -21,7 +21,7 @@
from . import Image, ImageFilter, ImageStat from . import Image, ImageFilter, ImageStat
class _Enhance(object): class _Enhance:
def enhance(self, factor): def enhance(self, factor):
""" """
Returns an enhanced image. Returns an enhanced image.

View File

@ -56,7 +56,7 @@ def raise_ioerror(error):
message = ERRORS.get(error) message = ERRORS.get(error)
if not message: if not message:
message = "decoder error %d" % error message = "decoder error %d" % error
raise IOError(message + " when reading image file") raise OSError(message + " when reading image file")
# #
@ -145,7 +145,7 @@ class ImageFile(Image.Image):
pixel = Image.Image.load(self) pixel = Image.Image.load(self)
if self.tile is None: if self.tile is None:
raise IOError("cannot load this image") raise OSError("cannot load this image")
if not self.tile: if not self.tile:
return pixel return pixel
@ -203,7 +203,7 @@ class ImageFile(Image.Image):
# we might need to reload the palette data. # we might need to reload the palette data.
if self.palette: if self.palette:
self.palette.dirty = 1 self.palette.dirty = 1
except (AttributeError, EnvironmentError, ImportError): except (AttributeError, OSError, ImportError):
self.map = None self.map = None
self.load_prepare() self.load_prepare()
@ -238,13 +238,13 @@ class ImageFile(Image.Image):
if LOAD_TRUNCATED_IMAGES: if LOAD_TRUNCATED_IMAGES:
break break
else: else:
raise IOError("image file is truncated") raise OSError("image file is truncated")
if not s: # truncated jpeg if not s: # truncated jpeg
if LOAD_TRUNCATED_IMAGES: if LOAD_TRUNCATED_IMAGES:
break break
else: else:
raise IOError( raise OSError(
"image file is truncated " "image file is truncated "
"(%d bytes not processed)" % len(b) "(%d bytes not processed)" % len(b)
) )
@ -322,7 +322,7 @@ class StubImageFile(ImageFile):
def load(self): def load(self):
loader = self._load() loader = self._load()
if loader is None: if loader is None:
raise IOError("cannot find loader for this %s file" % self.format) raise OSError("cannot find loader for this %s file" % self.format)
image = loader.load(self) image = loader.load(self)
assert image is not None assert image is not None
# become the other object (!) # become the other object (!)
@ -334,7 +334,7 @@ class StubImageFile(ImageFile):
raise NotImplementedError("StubImageFile subclass must implement _load") raise NotImplementedError("StubImageFile subclass must implement _load")
class Parser(object): class Parser:
""" """
Incremental image parser. This class implements the standard Incremental image parser. This class implements the standard
feed/close consumer interface. feed/close consumer interface.
@ -411,7 +411,7 @@ class Parser(object):
try: try:
with io.BytesIO(self.data) as fp: with io.BytesIO(self.data) as fp:
im = Image.open(fp) im = Image.open(fp)
except IOError: except OSError:
# traceback.print_exc() # traceback.print_exc()
pass # not enough data pass # not enough data
else: else:
@ -456,9 +456,9 @@ class Parser(object):
self.feed(b"") self.feed(b"")
self.data = self.decoder = None self.data = self.decoder = None
if not self.finished: if not self.finished:
raise IOError("image was incomplete") raise OSError("image was incomplete")
if not self.image: if not self.image:
raise IOError("cannot parse this image") raise OSError("cannot parse this image")
if self.data: if self.data:
# incremental parsing not possible; reopen the file # incremental parsing not possible; reopen the file
# not that we have all data # not that we have all data
@ -514,7 +514,7 @@ def _save(im, fp, tile, bufsize=0):
if s: if s:
break break
if s < 0: if s < 0:
raise IOError("encoder error %d when writing image file" % s) raise OSError("encoder error %d when writing image file" % s)
e.cleanup() e.cleanup()
else: else:
# slight speedup: compress to real file object # slight speedup: compress to real file object
@ -529,7 +529,7 @@ def _save(im, fp, tile, bufsize=0):
else: else:
s = e.encode_to_file(fh, bufsize) s = e.encode_to_file(fh, bufsize)
if s < 0: if s < 0:
raise IOError("encoder error %d when writing image file" % s) raise OSError("encoder error %d when writing image file" % s)
e.cleanup() e.cleanup()
if hasattr(fp, "flush"): if hasattr(fp, "flush"):
fp.flush() fp.flush()
@ -559,7 +559,7 @@ def _safe_read(fp, size):
return b"".join(data) return b"".join(data)
class PyCodecState(object): class PyCodecState:
def __init__(self): def __init__(self):
self.xsize = 0 self.xsize = 0
self.ysize = 0 self.ysize = 0
@ -570,7 +570,7 @@ class PyCodecState(object):
return (self.xoff, self.yoff, self.xoff + self.xsize, self.yoff + self.ysize) return (self.xoff, self.yoff, self.xoff + self.xsize, self.yoff + self.ysize)
class PyDecoder(object): class PyDecoder:
""" """
Python implementation of a format decoder. Override this class and Python implementation of a format decoder. Override this class and
add the decoding logic in the `decode` method. add the decoding logic in the `decode` method.

View File

@ -14,9 +14,6 @@
# #
# See the README file for information on usage and redistribution. # See the README file for information on usage and redistribution.
# #
from __future__ import division
import functools import functools
try: try:
@ -25,7 +22,7 @@ except ImportError: # pragma: no cover
numpy = None numpy = None
class Filter(object): class Filter:
pass pass

View File

@ -35,7 +35,7 @@ LAYOUT_BASIC = 0
LAYOUT_RAQM = 1 LAYOUT_RAQM = 1
class _imagingft_not_installed(object): class _imagingft_not_installed:
# module placeholder # module placeholder
def __getattr__(self, id): def __getattr__(self, id):
raise ImportError("The _imagingft C module is not installed") raise ImportError("The _imagingft C module is not installed")
@ -63,7 +63,7 @@ except ImportError:
# -------------------------------------------------------------------- # --------------------------------------------------------------------
class ImageFont(object): class ImageFont:
"PIL font wrapper" "PIL font wrapper"
def _load_pilfont(self, filename): def _load_pilfont(self, filename):
@ -79,7 +79,7 @@ class ImageFont(object):
if image and image.mode in ("1", "L"): if image and image.mode in ("1", "L"):
break break
else: else:
raise IOError("cannot find glyph data file") raise OSError("cannot find glyph data file")
self.file = fullname self.file = fullname
@ -145,7 +145,7 @@ class ImageFont(object):
# <b>truetype</b> factory function to create font objects. # <b>truetype</b> factory function to create font objects.
class FreeTypeFont(object): class FreeTypeFont:
"FreeType font wrapper (requires _imagingft service)" "FreeType font wrapper (requires _imagingft service)"
def __init__(self, font=None, size=10, index=0, encoding="", layout_engine=None): def __init__(self, font=None, size=10, index=0, encoding="", layout_engine=None):
@ -542,7 +542,7 @@ class FreeTypeFont(object):
raise NotImplementedError("FreeType 2.9.1 or greater is required") raise NotImplementedError("FreeType 2.9.1 or greater is required")
class TransposedFont(object): class TransposedFont:
"Wrapper for writing rotated or mirrored text" "Wrapper for writing rotated or mirrored text"
def __init__(self, font, orientation=None): def __init__(self, font, orientation=None):
@ -638,7 +638,7 @@ def truetype(font=None, size=10, index=0, encoding="", layout_engine=None):
try: try:
return freetype(font) return freetype(font)
except IOError: except OSError:
if not isPath(font): if not isPath(font):
raise raise
ttf_filename = os.path.basename(font) ttf_filename = os.path.basename(font)
@ -698,9 +698,9 @@ def load_path(filename):
filename = filename.decode("utf-8") filename = filename.decode("utf-8")
try: try:
return load(os.path.join(directory, filename)) return load(os.path.join(directory, filename))
except IOError: except OSError:
pass pass
raise IOError("cannot find font file") raise OSError("cannot find font file")
def load_default(): def load_default():

View File

@ -26,7 +26,7 @@ def _isconstant(v):
return isinstance(v, (int, float)) return isinstance(v, (int, float))
class _Operand(object): class _Operand:
"""Wraps an image operand, providing standard operators""" """Wraps an image operand, providing standard operators"""
def __init__(self, im): def __init__(self, im):

View File

@ -17,7 +17,7 @@
_modes = None _modes = None
class ModeDescriptor(object): class ModeDescriptor:
"""Wrapper for mode strings.""" """Wrapper for mode strings."""
def __init__(self, mode, bands, basemode, basetype): def __init__(self, mode, bands, basemode, basetype):

View File

@ -5,8 +5,6 @@
# #
# Copyright (c) 2014 Dov Grobgeld <dov.grobgeld@gmail.com> # Copyright (c) 2014 Dov Grobgeld <dov.grobgeld@gmail.com>
from __future__ import print_function
import re import re
from . import Image, _imagingmorph from . import Image, _imagingmorph
@ -27,7 +25,7 @@ MIRROR_MATRIX = [
# fmt: on # fmt: on
class LutBuilder(object): class LutBuilder:
"""A class for building a MorphLut from a descriptive language """A class for building a MorphLut from a descriptive language
The input patterns is a list of a strings sequences like these:: The input patterns is a list of a strings sequences like these::
@ -178,7 +176,7 @@ class LutBuilder(object):
return self.lut return self.lut
class MorphOp(object): class MorphOp:
"""A class for binary morphological operators""" """A class for binary morphological operators"""
def __init__(self, lut=None, op_name=None, patterns=None): def __init__(self, lut=None, op_name=None, patterns=None):

View File

@ -55,7 +55,7 @@ def _lut(image, lut):
lut = lut + lut + lut lut = lut + lut + lut
return image.point(lut) return image.point(lut)
else: else:
raise IOError("not supported for this image mode") raise OSError("not supported for this image mode")
# #

View File

@ -21,7 +21,7 @@ import array
from . import GimpGradientFile, GimpPaletteFile, ImageColor, PaletteFile from . import GimpGradientFile, GimpPaletteFile, ImageColor, PaletteFile
class ImagePalette(object): class ImagePalette:
""" """
Color palette for palette mapped images Color palette for palette mapped images
@ -216,6 +216,6 @@ def load(filename):
# traceback.print_exc() # traceback.print_exc()
pass pass
else: else:
raise IOError("cannot load palette") raise OSError("cannot load palette")
return lut # data, rawmode return lut # data, rawmode

View File

@ -16,7 +16,7 @@
## ##
class Iterator(object): class Iterator:
""" """
This class implements an iterator object that can be used to loop This class implements an iterator object that can be used to loop
over an image sequence. over an image sequence.

View File

@ -11,9 +11,6 @@
# #
# See the README file for information on usage and redistribution. # See the README file for information on usage and redistribution.
# #
from __future__ import print_function
import os import os
import subprocess import subprocess
import sys import sys
@ -52,7 +49,7 @@ def show(image, title=None, **options):
return 0 return 0
class Viewer(object): class Viewer:
"""Base class for viewers.""" """Base class for viewers."""
# main api # main api
@ -123,10 +120,8 @@ elif sys.platform == "darwin":
# on darwin open returns immediately resulting in the temp # on darwin open returns immediately resulting in the temp
# file removal while app is opening # file removal while app is opening
command = "open -a Preview.app" command = "open -a Preview.app"
command = "(%s %s; sleep 20; rm -f %s)&" % ( command = "({} {}; sleep 20; rm -f {})&".format(
command, command, quote(file), quote(file)
quote(file),
quote(file),
) )
return command return command
@ -166,7 +161,7 @@ else:
def get_command(self, file, **options): def get_command(self, file, **options):
command = self.get_command_ex(file, **options)[0] command = self.get_command_ex(file, **options)[0]
return "(%s %s; rm -f %s)&" % (command, quote(file), quote(file)) return "({} {}; rm -f {})&".format(command, quote(file), quote(file))
def show_file(self, file, **options): def show_file(self, file, **options):
"""Display given file""" """Display given file"""

View File

@ -26,7 +26,7 @@ import math
import operator import operator
class Stat(object): class Stat:
def __init__(self, image_or_list, mask=None): def __init__(self, image_or_list, mask=None):
try: try:
if mask: if mask:

View File

@ -62,7 +62,7 @@ def _get_image_from_kw(kw):
# PhotoImage # PhotoImage
class PhotoImage(object): class PhotoImage:
""" """
A Tkinter-compatible photo image. This can be used A Tkinter-compatible photo image. This can be used
everywhere Tkinter expects an image object. If the image is an RGBA everywhere Tkinter expects an image object. If the image is an RGBA
@ -203,7 +203,7 @@ class PhotoImage(object):
# BitmapImage # BitmapImage
class BitmapImage(object): class BitmapImage:
""" """
A Tkinter-compatible bitmap image. This can be used everywhere Tkinter A Tkinter-compatible bitmap image. This can be used everywhere Tkinter
expects an image object. expects an image object.
@ -293,7 +293,7 @@ def _show(image, title):
tkinter.Label.__init__(self, master, image=self.image, bg="black", bd=0) tkinter.Label.__init__(self, master, image=self.image, bg="black", bd=0)
if not tkinter._default_root: if not tkinter._default_root:
raise IOError("tkinter not initialized") raise OSError("tkinter not initialized")
top = tkinter.Toplevel() top = tkinter.Toplevel()
if title: if title:
top.title(title) top.title(title)

View File

@ -20,7 +20,7 @@
from . import Image from . import Image
class HDC(object): class HDC:
""" """
Wraps an HDC integer. The resulting object can be passed to the Wraps an HDC integer. The resulting object can be passed to the
:py:meth:`~PIL.ImageWin.Dib.draw` and :py:meth:`~PIL.ImageWin.Dib.expose` :py:meth:`~PIL.ImageWin.Dib.draw` and :py:meth:`~PIL.ImageWin.Dib.expose`
@ -34,7 +34,7 @@ class HDC(object):
return self.dc return self.dc
class HWND(object): class HWND:
""" """
Wraps an HWND integer. The resulting object can be passed to the Wraps an HWND integer. The resulting object can be passed to the
:py:meth:`~PIL.ImageWin.Dib.draw` and :py:meth:`~PIL.ImageWin.Dib.expose` :py:meth:`~PIL.ImageWin.Dib.draw` and :py:meth:`~PIL.ImageWin.Dib.expose`
@ -48,7 +48,7 @@ class HWND(object):
return self.wnd return self.wnd
class Dib(object): class Dib:
""" """
A Windows bitmap with the given mode and size. The mode can be one of "1", A Windows bitmap with the given mode and size. The mode can be one of "1",
"L", "P", or "RGB". "L", "P", or "RGB".
@ -186,7 +186,7 @@ class Dib(object):
return self.image.tobytes() return self.image.tobytes()
class Window(object): class Window:
"""Create a Window with the given title size.""" """Create a Window with the given title size."""
def __init__(self, title="PIL", width=None, height=None): def __init__(self, title="PIL", width=None, height=None):

View File

@ -14,9 +14,6 @@
# #
# See the README file for information on usage and redistribution. # See the README file for information on usage and redistribution.
# #
from __future__ import print_function
import os import os
import tempfile import tempfile
@ -75,7 +72,7 @@ class IptcImageFile(ImageFile.ImageFile):
# field size # field size
size = i8(s[3]) size = i8(s[3])
if size > 132: if size > 132:
raise IOError("illegal field length in IPTC/NAA file") raise OSError("illegal field length in IPTC/NAA file")
elif size == 128: elif size == 128:
size = 0 size = 0
elif size > 128: elif size > 128:
@ -126,7 +123,7 @@ class IptcImageFile(ImageFile.ImageFile):
try: try:
compression = COMPRESSION[self.getint((3, 120))] compression = COMPRESSION[self.getint((3, 120))]
except KeyError: except KeyError:
raise IOError("Unknown IPTC image compression") raise OSError("Unknown IPTC image compression")
# tile # tile
if tag == (8, 10): if tag == (8, 10):
@ -215,7 +212,7 @@ def getiptcinfo(im):
return None # no properties return None # no properties
# create an IptcImagePlugin object without initializing it # create an IptcImagePlugin object without initializing it
class FakeImage(object): class FakeImage:
pass pass
im = FakeImage() im = FakeImage()

View File

@ -31,9 +31,6 @@
# #
# See the README file for information on usage and redistribution. # See the README file for information on usage and redistribution.
# #
from __future__ import print_function
import array import array
import io import io
import struct import struct
@ -618,7 +615,7 @@ def _save(im, fp, filename):
try: try:
rawmode = RAWMODE[im.mode] rawmode = RAWMODE[im.mode]
except KeyError: except KeyError:
raise IOError("cannot write mode %s as JPEG" % im.mode) raise OSError("cannot write mode %s as JPEG" % im.mode)
info = im.encoderinfo info = im.encoderinfo

View File

@ -51,7 +51,7 @@ class MicImageFile(TiffImagePlugin.TiffImageFile):
try: try:
self.ole = olefile.OleFileIO(self.fp) self.ole = olefile.OleFileIO(self.fp)
except IOError: except OSError:
raise SyntaxError("not an MIC file; invalid OLE file") raise SyntaxError("not an MIC file; invalid OLE file")
# find ACI subfiles with Image members (maybe not the # find ACI subfiles with Image members (maybe not the

View File

@ -26,7 +26,7 @@ __version__ = "0.1"
# Bitstream parser # Bitstream parser
class BitStream(object): class BitStream:
def __init__(self, fp): def __init__(self, fp):
self.fp = fp self.fp = fp
self.bits = 0 self.bits = 0

View File

@ -122,7 +122,7 @@ class MspDecoder(ImageFile.PyDecoder):
"<%dH" % (self.state.ysize), self.fd.read(self.state.ysize * 2) "<%dH" % (self.state.ysize), self.fd.read(self.state.ysize * 2)
) )
except struct.error: except struct.error:
raise IOError("Truncated MSP file in row map") raise OSError("Truncated MSP file in row map")
for x, rowlen in enumerate(rowmap): for x, rowlen in enumerate(rowmap):
try: try:
@ -131,7 +131,7 @@ class MspDecoder(ImageFile.PyDecoder):
continue continue
row = self.fd.read(rowlen) row = self.fd.read(rowlen)
if len(row) != rowlen: if len(row) != rowlen:
raise IOError( raise OSError(
"Truncated MSP file, expected %d bytes on row %s", (rowlen, x) "Truncated MSP file, expected %d bytes on row %s", (rowlen, x)
) )
idx = 0 idx = 0
@ -148,7 +148,7 @@ class MspDecoder(ImageFile.PyDecoder):
idx += runcount idx += runcount
except struct.error: except struct.error:
raise IOError("Corrupted MSP file in row %d" % x) raise OSError("Corrupted MSP file in row %d" % x)
self.set_as_raw(img.getvalue(), ("1", 0, 1)) self.set_as_raw(img.getvalue(), ("1", 0, 1))
@ -165,7 +165,7 @@ Image.register_decoder("MSP", MspDecoder)
def _save(im, fp, filename): def _save(im, fp, filename):
if im.mode != "1": if im.mode != "1":
raise IOError("cannot write mode %s as MSP" % im.mode) raise OSError("cannot write mode %s as MSP" % im.mode)
# create MSP header # create MSP header
header = [0] * 16 header = [0] * 16

View File

@ -23,7 +23,7 @@ from . import EpsImagePlugin
# Simple Postscript graphics interface. # Simple Postscript graphics interface.
class PSDraw(object): class PSDraw:
""" """
Sets up printing to the given file. If **fp** is omitted, Sets up printing to the given file. If **fp** is omitted,
:py:attr:`sys.stdout` is assumed. :py:attr:`sys.stdout` is assumed.
@ -71,7 +71,7 @@ class PSDraw(object):
""" """
if font not in self.isofont: if font not in self.isofont:
# reencode font # reencode font
self._fp_write("/PSDraw-%s ISOLatin1Encoding /%s E\n" % (font, font)) self._fp_write("/PSDraw-{} ISOLatin1Encoding /{} E\n".format(font, font))
self.isofont[font] = 1 self.isofont[font] = 1
# rough # rough
self._fp_write("/F0 %d /PSDraw-%s F\n" % (size, font)) self._fp_write("/F0 %d /PSDraw-%s F\n" % (size, font))
@ -132,12 +132,12 @@ class PSDraw(object):
y = ymax y = ymax
dx = (xmax - x) / 2 + box[0] dx = (xmax - x) / 2 + box[0]
dy = (ymax - y) / 2 + box[1] dy = (ymax - y) / 2 + box[1]
self._fp_write("gsave\n%f %f translate\n" % (dx, dy)) self._fp_write("gsave\n{:f} {:f} translate\n".format(dx, dy))
if (x, y) != im.size: if (x, y) != im.size:
# EpsImagePlugin._save prints the image at (0,0,xsize,ysize) # EpsImagePlugin._save prints the image at (0,0,xsize,ysize)
sx = x / im.size[0] sx = x / im.size[0]
sy = y / im.size[1] sy = y / im.size[1]
self._fp_write("%f %f scale\n" % (sx, sy)) self._fp_write("{:f} {:f} scale\n".format(sx, sy))
EpsImagePlugin._save(im, self.fp, None, 0) EpsImagePlugin._save(im, self.fp, None, 0)
self._fp_write("\ngrestore\n") self._fp_write("\ngrestore\n")

View File

@ -19,7 +19,7 @@ from ._binary import o8
# File handler for Teragon-style palette files. # File handler for Teragon-style palette files.
class PaletteFile(object): class PaletteFile:
rawmode = "RGB" rawmode = "RGB"

View File

@ -141,7 +141,7 @@ def _save(im, fp, filename):
bpp = im.info["bpp"] bpp = im.info["bpp"]
im = im.point(lambda x, maxval=(1 << bpp) - 1: maxval - (x & maxval)) im = im.point(lambda x, maxval=(1 << bpp) - 1: maxval - (x & maxval))
else: else:
raise IOError("cannot write mode %s as Palm" % im.mode) raise OSError("cannot write mode %s as Palm" % im.mode)
# we ignore the palette here # we ignore the palette here
im.mode = "P" im.mode = "P"
@ -157,7 +157,7 @@ def _save(im, fp, filename):
else: else:
raise IOError("cannot write mode %s as Palm" % im.mode) raise OSError("cannot write mode %s as Palm" % im.mode)
# #
# make sure image data is available # make sure image data is available

View File

@ -184,7 +184,7 @@ class PcfFontFile(FontFile.FontFile):
nbitmaps = i32(fp.read(4)) nbitmaps = i32(fp.read(4))
if nbitmaps != len(metrics): if nbitmaps != len(metrics):
raise IOError("Wrong number of bitmaps") raise OSError("Wrong number of bitmaps")
offsets = [] offsets = []
for i in range(nbitmaps): for i in range(nbitmaps):

View File

@ -107,7 +107,7 @@ class PcxImageFile(ImageFile.ImageFile):
rawmode = "RGB;L" rawmode = "RGB;L"
else: else:
raise IOError("unknown PCX mode") raise OSError("unknown PCX mode")
self.mode = mode self.mode = mode
self._size = bbox[2] - bbox[0], bbox[3] - bbox[1] self._size = bbox[2] - bbox[0], bbox[3] - bbox[1]

View File

@ -24,47 +24,47 @@ def encode_text(s):
PDFDocEncoding = { PDFDocEncoding = {
0x16: u"\u0017", 0x16: "\u0017",
0x18: u"\u02D8", 0x18: "\u02D8",
0x19: u"\u02C7", 0x19: "\u02C7",
0x1A: u"\u02C6", 0x1A: "\u02C6",
0x1B: u"\u02D9", 0x1B: "\u02D9",
0x1C: u"\u02DD", 0x1C: "\u02DD",
0x1D: u"\u02DB", 0x1D: "\u02DB",
0x1E: u"\u02DA", 0x1E: "\u02DA",
0x1F: u"\u02DC", 0x1F: "\u02DC",
0x80: u"\u2022", 0x80: "\u2022",
0x81: u"\u2020", 0x81: "\u2020",
0x82: u"\u2021", 0x82: "\u2021",
0x83: u"\u2026", 0x83: "\u2026",
0x84: u"\u2014", 0x84: "\u2014",
0x85: u"\u2013", 0x85: "\u2013",
0x86: u"\u0192", 0x86: "\u0192",
0x87: u"\u2044", 0x87: "\u2044",
0x88: u"\u2039", 0x88: "\u2039",
0x89: u"\u203A", 0x89: "\u203A",
0x8A: u"\u2212", 0x8A: "\u2212",
0x8B: u"\u2030", 0x8B: "\u2030",
0x8C: u"\u201E", 0x8C: "\u201E",
0x8D: u"\u201C", 0x8D: "\u201C",
0x8E: u"\u201D", 0x8E: "\u201D",
0x8F: u"\u2018", 0x8F: "\u2018",
0x90: u"\u2019", 0x90: "\u2019",
0x91: u"\u201A", 0x91: "\u201A",
0x92: u"\u2122", 0x92: "\u2122",
0x93: u"\uFB01", 0x93: "\uFB01",
0x94: u"\uFB02", 0x94: "\uFB02",
0x95: u"\u0141", 0x95: "\u0141",
0x96: u"\u0152", 0x96: "\u0152",
0x97: u"\u0160", 0x97: "\u0160",
0x98: u"\u0178", 0x98: "\u0178",
0x99: u"\u017D", 0x99: "\u017D",
0x9A: u"\u0131", 0x9A: "\u0131",
0x9B: u"\u0142", 0x9B: "\u0142",
0x9C: u"\u0153", 0x9C: "\u0153",
0x9D: u"\u0161", 0x9D: "\u0161",
0x9E: u"\u017E", 0x9E: "\u017E",
0xA0: u"\u20AC", 0xA0: "\u20AC",
} }
@ -235,7 +235,7 @@ class PdfName:
def from_pdf_stream(cls, data): def from_pdf_stream(cls, data):
return cls(PdfParser.interpret_name(data)) return cls(PdfParser.interpret_name(data))
allowed_chars = set(range(33, 127)) - set(ord(c) for c in "#%/()<>[]{}") allowed_chars = set(range(33, 127)) - {ord(c) for c in "#%/()<>[]{}"}
def __bytes__(self): def __bytes__(self):
result = bytearray(b"/") result = bytearray(b"/")
@ -441,7 +441,7 @@ class PdfParser:
self.f.write(b"%PDF-1.4\n") self.f.write(b"%PDF-1.4\n")
def write_comment(self, s): def write_comment(self, s):
self.f.write(("%% %s\n" % (s,)).encode("utf-8")) self.f.write(("% {}\n".format(s)).encode("utf-8"))
def write_catalog(self): def write_catalog(self):
self.del_root() self.del_root()

View File

@ -101,7 +101,7 @@ def _crc32(data, seed=0):
# Support classes. Suitable for PNG and related formats like MNG etc. # Support classes. Suitable for PNG and related formats like MNG etc.
class ChunkStream(object): class ChunkStream:
def __init__(self, fp): def __init__(self, fp):
self.fp = fp self.fp = fp
@ -179,7 +179,7 @@ class ChunkStream(object):
try: try:
cid, pos, length = self.read() cid, pos, length = self.read()
except struct.error: except struct.error:
raise IOError("truncated PNG file") raise OSError("truncated PNG file")
if cid == endchunk: if cid == endchunk:
break break
@ -211,7 +211,7 @@ class iTXt(str):
return self return self
class PngInfo(object): class PngInfo:
""" """
PNG chunk container (for use with save(pnginfo=)) PNG chunk container (for use with save(pnginfo=))
@ -742,7 +742,7 @@ def putchunk(fp, cid, *data):
fp.write(o32(crc)) fp.write(o32(crc))
class _idat(object): class _idat:
# wrap output from the encoder in IDAT chunks # wrap output from the encoder in IDAT chunks
def __init__(self, fp, chunk): def __init__(self, fp, chunk):
@ -795,7 +795,7 @@ def _save(im, fp, filename, chunk=putchunk):
try: try:
rawmode, mode = _OUTMODES[mode] rawmode, mode = _OUTMODES[mode]
except KeyError: except KeyError:
raise IOError("cannot write mode %s as PNG" % mode) raise OSError("cannot write mode %s as PNG" % mode)
# #
# write minimal PNG file # write minimal PNG file
@ -870,7 +870,7 @@ def _save(im, fp, filename, chunk=putchunk):
if "transparency" in im.encoderinfo: if "transparency" in im.encoderinfo:
# don't bother with transparency if it's an RGBA # don't bother with transparency if it's an RGBA
# and it's in the info dict. It's probably just stale. # and it's in the info dict. It's probably just stale.
raise IOError("cannot use transparency for this mode") raise OSError("cannot use transparency for this mode")
else: else:
if im.mode == "P" and im.im.getpalettemode() == "RGBA": if im.mode == "P" and im.im.getpalettemode() == "RGBA":
alpha = im.im.getpalette("RGBA", "A") alpha = im.im.getpalette("RGBA", "A")
@ -918,7 +918,7 @@ def _save(im, fp, filename, chunk=putchunk):
def getchunks(im, **params): def getchunks(im, **params):
"""Return a list of PNG chunks representing this image.""" """Return a list of PNG chunks representing this image."""
class collector(object): class collector:
data = [] data = []
def write(self, data): def write(self, data):

View File

@ -139,7 +139,7 @@ def _save(im, fp, filename):
elif im.mode == "RGBA": elif im.mode == "RGBA":
rawmode, head = "RGB", b"P6" rawmode, head = "RGB", b"P6"
else: else:
raise IOError("cannot write mode %s as PPM" % im.mode) raise OSError("cannot write mode %s as PPM" % im.mode)
fp.write(head + ("\n%d %d\n" % im.size).encode("ascii")) fp.write(head + ("\n%d %d\n" % im.size).encode("ascii"))
if head == b"P6": if head == b"P6":
fp.write(b"255\n") fp.write(b"255\n")

View File

@ -75,7 +75,7 @@ class PsdImageFile(ImageFile.ImageFile):
mode, channels = MODES[(psd_mode, psd_bits)] mode, channels = MODES[(psd_mode, psd_bits)]
if channels > psd_channels: if channels > psd_channels:
raise IOError("not enough channels") raise OSError("not enough channels")
self.mode = mode self.mode = mode
self._size = i32(s[18:]), i32(s[14:]) self._size = i32(s[18:]), i32(s[14:])

View File

@ -40,7 +40,7 @@ ffi = FFI()
ffi.cdef(defs) ffi.cdef(defs)
class PyAccess(object): class PyAccess:
def __init__(self, img, readonly=False): def __init__(self, img, readonly=False):
vals = dict(img.im.unsafe_ptrs) vals = dict(img.im.unsafe_ptrs)
self.readonly = readonly self.readonly = readonly

View File

@ -163,7 +163,9 @@ def _save(im, fp, filename):
# assert we've got the right number of bands. # assert we've got the right number of bands.
if len(im.getbands()) != z: if len(im.getbands()) != z:
raise ValueError( raise ValueError(
"incorrect number of bands in SGI write: %s vs %s" % (z, len(im.getbands())) "incorrect number of bands in SGI write: {} vs {}".format(
z, len(im.getbands())
)
) )
# Minimum Byte value # Minimum Byte value

View File

@ -32,9 +32,6 @@
# Details about the Spider image format: # Details about the Spider image format:
# https://spider.wadsworth.org/spider_doc/spider/docs/image_doc.html # https://spider.wadsworth.org/spider_doc/spider/docs/image_doc.html
# #
from __future__ import print_function
import os import os
import struct import struct
import sys import sys
@ -273,7 +270,7 @@ def _save(im, fp, filename):
hdr = makeSpiderHeader(im) hdr = makeSpiderHeader(im)
if len(hdr) < 256: if len(hdr) < 256:
raise IOError("Error creating Spider header") raise OSError("Error creating Spider header")
# write the SPIDER header # write the SPIDER header
fp.writelines(hdr) fp.writelines(hdr)

View File

@ -37,12 +37,12 @@ class TarIO(ContainerIO.ContainerIO):
s = self.fh.read(512) s = self.fh.read(512)
if len(s) != 512: if len(s) != 512:
raise IOError("unexpected end of tar file") raise OSError("unexpected end of tar file")
name = s[:100].decode("utf-8") name = s[:100].decode("utf-8")
i = name.find("\0") i = name.find("\0")
if i == 0: if i == 0:
raise IOError("cannot find subfile") raise OSError("cannot find subfile")
if i > 0: if i > 0:
name = name[:i] name = name[:i]

View File

@ -173,7 +173,7 @@ def _save(im, fp, filename):
try: try:
rawmode, bits, colormaptype, imagetype = SAVE[im.mode] rawmode, bits, colormaptype, imagetype = SAVE[im.mode]
except KeyError: except KeyError:
raise IOError("cannot write mode %s as TGA" % im.mode) raise OSError("cannot write mode %s as TGA" % im.mode)
if "rle" in im.encoderinfo: if "rle" in im.encoderinfo:
rle = im.encoderinfo["rle"] rle = im.encoderinfo["rle"]

View File

@ -38,9 +38,6 @@
# #
# See the README file for information on usage and redistribution. # See the README file for information on usage and redistribution.
# #
from __future__ import division, print_function
import distutils.version import distutils.version
import io import io
import itertools import itertools
@ -712,7 +709,7 @@ class ImageFileDirectory_v2(MutableMapping):
def _ensure_read(self, fp, size): def _ensure_read(self, fp, size):
ret = fp.read(size) ret = fp.read(size)
if len(ret) != size: if len(ret) != size:
raise IOError( raise OSError(
"Corrupt EXIF data. " "Corrupt EXIF data. "
+ "Expecting to read %d bytes but only got %d. " % (size, len(ret)) + "Expecting to read %d bytes but only got %d. " % (size, len(ret))
) )
@ -746,7 +743,7 @@ class ImageFileDirectory_v2(MutableMapping):
offset, = self._unpack("L", data) offset, = self._unpack("L", data)
if DEBUG: if DEBUG:
print( print(
"Tag Location: %s - Data Location: %s" % (here, offset), "Tag Location: {} - Data Location: {}".format(here, offset),
end=" ", end=" ",
) )
fp.seek(offset) fp.seek(offset)
@ -776,7 +773,7 @@ class ImageFileDirectory_v2(MutableMapping):
print("- value:", self[tag]) print("- value:", self[tag])
self.next, = self._unpack("L", self._ensure_read(fp, 4)) self.next, = self._unpack("L", self._ensure_read(fp, 4))
except IOError as msg: except OSError as msg:
warnings.warn(str(msg)) warnings.warn(str(msg))
return return
@ -795,7 +792,7 @@ class ImageFileDirectory_v2(MutableMapping):
stripoffsets = len(entries) stripoffsets = len(entries)
typ = self.tagtype.get(tag) typ = self.tagtype.get(tag)
if DEBUG: if DEBUG:
print("Tag %s, Type: %s, Value: %s" % (tag, typ, value)) print("Tag {}, Type: {}, Value: {}".format(tag, typ, value))
values = value if isinstance(value, tuple) else (value,) values = value if isinstance(value, tuple) else (value,)
data = self._write_dispatch[typ](self, *values) data = self._write_dispatch[typ](self, *values)
if DEBUG: if DEBUG:
@ -1060,7 +1057,7 @@ class TiffImageFile(ImageFile.ImageFile):
def load(self): def load(self):
if self.use_load_libtiff: if self.use_load_libtiff:
return self._load_libtiff() return self._load_libtiff()
return super(TiffImageFile, self).load() return super().load()
def load_end(self): def load_end(self):
if self._tile_orientation: if self._tile_orientation:
@ -1089,14 +1086,14 @@ class TiffImageFile(ImageFile.ImageFile):
pixel = Image.Image.load(self) pixel = Image.Image.load(self)
if self.tile is None: if self.tile is None:
raise IOError("cannot load this image") raise OSError("cannot load this image")
if not self.tile: if not self.tile:
return pixel return pixel
self.load_prepare() self.load_prepare()
if not len(self.tile) == 1: if not len(self.tile) == 1:
raise IOError("Not exactly one tile") raise OSError("Not exactly one tile")
# (self._compression, (extents tuple), # (self._compression, (extents tuple),
# 0, (rawmode, self._compression, fp)) # 0, (rawmode, self._compression, fp))
@ -1114,7 +1111,7 @@ class TiffImageFile(ImageFile.ImageFile):
# in _seek # in _seek
if hasattr(self.fp, "flush"): if hasattr(self.fp, "flush"):
self.fp.flush() self.fp.flush()
except IOError: except OSError:
# io.BytesIO have a fileno, but returns an IOError if # io.BytesIO have a fileno, but returns an IOError if
# it doesn't use a file descriptor. # it doesn't use a file descriptor.
fp = False fp = False
@ -1128,7 +1125,7 @@ class TiffImageFile(ImageFile.ImageFile):
try: try:
decoder.setimage(self.im, extents) decoder.setimage(self.im, extents)
except ValueError: except ValueError:
raise IOError("Couldn't set the image") raise OSError("Couldn't set the image")
close_self_fp = self._exclusive_fp and not self._is_animated close_self_fp = self._exclusive_fp and not self._is_animated
if hasattr(self.fp, "getvalue"): if hasattr(self.fp, "getvalue"):
@ -1171,7 +1168,7 @@ class TiffImageFile(ImageFile.ImageFile):
self.fp = None # might be shared self.fp = None # might be shared
if err < 0: if err < 0:
raise IOError(err) raise OSError(err)
return Image.Image.load(self) return Image.Image.load(self)
@ -1179,7 +1176,7 @@ class TiffImageFile(ImageFile.ImageFile):
"""Setup this image object based on current tags""" """Setup this image object based on current tags"""
if 0xBC01 in self.tag_v2: if 0xBC01 in self.tag_v2:
raise IOError("Windows Media Photo files not yet supported") raise OSError("Windows Media Photo files not yet supported")
# extract relevant tags # extract relevant tags
self._compression = COMPRESSION_INFO[self.tag_v2.get(COMPRESSION, 1)] self._compression = COMPRESSION_INFO[self.tag_v2.get(COMPRESSION, 1)]
@ -1421,7 +1418,7 @@ def _save(im, fp, filename):
try: try:
rawmode, prefix, photo, format, bits, extra = SAVE_INFO[im.mode] rawmode, prefix, photo, format, bits, extra = SAVE_INFO[im.mode]
except KeyError: except KeyError:
raise IOError("cannot write mode %s as TIFF" % im.mode) raise OSError("cannot write mode %s as TIFF" % im.mode)
ifd = ImageFileDirectory_v2(prefix=prefix) ifd = ImageFileDirectory_v2(prefix=prefix)
@ -1616,7 +1613,7 @@ def _save(im, fp, filename):
if s: if s:
break break
if s < 0: if s < 0:
raise IOError("encoder error %d when writing image file" % s) raise OSError("encoder error %d when writing image file" % s)
else: else:
offset = ifd.save(fp) offset = ifd.save(fp)
@ -1664,9 +1661,9 @@ class AppendingTiffWriter:
self.name = fn self.name = fn
self.close_fp = True self.close_fp = True
try: try:
self.f = io.open(fn, "w+b" if new else "r+b") self.f = open(fn, "w+b" if new else "r+b")
except IOError: except OSError:
self.f = io.open(fn, "w+b") self.f = open(fn, "w+b")
self.beginning = self.f.tell() self.beginning = self.f.tell()
self.setup() self.setup()

View File

@ -24,7 +24,7 @@ class TagInfo(namedtuple("_TagInfo", "value name type length enum")):
__slots__ = [] __slots__ = []
def __new__(cls, value=None, name="unknown", type=None, length=None, enum=None): def __new__(cls, value=None, name="unknown", type=None, length=None, enum=None):
return super(TagInfo, cls).__new__(cls, value, name, type, length, enum or {}) return super().__new__(cls, value, name, type, length, enum or {})
def cvt_enum(self, value): def cvt_enum(self, value):
# Using get will call hash(value), which can be expensive # Using get will call hash(value), which can be expensive

View File

@ -1,4 +1,3 @@
# encoding: utf-8
# #
# The Python Imaging Library. # The Python Imaging Library.
# $Id$ # $Id$

View File

@ -105,7 +105,7 @@ class WebPImageFile(ImageFile.ImageFile):
def seek(self, frame): def seek(self, frame):
if not _webp.HAVE_WEBPANIM: if not _webp.HAVE_WEBPANIM:
return super(WebPImageFile, self).seek(frame) return super().seek(frame)
# Perform some simple checks first # Perform some simple checks first
if frame >= self._n_frames: if frame >= self._n_frames:
@ -168,11 +168,11 @@ class WebPImageFile(ImageFile.ImageFile):
self.fp = BytesIO(data) self.fp = BytesIO(data)
self.tile = [("raw", (0, 0) + self.size, 0, self.rawmode)] self.tile = [("raw", (0, 0) + self.size, 0, self.rawmode)]
return super(WebPImageFile, self).load() return super().load()
def tell(self): def tell(self):
if not _webp.HAVE_WEBPANIM: if not _webp.HAVE_WEBPANIM:
return super(WebPImageFile, self).tell() return super().tell()
return self.__logical_frame return self.__logical_frame
@ -233,7 +233,7 @@ def _save_all(im, fp, filename):
or len(background) != 4 or len(background) != 4
or not all(v >= 0 and v < 256 for v in background) or not all(v >= 0 and v < 256 for v in background)
): ):
raise IOError( raise OSError(
"Background color is not an RGBA tuple clamped to (0-255): %s" "Background color is not an RGBA tuple clamped to (0-255): %s"
% str(background) % str(background)
) )
@ -312,7 +312,7 @@ def _save_all(im, fp, filename):
# Get the final output from the encoder # Get the final output from the encoder
data = enc.assemble(icc_profile, exif, xmp) data = enc.assemble(icc_profile, exif, xmp)
if data is None: if data is None:
raise IOError("cannot write file as WebP (encoder returned None)") raise OSError("cannot write file as WebP (encoder returned None)")
fp.write(data) fp.write(data)
@ -346,7 +346,7 @@ def _save(im, fp, filename):
xmp, xmp,
) )
if data is None: if data is None:
raise IOError("cannot write file as WebP (encoder returned None)") raise OSError("cannot write file as WebP (encoder returned None)")
fp.write(data) fp.write(data)

Some files were not shown because too many files have changed in this diff Show More