Skip to content

Commit b382bf5

Browse files
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 f32e6b4) Co-authored-by: Barney Gale <[email protected]>
1 parent 9cdfd1b commit b382bf5

File tree

3 files changed

+9
-0
lines changed

3 files changed

+9
-0
lines changed

Lib/pathlib.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -528,6 +528,8 @@ def __getitem__(self, idx):
528528

529529
if idx >= len(self) or idx < -len(self):
530530
raise IndexError(idx)
531+
if idx < 0:
532+
idx += len(self)
531533
return self._pathcls._from_parsed_parts(self._drv, self._root,
532534
self._parts[:-idx - 1])
533535

Lib/test/test_pathlib.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -463,13 +463,18 @@ def test_parents_common(self):
463463
self.assertEqual(par[0], P('/a/b'))
464464
self.assertEqual(par[1], P('/a'))
465465
self.assertEqual(par[2], P('/'))
466+
self.assertEqual(par[-1], P('/'))
467+
self.assertEqual(par[-2], P('/a'))
468+
self.assertEqual(par[-3], P('/a/b'))
466469
self.assertEqual(par[0:1], (P('/a/b'),))
467470
self.assertEqual(par[:2], (P('/a/b'), P('/a')))
468471
self.assertEqual(par[:-1], (P('/a/b'), P('/a')))
469472
self.assertEqual(par[1:], (P('/a'), P('/')))
470473
self.assertEqual(par[::2], (P('/a/b'), P('/')))
471474
self.assertEqual(par[::-1], (P('/'), P('/a'), P('/a/b')))
472475
self.assertEqual(list(par), [P('/a/b'), P('/a'), P('/')])
476+
with self.assertRaises(IndexError):
477+
par[-4]
473478
with self.assertRaises(IndexError):
474479
par[3]
475480

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Accessing the :attr:`pathlib.PurePath.parents` sequence of an absolute path
2+
using negative index values produced incorrect results.

0 commit comments

Comments
 (0)