_util.isPath returns True for pathlib.Path objects

Now, for functions which accept either a path or file object, the
predicate will pass on Paths and not attempt to call .read on them
before opening.

The pathlib module was added in 3.4 but os.path functions did not start
accepting path-like objects until 3.6, so that is the version after
which this implementation is defined.

Added a unit test to make sure isPath accepts Path objects. The unit
test is skipped if python version is not 3.6 or later.
This commit is contained in:
Will Badart 2019-01-28 12:14:42 -05:00
parent 071dc9409f
commit adae7ecc6a
No known key found for this signature in database
GPG Key ID: 75CC5647CFEAA75E
2 changed files with 25 additions and 2 deletions

View File

@ -1,7 +1,11 @@
import sys
from helper import unittest, PillowTestCase
from PIL import _util
py36 = sys.version_info.major >= 3 and sys.version_info.minor >= 6
class TestUtil(PillowTestCase):
@ -35,6 +39,18 @@ class TestUtil(PillowTestCase):
# Assert
self.assertTrue(it_is)
@unittest.skipIf(not py36, 'os.path support for Paths added in 3.6')
def test_path_obj_is_path(self):
# Arrange
from pathlib import Path
fp = Path('filename.ext')
# Act
it_is = _util.isPath(fp)
# Assert
self.assertTrue(it_is)
def test_is_not_path(self):
# Arrange
filename = self.tempfile("temp.ext")

View File

@ -2,13 +2,20 @@ import os
import sys
py3 = sys.version_info.major >= 3
py36 = py3 and sys.version_info.minor >= 6
if py3:
def isStringType(t):
return isinstance(t, str)
def isPath(f):
return isinstance(f, (bytes, str))
if py36:
from pathlib import Path
def isPath(f):
return isinstance(f, (bytes, str, Path))
else:
def isPath(f):
return isinstance(f, (bytes, str))
else:
def isStringType(t):
return isinstance(t, basestring) # noqa: F821