Skip to content

Commit de7f694

Browse files
authored
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.
1 parent 376137f commit de7f694

File tree

2 files changed

+14
-1
lines changed

2 files changed

+14
-1
lines changed

Lib/pathlib.py

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -664,7 +664,7 @@ def is_absolute(self):
664664
# ntpath.isabs() is defective - see GH-44626 .
665665
if self._flavour is ntpath:
666666
return bool(self.drive and self.root)
667-
return self._flavour.isabs(self)
667+
return self._flavour.isabs(self._raw_path)
668668

669669
def is_reserved(self):
670670
"""Return True if the path contains one of the special names reserved
@@ -873,6 +873,15 @@ def absolute(self):
873873
cwd = self._flavour.abspath(self.drive)
874874
else:
875875
cwd = os.getcwd()
876+
# Fast path for "empty" paths, e.g. Path("."), Path("") or Path().
877+
# We pass only one argument to with_segments() to avoid the cost
878+
# of joining, and we exploit the fact that getcwd() returns a
879+
# fully-normalized string by storing it in _str. This is used to
880+
# implement Path.cwd().
881+
if not self.root and not self._tail:
882+
result = self.with_segments(cwd)
883+
result._str = cwd
884+
return result
876885
return self.with_segments(cwd, self)
877886

878887
def resolve(self, strict=False):
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
Improve performance of :meth:`pathlib.Path.absolute` and
2+
:meth:`~pathlib.Path.cwd` by joining paths only when necessary. Also improve
3+
performance of :meth:`pathlib.PurePath.is_absolute` on Posix by skipping path
4+
parsing and normalization.

0 commit comments

Comments
 (0)