Merge pull request #3105 from radarhere/py3

Change Python version checks to use util
This commit is contained in:
Hugo 2018-04-22 18:37:33 +03:00 committed by GitHub
commit 04a1f71b4c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
26 changed files with 130 additions and 108 deletions

View File

@ -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')))

View File

@ -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')))

View File

@ -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

View File

@ -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)

View File

@ -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

View File

@ -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

View File

@ -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__)

View File

@ -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'))

View File

@ -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)

View File

@ -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):

View File

@ -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):

View File

@ -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:

View File

@ -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:

View File

@ -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)

View File

@ -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

View File

@ -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:

View File

@ -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__

View File

@ -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)

View File

@ -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'))

View File

@ -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:
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

View File

@ -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")

View File

@ -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

View File

@ -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)

View File

@ -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

View File

@ -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

View File

@ -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.