Skip to content

Commit

Permalink
gh-93156 - fix negative indexing into absolute `pathlib.PurePath().pa…
Browse files Browse the repository at this point in the history
…rents` (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 f32e6b4)

Co-authored-by: Barney Gale <barney.gale@gmail.com>
  • Loading branch information
miss-islington and barneygale committed Jun 3, 2022
1 parent e4113be commit 9f101c2
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 0 deletions.
2 changes: 2 additions & 0 deletions Lib/pathlib.py
Expand Up @@ -443,6 +443,8 @@ def __getitem__(self, idx):

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])

Expand Down
5 changes: 5 additions & 0 deletions Lib/test/test_pathlib.py
Expand Up @@ -465,13 +465,18 @@ def test_parents_common(self):
self.assertEqual(par[0], P('/a/b'))
self.assertEqual(par[1], P('/a'))
self.assertEqual(par[2], P('/'))
self.assertEqual(par[-1], P('/'))
self.assertEqual(par[-2], P('/a'))
self.assertEqual(par[-3], P('/a/b'))
self.assertEqual(par[0:1], (P('/a/b'),))
self.assertEqual(par[:2], (P('/a/b'), P('/a')))
self.assertEqual(par[:-1], (P('/a/b'), P('/a')))
self.assertEqual(par[1:], (P('/a'), P('/')))
self.assertEqual(par[::2], (P('/a/b'), P('/')))
self.assertEqual(par[::-1], (P('/'), P('/a'), P('/a/b')))
self.assertEqual(list(par), [P('/a/b'), P('/a'), P('/')])
with self.assertRaises(IndexError):
par[-4]
with self.assertRaises(IndexError):
par[3]

Expand Down
@@ -0,0 +1,2 @@
Accessing the :attr:`pathlib.PurePath.parents` sequence of an absolute path
using negative index values produced incorrect results.

0 comments on commit 9f101c2

Please sign in to comment.