From 7e8a6c61f8550095a8c171678c955dc08d0d0976 Mon Sep 17 00:00:00 2001 From: Alessio Sergi Date: Sat, 17 Dec 2016 18:50:50 +0100 Subject: [PATCH] Use pathlib2 for Path objects on Python < 3.4 The pathlib backport module is no longer maintained. The development has moved to the pathlib2 module instead. Quoting from the pathlib's README: "Attention: this backport module isn't maintained anymore. If you want to report issues or contribute patches, please consider the pathlib2 project instead." Other projects have already switched to pathlib2, most notably IPython and its dependencies. --- PIL/Image.py | 27 +++++++++++++++------------ Tests/test_image.py | 6 ++---- 2 files changed, 17 insertions(+), 16 deletions(-) diff --git a/PIL/Image.py b/PIL/Image.py index c086dfcd7..93278ec4d 100644 --- a/PIL/Image.py +++ b/PIL/Image.py @@ -132,6 +132,16 @@ try: except ImportError: HAS_CFFI = False +try: + from pathlib import Path + HAS_PATHLIB = True +except ImportError: + try: + from pathlib2 import Path + HAS_PATHLIB = True + except ImportError: + HAS_PATHLIB = False + def isImageType(t): """ @@ -1652,11 +1662,9 @@ class Image(object): if isPath(fp): filename = fp open_fp = True - elif sys.version_info >= (3, 4): - from pathlib import Path - if isinstance(fp, Path): - filename = str(fp) - open_fp = True + elif HAS_PATHLIB and isinstance(fp, Path): + filename = str(fp) + open_fp = True if not filename and hasattr(fp, "name") and isPath(fp.name): # only set the name for metadata purposes filename = fp.name @@ -2267,13 +2275,8 @@ def open(fp, mode="r"): filename = "" if isPath(fp): filename = fp - else: - try: - from pathlib import Path - if isinstance(fp, Path): - filename = str(fp.resolve()) - except ImportError: - pass + elif HAS_PATHLIB and isinstance(fp, Path): + filename = str(fp.resolve()) if filename: fp = builtins.open(filename, "rb") diff --git a/Tests/test_image.py b/Tests/test_image.py index ef9aa16af..7c62b3297 100644 --- a/Tests/test_image.py +++ b/Tests/test_image.py @@ -2,7 +2,6 @@ from helper import unittest, PillowTestCase, hopper from PIL import Image import os -import sys class TestImage(PillowTestCase): @@ -50,10 +49,9 @@ class TestImage(PillowTestCase): im = io.BytesIO(b'') self.assertRaises(IOError, lambda: Image.open(im)) - @unittest.skipIf(sys.version_info < (3, 4), - "pathlib only available in Python 3.4 or later") + @unittest.skipUnless(Image.HAS_PATHLIB, "requires pathlib/pathlib2") def test_pathlib(self): - from pathlib import Path + from PIL.Image import Path im = Image.open(Path("Tests/images/hopper.jpg")) self.assertEqual(im.mode, "RGB") self.assertEqual(im.size, (128, 128))