8000 gh-100562: improve performance of `pathlib.Path.absolute()` (GH-100563) · python/cpython@7fba99e · GitHub
[go: up one dir, main page]

Skip to content

Commit 7fba99e

Browse files
authored
gh-100562: improve performance of pathlib.Path.absolute() (GH-100563)
Increase performance of the `absolute()` method by calling `os.getcwd()` directly, rather than using the `Path.cwd()` class method. This avoids constructing an extra `Path` object (and the parsing/normalization that comes with it). Decrease performance of the `cwd()` class method by calling the `Path.absolute()` method, rather than using `os.getcwd()` directly. This involves constructing an extra `Path` object. We do this to maintain a longstanding pattern where `os` functions are called from only one place, which allows them to be more readily replaced by users. As `cwd()` is generally called at most once within user programs, it's a good bargain. ```shell # before $ ./python -m timeit -s 'from pathlib import Path; p = Path("foo", "bar")' 'p.absolute()' 50000 loops, best of 5: 9.04 usec per loop # after $ ./python -m timeit -s 'from pathlib import Path; p = Path("foo", "bar")' 'p.absolute()' 50000 loops, best of 5: 5.02 usec per loop ``` Automerge-Triggered-By: GH:AlexWaygood
1 parent af5149f commit 7fba99e

File tree

2 files changed

+10
-5
lines changed

2 files changed

+10
-5
lines changed

Lib/pathlib.py

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -748,10 +748,12 @@ def __exit__(self, t, v, tb):
748748

749749
@classmethod
750750
def cwd(cls):
751-
"""Return a new path pointing to the current working directory
752-
(as returned by os.getcwd()).
753-
"""
754-
return cls(os.getcwd())
751+
"""Return a new path pointing to the current working directory."""
752+
# We call 'absolute()' rather than using 'os.getcwd()' directly to
753+
# enable users to replace the implementation of 'absolute()' in a
754+
# subclass and benefit from the new behaviour here. This works because
755+
# os.path.abspath('.') == os.getcwd().
756+
return cls().absolute()
755757

756758
@classmethod
757759
def home(cls):
@@ -825,7 +827,7 @@ def absolute(self):
825827
"""
826828
if self.is_absolute():
827829
return self
828-
return self._from_parts([self.cwd()] + self._parts)
830+
return self._from_parts([os.getcwd()] + self._parts)
829831

830832
def resolve(self, strict=False):
831833
"""
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Improve performance of :meth:`pathlib.Path.absolute` by nearly 2x. This comes
2+
at the cost of a performance regression in :meth:`pathlib.Path.cwd`, which is
3+
generally used less frequently in user code.

0 commit comments

Comments
 (0)
0