Skip to content

Commit 3e60e02

Browse files
authored
GH-101362: Check pathlib.Path flavour compatibility at import time (GH-101664)
This saves a comparison in `pathlib.Path.__new__()` and reduces the time taken to run `Path()` by ~5%. Automerge-Triggered-By: GH:AlexWaygood
1 parent 3572c86 commit 3e60e02

File tree

2 files changed

+13
-5
lines changed

2 files changed

+13
-5
lines changed

Lib/pathlib.py

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -707,11 +707,7 @@ def __new__(cls, *args, **kwargs):
707707
warnings._deprecated("pathlib.PurePath(**kwargs)", msg, remove=(3, 14))
708708
if cls is Path:
709709
cls = WindowsPath if os.name == 'nt' else PosixPath
710-
self = cls._from_parts(args)
711-
if self._flavour is not os.path:
712-
raise NotImplementedError("cannot instantiate %r on your system"
713-
% (cls.__name__,))
714-
return self
710+
return cls._from_parts(args)
715711

716712
def _make_child_relpath(self, part):
717713
# This is an optimization used for dir walking. `part` must be
@@ -1261,9 +1257,19 @@ class PosixPath(Path, PurePosixPath):
12611257
"""
12621258
__slots__ = ()
12631259

1260+
if os.name == 'nt':
1261+
def __new__(cls, *args, **kwargs):
1262+
raise NotImplementedError(
1263+
f"cannot instantiate {cls.__name__!r} on your system")
1264+
12641265
class WindowsPath(Path, PureWindowsPath):
12651266
"""Path subclass for Windows systems.
12661267
12671268
On a Windows system, instantiating a Path should return this object.
12681269
"""
12691270
__slots__ = ()
1271+
1272+
if os.name != 'nt':
1273+
def __new__(cls, *args, **kwargs):
1274+
raise NotImplementedError(
1275+
f"cannot instantiate {cls.__name__!r} on your system")
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Speed up :class:`pathlib.Path` construction by running the path flavour
2+
compatibility check only when pathlib is imported.

0 commit comments

Comments
 (0)