From b382bf50c53e6eab09f3e3bf0802ab052cb0289d Mon Sep 17 00:00:00 2001 From: "Miss Islington (bot)" <31488909+miss-islington@users.noreply.github.com> Date: Fri, 3 Jun 2022 14:53:00 -0700 Subject: gh-93156 - fix negative indexing into absolute `pathlib.PurePath().parents` (GH-93273) When a `_PathParents` object has a drive or a root, the length of the object is *one less* than than the length of `self._parts`, which resulted in an off-by-one error when `path.parents[-n]` was fed through to `self._parts[:-n - 1]`. In particular, `path.parents[-1]` was a malformed path object with spooky properties. This is addressed by adding `len(self)` to negative indices. (cherry picked from commit f32e6b48d12834ba3bde01ec21c14da33abd26d6) Co-authored-by: Barney Gale --- Lib/pathlib.py | 2 ++ 1 file changed, 2 insertions(+) (limited to 'Lib/pathlib.py') diff --git a/Lib/pathlib.py b/Lib/pathlib.py index 621fba0e75..97b23ca45a 100644 --- a/Lib/pathlib.py +++ b/Lib/pathlib.py @@ -528,6 +528,8 @@ class _PathParents(Sequence): if idx >= len(self) or idx < -len(self): raise IndexError(idx) + if idx < 0: + idx += len(self) return self._pathcls._from_parsed_parts(self._drv, self._root, self._parts[:-idx - 1]) -- cgit v1.2.1