Skip to content

Commit 304a1b3

Browse files
GH-112727: Speed up pathlib.Path.absolute() (#112728)
Use `_from_parsed_parts()` to create a pre-joined/pre-parsed path, rather than passing multiple arguments to `with_segments()` Co-authored-by: Alex Waygood <[email protected]>
1 parent 9fe7655 commit 304a1b3

File tree

2 files changed

+15
-6
lines changed

2 files changed

+15
-6
lines changed

Lib/pathlib.py

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1415,21 +1415,29 @@ def absolute(self):
14151415
"""
14161416
if self.is_absolute():
14171417
return self
1418-
elif self.drive:
1418+
if self.root:
1419+
drive = os.path.splitroot(os.getcwd())[0]
1420+
return self._from_parsed_parts(drive, self.root, self._tail)
1421+
if self.drive:
14191422
# There is a CWD on each drive-letter drive.
14201423
cwd = os.path.abspath(self.drive)
14211424
else:
14221425
cwd = os.getcwd()
1426+
if not self._tail:
14231427
# Fast path for "empty" paths, e.g. Path("."), Path("") or Path().
14241428
# We pass only one argument to with_segments() to avoid the cost
14251429
# of joining, and we exploit the fact that getcwd() returns a
14261430
# fully-normalized string by storing it in _str. This is used to
14271431
# implement Path.cwd().
1428-
if not self.root and not self._tail:
1429-
result = self.with_segments(cwd)
1430-
result._str = cwd
1431-
return result
1432-
return self.with_segments(cwd, self)
1432+
result = self.with_segments(cwd)
1433+
result._str = cwd
1434+
return result
1435+
drive, root, rel = os.path.splitroot(cwd)
1436+
if not rel:
1437+
return self._from_parsed_parts(drive, root, self._tail)
1438+
tail = rel.split(self.pathmod.sep)
1439+
tail.extend(self._tail)
1440+
return self._from_parsed_parts(drive, root, tail)
14331441

14341442
def resolve(self, strict=False):
14351443
"""
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Speed up :meth:`pathlib.Path.absolute`. Patch by Barney Gale.

0 commit comments

Comments
 (0)