diff --git a/Tests/check_icns_dos.py b/Tests/check_icns_dos.py index e56709bbb..d4c3cf7cb 100644 --- a/Tests/check_icns_dos.py +++ b/Tests/check_icns_dos.py @@ -2,10 +2,11 @@ # Run from anywhere that PIL is importable. from PIL import Image +from PIL._util import py3 from io import BytesIO -if bytes is str: - Image.open(BytesIO(bytes('icns\x00\x00\x00\x10hang\x00\x00\x00\x00'))) -else: +if py3: Image.open(BytesIO(bytes('icns\x00\x00\x00\x10hang\x00\x00\x00\x00', 'latin-1'))) +else: + Image.open(BytesIO(bytes('icns\x00\x00\x00\x10hang\x00\x00\x00\x00'))) diff --git a/Tests/check_j2k_dos.py b/Tests/check_j2k_dos.py index 9f06888a3..4ea31cec2 100644 --- a/Tests/check_j2k_dos.py +++ b/Tests/check_j2k_dos.py @@ -2,12 +2,14 @@ # Run from anywhere that PIL is importable. from PIL import Image +from PIL._util import py3 from io import BytesIO -if bytes is str: - Image.open(BytesIO(bytes( - '\x00\x00\x00\x0cjP\x20\x20\x0d\x0a\x87\x0a\x00\x00\x00\x00hang'))) -else: +if py3: Image.open(BytesIO(bytes( '\x00\x00\x00\x0cjP\x20\x20\x0d\x0a\x87\x0a\x00\x00\x00\x00hang', 'latin-1'))) + +else: + Image.open(BytesIO(bytes( + '\x00\x00\x00\x0cjP\x20\x20\x0d\x0a\x87\x0a\x00\x00\x00\x00hang'))) diff --git a/Tests/helper.py b/Tests/helper.py index 606dca006..d70b6f51d 100644 --- a/Tests/helper.py +++ b/Tests/helper.py @@ -8,6 +8,7 @@ import os import unittest from PIL import Image, ImageMath +from PIL._util import py3 import logging logger = logging.getLogger(__name__) @@ -265,8 +266,6 @@ class PillowLeakTestCase(PillowTestCase): # helpers -py3 = sys.version_info.major >= 3 - if not py3: # Remove DeprecationWarning in Python 3 PillowTestCase.assertRaisesRegex = PillowTestCase.assertRaisesRegexp diff --git a/Tests/test_file_eps.py b/Tests/test_file_eps.py index bd7c79f82..9d6bed060 100644 --- a/Tests/test_file_eps.py +++ b/Tests/test_file_eps.py @@ -1,6 +1,7 @@ from helper import unittest, PillowTestCase, hopper from PIL import Image, EpsImagePlugin +from PIL._util import py3 import io # Our two EPS test files (they are identical except for their bounding boxes) @@ -206,19 +207,19 @@ class TestFileEps(PillowTestCase): self._test_readline(t, ending) def _test_readline_io(self, test_string, ending): - if str is bytes: - t = io.StringIO(unicode(test_string)) - else: + if py3: t = io.StringIO(test_string) + else: + t = io.StringIO(unicode(test_string)) self._test_readline(t, ending) def _test_readline_file_universal(self, test_string, ending): f = self.tempfile('temp.txt') with open(f, 'wb') as w: - if str is bytes: - w.write(test_string) - else: + if py3: w.write(test_string.encode('UTF-8')) + else: + w.write(test_string) with open(f, 'rU') as t: self._test_readline(t, ending) @@ -226,10 +227,10 @@ class TestFileEps(PillowTestCase): def _test_readline_file_psfile(self, test_string, ending): f = self.tempfile('temp.txt') with open(f, 'wb') as w: - if str is bytes: - w.write(test_string) - else: + if py3: w.write(test_string.encode('UTF-8')) + else: + w.write(test_string) with open(f, 'rb') as r: t = EpsImagePlugin.PSFile(r) diff --git a/Tests/test_file_libtiff.py b/Tests/test_file_libtiff.py index dc3b10845..05433d9b6 100644 --- a/Tests/test_file_libtiff.py +++ b/Tests/test_file_libtiff.py @@ -1,6 +1,7 @@ from __future__ import print_function -from helper import unittest, PillowTestCase, hopper, py3 +from helper import unittest, PillowTestCase, hopper from PIL import features +from PIL._util import py3 from ctypes import c_float import io diff --git a/Tests/test_file_png.py b/Tests/test_file_png.py index abf3f2953..c78351464 100644 --- a/Tests/test_file_png.py +++ b/Tests/test_file_png.py @@ -1,5 +1,6 @@ from helper import unittest, PillowTestCase, PillowLeakTestCase, hopper from PIL import Image, ImageFile, PngImagePlugin +from PIL._util import py3 from io import BytesIO import zlib @@ -419,7 +420,7 @@ class TestFilePng(PillowTestCase): im = roundtrip(im, pnginfo=info) self.assertEqual(im.info, {"Text": value}) - if str is not bytes: + if py3: rt_text(" Aa" + chr(0xa0) + chr(0xc4) + chr(0xff)) # Latin1 rt_text(chr(0x400) + chr(0x472) + chr(0x4ff)) # Cyrillic rt_text(chr(0x4e00) + chr(0x66f0) + # CJK diff --git a/Tests/test_file_tiff.py b/Tests/test_file_tiff.py index 334f5c96b..282a0c676 100644 --- a/Tests/test_file_tiff.py +++ b/Tests/test_file_tiff.py @@ -3,9 +3,10 @@ from io import BytesIO import struct import sys -from helper import unittest, PillowTestCase, hopper, py3 +from helper import unittest, PillowTestCase, hopper from PIL import Image, TiffImagePlugin +from PIL._util import py3 from PIL.TiffImagePlugin import X_RESOLUTION, Y_RESOLUTION, RESOLUTION_UNIT logger = logging.getLogger(__name__) diff --git a/Tests/test_font_pcf.py b/Tests/test_font_pcf.py index 0b757b963..20869505f 100644 --- a/Tests/test_font_pcf.py +++ b/Tests/test_font_pcf.py @@ -2,6 +2,7 @@ from helper import unittest, PillowTestCase from PIL import Image, FontFile, PcfFontFile from PIL import ImageFont, ImageDraw +from PIL._util import py3 codecs = dir(Image.core) @@ -76,7 +77,7 @@ class TestFontPcf(PillowTestCase): message = "".join(chr(i+1) for i in range(140, 232)) self._test_high_characters(message) # accept bytes instances in Py3. - if bytes is not str: + if py3: self._test_high_characters(message.encode('latin1')) diff --git a/Tests/test_format_hsv.py b/Tests/test_format_hsv.py index 2cc54c910..31309da60 100644 --- a/Tests/test_format_hsv.py +++ b/Tests/test_format_hsv.py @@ -1,6 +1,7 @@ from helper import unittest, PillowTestCase, hopper from PIL import Image +from PIL._util import py3 import colorsys import itertools @@ -57,10 +58,10 @@ class TestFormatHSV(PillowTestCase): (r, g, b) = im.split() - if bytes is str: - conv_func = self.str_to_float - else: + if py3: conv_func = self.int_to_float + else: + conv_func = self.str_to_float if hasattr(itertools, 'izip'): iter_helper = itertools.izip @@ -72,11 +73,11 @@ class TestFormatHSV(PillowTestCase): for (_r, _g, _b) in iter_helper(r.tobytes(), g.tobytes(), b.tobytes())] - if str is bytes: - new_bytes = b''.join(chr(h)+chr(s)+chr(v) for ( + if py3: + new_bytes = b''.join(bytes(chr(h)+chr(s)+chr(v), 'latin-1') for ( h, s, v) in converted) else: - new_bytes = b''.join(bytes(chr(h)+chr(s)+chr(v), 'latin-1') for ( + new_bytes = b''.join(chr(h)+chr(s)+chr(v) for ( h, s, v) in converted) hsv = Image.frombytes(mode, r.size, new_bytes) diff --git a/Tests/test_image.py b/Tests/test_image.py index f64ea241b..7222e389b 100644 --- a/Tests/test_image.py +++ b/Tests/test_image.py @@ -1,6 +1,7 @@ from helper import unittest, PillowTestCase, hopper from PIL import Image +from PIL._util import py3 import os @@ -60,12 +61,12 @@ class TestImage(PillowTestCase): self.assertEqual(im.height, 4) def test_invalid_image(self): - if str is bytes: - import StringIO - im = StringIO.StringIO('') - else: + if py3: import io im = io.BytesIO(b'') + else: + import StringIO + im = StringIO.StringIO('') self.assertRaises(IOError, Image.open, im) def test_bad_mode(self): diff --git a/Tests/test_image_getim.py b/Tests/test_image_getim.py index bc562de5a..1452e584e 100644 --- a/Tests/test_image_getim.py +++ b/Tests/test_image_getim.py @@ -1,4 +1,5 @@ -from helper import unittest, PillowTestCase, hopper, py3 +from helper import unittest, PillowTestCase, hopper +from PIL._util import py3 class TestImageGetIm(PillowTestCase): diff --git a/Tests/test_imagepath.py b/Tests/test_imagepath.py index 98a6d3416..8df71121d 100644 --- a/Tests/test_imagepath.py +++ b/Tests/test_imagepath.py @@ -1,6 +1,7 @@ from helper import unittest, PillowTestCase from PIL import ImagePath, Image +from PIL._util import py3 import array import struct @@ -77,10 +78,10 @@ class TestImagePath(PillowTestCase): # This fails due to the invalid malloc above, # and segfaults for i in range(200000): - if str is bytes: - x[i] = "0"*16 - else: + if py3: x[i] = b'0'*16 + else: + x[i] = "0"*16 class evil: diff --git a/Tests/test_imagetk.py b/Tests/test_imagetk.py index dd0d67d5e..2df35c584 100644 --- a/Tests/test_imagetk.py +++ b/Tests/test_imagetk.py @@ -1,5 +1,6 @@ -from helper import unittest, PillowTestCase, hopper, py3 +from helper import unittest, PillowTestCase, hopper from PIL import Image +from PIL._util import py3 try: diff --git a/src/PIL/EpsImagePlugin.py b/src/PIL/EpsImagePlugin.py index b50348771..1ae7865b1 100644 --- a/src/PIL/EpsImagePlugin.py +++ b/src/PIL/EpsImagePlugin.py @@ -26,6 +26,7 @@ import os import sys from . import Image, ImageFile from ._binary import i32le as i32 +from ._util import py3 __version__ = "0.5" @@ -206,12 +207,12 @@ class EpsImageFile(ImageFile.ImageFile): # Rewrap the open file pointer in something that will # convert line endings and decode to latin-1. try: - if bytes is str: - # Python2, no encoding conversion necessary - fp = open(self.fp.name, "Ur") - else: + if py3: # Python3, can use bare open command. fp = open(self.fp.name, "Ur", encoding='latin-1') + else: + # Python2, no encoding conversion necessary + fp = open(self.fp.name, "Ur") except: # Expect this for bytesio/stringio fp = PSFile(self.fp) diff --git a/src/PIL/Image.py b/src/PIL/Image.py index 9057c5f8d..bf187f2d4 100644 --- a/src/PIL/Image.py +++ b/src/PIL/Image.py @@ -25,6 +25,7 @@ # from . import VERSION, PILLOW_VERSION, _plugins +from ._util import py3 import logging import warnings @@ -1260,10 +1261,10 @@ class Image(object): self.load() try: - if bytes is str: - return [i8(c) for c in self.im.getpalette()] - else: + if py3: return list(self.im.getpalette()) + else: + return [i8(c) for c in self.im.getpalette()] except ValueError: return None # no palette @@ -1586,10 +1587,10 @@ class Image(object): palette = ImagePalette.raw(data.rawmode, data.palette) else: if not isinstance(data, bytes): - if bytes is str: - data = "".join(chr(x) for x in data) - else: + if py3: data = bytes(data) + else: + data = "".join(chr(x) for x in data) palette = ImagePalette.raw(rawmode, data) self.mode = "P" self.palette = palette diff --git a/src/PIL/ImageFont.py b/src/PIL/ImageFont.py index f3b55e0c4..5ae6c3a4e 100644 --- a/src/PIL/ImageFont.py +++ b/src/PIL/ImageFont.py @@ -26,7 +26,7 @@ # from . import Image -from ._util import isDirectory, isPath +from ._util import isDirectory, isPath, py3 import os import sys @@ -314,10 +314,10 @@ def load_path(filename): for directory in sys.path: if isDirectory(directory): if not isinstance(filename, str): - if bytes is str: - filename = filename.encode("utf-8") - else: + if py3: filename = filename.decode("utf-8") + else: + filename = filename.encode("utf-8") try: return load(os.path.join(directory, filename)) except IOError: diff --git a/src/PIL/ImageMath.py b/src/PIL/ImageMath.py index c5bea708a..d985877a6 100644 --- a/src/PIL/ImageMath.py +++ b/src/PIL/ImageMath.py @@ -16,6 +16,7 @@ # from . import Image, _imagingmath +from ._util import py3 try: import builtins @@ -100,7 +101,7 @@ class _Operand(object): # an image is "true" if it contains at least one non-zero pixel return self.im.getbbox() is not None - if bytes is str: + if not py3: # Provide __nonzero__ for pre-Py3k __nonzero__ = __bool__ del __bool__ @@ -151,7 +152,7 @@ class _Operand(object): def __rpow__(self, other): return self.apply("pow", other, self) - if bytes is str: + if not py3: # Provide __div__ and __rdiv__ for pre-Py3k __div__ = __truediv__ __rdiv__ = __rtruediv__ diff --git a/src/PIL/ImageQt.py b/src/PIL/ImageQt.py index 280cbc6fc..ca5fff180 100644 --- a/src/PIL/ImageQt.py +++ b/src/PIL/ImageQt.py @@ -17,7 +17,7 @@ # from . import Image -from ._util import isPath +from ._util import isPath, py3 from io import BytesIO qt_is_installed = True @@ -123,10 +123,10 @@ def _toqclass_helper(im): # handle filename, if given instead of image name if hasattr(im, "toUtf8"): # FIXME - is this really the best way to do this? - if str is bytes: - im = unicode(im.toUtf8(), "utf-8") - else: + if py3: im = str(im.toUtf8(), "utf-8") + else: + im = unicode(im.toUtf8(), "utf-8") if isPath(im): im = Image.open(im) diff --git a/src/PIL/PSDraw.py b/src/PIL/PSDraw.py index de34713ea..1c17c61b2 100644 --- a/src/PIL/PSDraw.py +++ b/src/PIL/PSDraw.py @@ -16,6 +16,7 @@ # from . import EpsImagePlugin +from ._util import py3 import sys ## @@ -34,7 +35,7 @@ class PSDraw(object): self.fp = fp def _fp_write(self, to_write): - if bytes is str or self.fp == sys.stdout: + if not py3 or self.fp == sys.stdout: self.fp.write(to_write) else: self.fp.write(bytes(to_write, 'UTF-8')) diff --git a/src/PIL/PdfParser.py b/src/PIL/PdfParser.py index 5cc5a1bbb..ceea7dd2e 100644 --- a/src/PIL/PdfParser.py +++ b/src/PIL/PdfParser.py @@ -4,6 +4,7 @@ import mmap import os import re import zlib +from ._util import py3 try: from UserDict import UserDict # Python 2.x @@ -11,12 +12,12 @@ except ImportError: UserDict = collections.UserDict # Python 3.x -if str == bytes: # Python 2.x - def make_bytes(s): # pragma: no cover - return s # pragma: no cover -else: # Python 3.x +if py3: # Python 3.x def make_bytes(s): return s.encode("us-ascii") +else: # Python 2.x + def make_bytes(s): # pragma: no cover + return s # pragma: no cover # see 7.9.2.2 Text String Type on page 86 and D.3 PDFDocEncoding Character Set on page 656 @@ -72,10 +73,10 @@ PDFDocEncoding = { def decode_text(b): if b[:len(codecs.BOM_UTF16_BE)] == codecs.BOM_UTF16_BE: return b[len(codecs.BOM_UTF16_BE):].decode("utf_16_be") - elif str == bytes: # Python 2.x - return u"".join(PDFDocEncoding.get(ord(byte), byte) for byte in b) - else: + elif py3: # Python 3.x return "".join(PDFDocEncoding.get(byte, chr(byte)) for byte in b) + else: # Python 2.x + return u"".join(PDFDocEncoding.get(ord(byte), byte) for byte in b) class PdfFormatError(RuntimeError): @@ -214,20 +215,18 @@ class PdfName: allowed_chars = set(range(33, 127)) - set(ord(c) for c in "#%/()<>[]{}") def __bytes__(self): - if str == bytes: # Python 2.x - result = bytearray(b"/") - for b in self.name: - if ord(b) in self.allowed_chars: - result.append(b) - else: - result.extend(b"#%02X" % ord(b)) - else: # Python 3.x - result = bytearray(b"/") - for b in self.name: + result = bytearray(b"/") + for b in self.name: + if py3: # Python 3.x if b in self.allowed_chars: result.append(b) else: result.extend(make_bytes("#%02X" % b)) + else: # Python 2.x + if ord(b) in self.allowed_chars: + result.append(b) + else: + result.extend(b"#%02X" % ord(b)) return bytes(result) __str__ = __bytes__ @@ -281,7 +280,7 @@ class PdfDict(UserDict): out.extend(b"\n>>") return bytes(out) - if str == bytes: + if not py3: __str__ = __bytes__ @@ -289,13 +288,13 @@ class PdfBinary: def __init__(self, data): self.data = data - if str == bytes: # Python 2.x + if py3: # Python 3.x + def __bytes__(self): + return make_bytes("<%s>" % "".join("%02X" % b for b in self.data)) + else: # Python 2.x def __str__(self): return "<%s>" % "".join("%02X" % ord(b) for b in self.data) - else: # Python 3.x - def __bytes__(self): - return make_bytes("<%s>" % "".join("%02X" % b for b in self.data)) class PdfStream: @@ -333,7 +332,7 @@ def pdf_repr(x): return bytes(PdfDict(x)) elif isinstance(x, list): return bytes(PdfArray(x)) - elif (str == bytes and isinstance(x, unicode)) or (str != bytes and isinstance(x, str)): + elif (py3 and isinstance(x, str)) or (not py3 and isinstance(x, unicode)): return pdf_repr(encode_text(x)) elif isinstance(x, bytes): return b"(" + x.replace(b"\\", b"\\\\").replace(b"(", b"\\(").replace(b")", b"\\)") + b")" # XXX escape more chars? handle binary garbage diff --git a/src/PIL/PngImagePlugin.py b/src/PIL/PngImagePlugin.py index 9eb364206..826061990 100644 --- a/src/PIL/PngImagePlugin.py +++ b/src/PIL/PngImagePlugin.py @@ -38,6 +38,7 @@ import struct from . import Image, ImageFile, ImagePalette from ._binary import i8, i16be as i16, i32be as i32, o16be as o16, o32be as o32 +from ._util import py3 __version__ = "0.9" @@ -437,7 +438,7 @@ class PngStream(ChunkStream): k = s v = b"" if k: - if bytes is not str: + if py3: k = k.decode('latin-1', 'strict') v = v.decode('latin-1', 'replace') @@ -473,7 +474,7 @@ class PngStream(ChunkStream): v = b"" if k: - if bytes is not str: + if py3: k = k.decode('latin-1', 'strict') v = v.decode('latin-1', 'replace') @@ -510,7 +511,7 @@ class PngStream(ChunkStream): return s else: return s - if bytes is not str: + if py3: try: k = k.decode("latin-1", "strict") lang = lang.decode("utf-8", "strict") diff --git a/src/PIL/SgiImagePlugin.py b/src/PIL/SgiImagePlugin.py index 8b34561e5..ef0f40ebd 100644 --- a/src/PIL/SgiImagePlugin.py +++ b/src/PIL/SgiImagePlugin.py @@ -24,6 +24,7 @@ from . import Image, ImageFile from ._binary import i8, o8, i16be as i16 +from ._util import py3 import struct import os @@ -165,7 +166,7 @@ def _save(im, fp, filename): pinmax = 255 # Image name (79 characters max, truncated below in write) imgName = os.path.splitext(os.path.basename(filename))[0] - if str is not bytes: + if py3: imgName = imgName.encode('ascii', 'ignore') # Standard representation of pixel in the file colormap = 0 diff --git a/src/PIL/TiffImagePlugin.py b/src/PIL/TiffImagePlugin.py index f9039183e..167f0cba1 100644 --- a/src/PIL/TiffImagePlugin.py +++ b/src/PIL/TiffImagePlugin.py @@ -43,6 +43,7 @@ from __future__ import division, print_function from . import Image, ImageFile, ImagePalette, TiffTags from ._binary import i8, o8 +from ._util import py3 import collections from fractions import Fraction @@ -519,7 +520,7 @@ class ImageFileDirectory_v2(collections.MutableMapping): def __contains__(self, tag): return tag in self._tags_v2 or tag in self._tagdata - if bytes is str: + if not py3: def has_key(self, tag): return tag in self @@ -528,7 +529,7 @@ class ImageFileDirectory_v2(collections.MutableMapping): def _setitem(self, tag, value, legacy_api): basetypes = (Number, bytes, str) - if bytes is str: + if not py3: basetypes += unicode, info = TiffTags.lookup(tag) @@ -549,14 +550,14 @@ class ImageFileDirectory_v2(collections.MutableMapping): elif all(isinstance(v, float) for v in values): self.tagtype[tag] = 12 else: - if bytes is str: - # Never treat data as binary by default on Python 2. - self.tagtype[tag] = 2 - else: + if py3: if all(isinstance(v, str) for v in values): self.tagtype[tag] = 2 + else: + # Never treat data as binary by default on Python 2. + self.tagtype[tag] = 2 - if self.tagtype[tag] == 7 and bytes is not str: + if self.tagtype[tag] == 7 and py3: values = [value.encode("ascii", 'replace') if isinstance( value, str) else value] @@ -1503,7 +1504,7 @@ def _save(im, fp, filename): if tag not in TiffTags.LIBTIFF_CORE: continue if tag not in atts and tag not in blocklist: - if isinstance(value, unicode if bytes is str else str): + if isinstance(value, str if py3 else unicode): atts[tag] = value.encode('ascii', 'replace') + b"\0" elif isinstance(value, IFDRational): atts[tag] = float(value) diff --git a/src/PIL/WmfImagePlugin.py b/src/PIL/WmfImagePlugin.py index 173ddb25b..213584497 100644 --- a/src/PIL/WmfImagePlugin.py +++ b/src/PIL/WmfImagePlugin.py @@ -23,13 +23,14 @@ from __future__ import print_function from . import Image, ImageFile from ._binary import i16le as word, si16le as short, i32le as dword, si32le as _long +from ._util import py3 __version__ = "0.2" _handler = None -if str != bytes: +if py3: long = int diff --git a/src/PIL/_binary.py b/src/PIL/_binary.py index b15f796c0..7e0d560b5 100644 --- a/src/PIL/_binary.py +++ b/src/PIL/_binary.py @@ -12,19 +12,20 @@ # from struct import unpack, pack +from ._util import py3 -if bytes is str: - def i8(c): - return ord(c) - - def o8(i): - return chr(i & 255) -else: +if py3: def i8(c): return c if c.__class__ is int else c[0] def o8(i): return bytes((i & 255,)) +else: + def i8(c): + return ord(c) + + def o8(i): + return chr(i & 255) # Input, le = little endian, be = big endian diff --git a/src/PIL/_util.py b/src/PIL/_util.py index 51c6f6887..6618c625f 100644 --- a/src/PIL/_util.py +++ b/src/PIL/_util.py @@ -1,17 +1,19 @@ -import os +import os, sys -if bytes is str: - def isStringType(t): - return isinstance(t, basestring) +py3 = sys.version_info.major >= 3 - def isPath(f): - return isinstance(f, basestring) -else: +if py3: def isStringType(t): return isinstance(t, str) def isPath(f): return isinstance(f, (bytes, str)) +else: + def isStringType(t): + return isinstance(t, basestring) + + def isPath(f): + return isinstance(f, basestring) # Checks if an object is a string, and that it points to a directory.