Skip to content

Commit

Permalink
pythonGH-101362: Check pathlib.Path flavour compatibility at import time
Browse files Browse the repository at this point in the history
This saves a comparison in `pathlib.Path.__new__()` and reduces the time
taken to run `Path()` by ~5%
  • Loading branch information
barneygale committed Feb 7, 2023
1 parent 144aaa7 commit 82fc553
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 5 deletions.
16 changes: 11 additions & 5 deletions Lib/pathlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -709,11 +709,7 @@ def __new__(cls, *args, **kwargs):
warnings._deprecated("pathlib.PurePath(**kwargs)", msg, remove=(3, 14))
if cls is Path:
cls = WindowsPath if os.name == 'nt' else PosixPath
self = cls._from_parts(args)
if self._flavour is not os.path:
raise NotImplementedError("cannot instantiate %r on your system"
% (cls.__name__,))
return self
return cls._from_parts(args)

def _make_child_relpath(self, part):
# This is an optimization used for dir walking. `part` must be
Expand Down Expand Up @@ -1258,9 +1254,19 @@ class PosixPath(Path, PurePosixPath):
"""
__slots__ = ()

if posixpath is not os.path:
def __new__(cls, *args, **kwargs):
raise NotImplementedError("cannot instantiate %r on your system"
% (cls.__name__,))

class WindowsPath(Path, PureWindowsPath):
"""Path subclass for Windows systems.
On a Windows system, instantiating a Path should return this object.
"""
__slots__ = ()

if ntpath is not os.path:
def __new__(cls, *args, **kwargs):
raise NotImplementedError("cannot instantiate %r on your system"
% (cls.__name__,))
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Speed up :cls:`pathlib.Path` construction by running the path flavour
compatibility check only when pathlib is imported.

0 comments on commit 82fc553

Please sign in to comment.