Issue #27186: Add os.PathLike support to pathlib.

This adds support both to pathlib.PurePath's constructor as well as
implementing __fspath__(). This removes the provisional status for
pathlib.

Initial patch by Dusty Phillips.
This commit is contained in:
Brett Cannon 2016-06-10 12:20:49 -07:00
parent f41b82fb19
commit 568be63248
4 changed files with 56 additions and 14 deletions

View file

@ -634,13 +634,16 @@ class PurePath(object):
for a in args:
if isinstance(a, PurePath):
parts += a._parts
elif isinstance(a, str):
# Force-cast str subclasses to str (issue #21127)
parts.append(str(a))
else:
raise TypeError(
"argument should be a path or str object, not %r"
% type(a))
a = os.fspath(a)
if isinstance(a, str):
# Force-cast str subclasses to str (issue #21127)
parts.append(str(a))
else:
raise TypeError(
"argument should be a str object or an os.PathLike "
"object returning str, not %r"
% type(a))
return cls._flavour.parse_parts(parts)
@classmethod
@ -693,6 +696,9 @@ class PurePath(object):
self._parts) or '.'
return self._str
def __fspath__(self):
return str(self)
def as_posix(self):
"""Return the string representation of the path with forward (/)
slashes."""
@ -943,6 +949,10 @@ class PurePath(object):
return False
return True
# Can't subclass os.PathLike from PurePath and keep the constructor
# optimizations in PurePath._parse_args().
os.PathLike.register(PurePath)
class PurePosixPath(PurePath):
_flavour = _posix_flavour