]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
GH-101362: Check pathlib.Path flavour compatibility at import time (GH-101664)
authorBarney Gale <barney.gale@gmail.com>
Sun, 5 Mar 2023 22:46:45 +0000 (22:46 +0000)
committerGitHub <noreply@github.com>
Sun, 5 Mar 2023 22:46:45 +0000 (14:46 -0800)
This saves a comparison in `pathlib.Path.__new__()` and reduces the time taken to run `Path()` by ~5%.

Automerge-Triggered-By: GH:AlexWaygood
Lib/pathlib.py
Misc/NEWS.d/next/Library/2023-02-07-20-46-08.gh-issue-101362.2ckZ6R.rst [new file with mode: 0644]

index ed0f2cc73dfa691a9615c37a0f600ef5af5b40b0..c37ff21c0352d89c815cfc7f648b4e29c58fdfd7 100644 (file)
@@ -707,11 +707,7 @@ class Path(PurePath):
             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
@@ -1261,9 +1257,19 @@ class PosixPath(Path, PurePosixPath):
     """
     __slots__ = ()
 
+    if os.name == 'nt':
+        def __new__(cls, *args, **kwargs):
+            raise NotImplementedError(
+                f"cannot instantiate {cls.__name__!r} on your system")
+
 class WindowsPath(Path, PureWindowsPath):
     """Path subclass for Windows systems.
 
     On a Windows system, instantiating a Path should return this object.
     """
     __slots__ = ()
+
+    if os.name != 'nt':
+        def __new__(cls, *args, **kwargs):
+            raise NotImplementedError(
+                f"cannot instantiate {cls.__name__!r} on your system")
diff --git a/Misc/NEWS.d/next/Library/2023-02-07-20-46-08.gh-issue-101362.2ckZ6R.rst b/Misc/NEWS.d/next/Library/2023-02-07-20-46-08.gh-issue-101362.2ckZ6R.rst
new file mode 100644 (file)
index 0000000..8421466
--- /dev/null
@@ -0,0 +1,2 @@
+Speed up :class:`pathlib.Path` construction by running the path flavour
+compatibility check only when pathlib is imported.