Skip to content

Commit

Permalink
pythongh-100562: improve performance of pathlib.Path.absolute() (py…
Browse files Browse the repository at this point in the history
…thonGH-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
  • Loading branch information
barneygale committed Jan 5, 2023
1 parent af5149f commit 7fba99e
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 5 deletions.
12 changes: 7 additions & 5 deletions Lib/pathlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -748,10 +748,12 @@ def __exit__(self, t, v, tb):

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

@classmethod
def home(cls):
Expand Down Expand Up @@ -825,7 +827,7 @@ def absolute(self):
"""
if self.is_absolute():
return self
return self._from_parts([self.cwd()] + self._parts)
return self._from_parts([os.getcwd()] + self._parts)

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

0 comments on commit 7fba99e

Please sign in to comment.