[Python-checkins] GH-103548: Improve performance of `pathlib.Path.[is_]absolute()` (GH-103549)

barneygale webhook-mailer at python.org
Sat May 6 14:03:21 EDT 2023


https://github.com/python/cpython/commit/de7f694e3c92797fe65f04cd2c6941ed0446bb24
commit: de7f694e3c92797fe65f04cd2c6941ed0446bb24
branch: main
author: Barney Gale <barney.gale at gmail.com>
committer: barneygale <barney.gale at gmail.com>
date: 2023-05-06T18:03:07Z
summary:

GH-103548: Improve performance of `pathlib.Path.[is_]absolute()` (GH-103549)

Improve performance of `pathlib.Path.absolute()` and `cwd()` by joining paths only when necessary. Also improve
performance of `PurePath.is_absolute()` on Posix by skipping path parsing and normalization.

files:
A Misc/NEWS.d/next/Library/2023-04-14-21-16-05.gh-issue-103548.lagdpp.rst
M Lib/pathlib.py

diff --git a/Lib/pathlib.py b/Lib/pathlib.py
index 9aa3c1e52447..480c354ce8b6 100644
--- a/Lib/pathlib.py
+++ b/Lib/pathlib.py
@@ -664,7 +664,7 @@ def is_absolute(self):
         # ntpath.isabs() is defective - see GH-44626 .
         if self._flavour is ntpath:
             return bool(self.drive and self.root)
-        return self._flavour.isabs(self)
+        return self._flavour.isabs(self._raw_path)
 
     def is_reserved(self):
         """Return True if the path contains one of the special names reserved
@@ -873,6 +873,15 @@ def absolute(self):
             cwd = self._flavour.abspath(self.drive)
         else:
             cwd = os.getcwd()
+            # Fast path for "empty" paths, e.g. Path("."), Path("") or Path().
+            # We pass only one argument to with_segments() to avoid the cost
+            # of joining, and we exploit the fact that getcwd() returns a
+            # fully-normalized string by storing it in _str. This is used to
+            # implement Path.cwd().
+            if not self.root and not self._tail:
+                result = self.with_segments(cwd)
+                result._str = cwd
+                return result
         return self.with_segments(cwd, self)
 
     def resolve(self, strict=False):
diff --git a/Misc/NEWS.d/next/Library/2023-04-14-21-16-05.gh-issue-103548.lagdpp.rst b/Misc/NEWS.d/next/Library/2023-04-14-21-16-05.gh-issue-103548.lagdpp.rst
new file mode 100644
index 000000000000..238f28688674
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2023-04-14-21-16-05.gh-issue-103548.lagdpp.rst
@@ -0,0 +1,4 @@
+Improve performance of :meth:`pathlib.Path.absolute` and
+:meth:`~pathlib.Path.cwd` by joining paths only when necessary. Also improve
+performance of :meth:`pathlib.PurePath.is_absolute` on Posix by skipping path
+parsing and normalization.



More information about the Python-checkins mailing list