Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
GH-112727: Speed up pathlib.Path.absolute()
Use `_from_parsed_parts()` to create a pre-joined/pre-parsed path, rather
than passing multiple arguments to `with_segments()`
  • Loading branch information
barneygale committed Dec 4, 2023
commit b827144ff558f1f289d3a2dcc9a7768de5811261
35 changes: 21 additions & 14 deletions Lib/pathlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -1415,21 +1415,28 @@ def absolute(self):
"""
if self.is_absolute():
return self
elif self.drive:
# There is a CWD on each drive-letter drive.
cwd = os.path.abspath(self.drive)
else:
elif self.root:
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)
if self._tail:
cwd_drv = os.path.splitroot(cwd)[0]
return self._from_parsed_parts(cwd_drv, self.root, self._tail)
else:
cwd = os.path.abspath(self.drive) if self.drive else os.getcwd()
if self._tail:
# Optimization: use os.path.splitroot() rather than _parse_path().
# This is possible because os.getcwd() returns a normalized path.
cwd_drv, cwd_root, cwd_tail = os.path.splitroot(cwd)
if cwd_tail:
cwd_tail = cwd_tail.split(self.pathmod.sep)
cwd_tail.extend(self._tail)
else:
cwd_tail = self._tail
return self._from_parsed_parts(cwd_drv, cwd_root, cwd_tail)
# Optimization: store the result of os.getcwd() as the normalized
# string representation of the path.
result = self.with_segments(cwd)
result._str = cwd
return result

def resolve(self, strict=False):
"""
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Speed up :meth:`pathlib.Path.absolute`. Patch by Barney Gale.