Skip to content

Commit

Permalink
pythonGH-114610: Fix pathlib._abc.PurePathBase.with_suffix('.ext')
Browse files Browse the repository at this point in the history
…handling of stems (python#114613)

Raise `ValueError` if `with_suffix('.ext')` is called on a path without a
stem. Paths may only have a non-empty suffix if they also have a non-empty
stem.

ABC-only bugfix; no effect on public classes.
  • Loading branch information
barneygale authored Jan 30, 2024
1 parent e21754d commit 809eed4
Show file tree
Hide file tree
Showing 3 changed files with 7 additions and 12 deletions.
7 changes: 5 additions & 2 deletions Lib/pathlib/_abc.py
Original file line number Diff line number Diff line change
Expand Up @@ -299,10 +299,13 @@ def with_suffix(self, suffix):
has no suffix, add given suffix. If the given suffix is an empty
string, remove the suffix from the path.
"""
stem = self.stem
if not suffix:
return self.with_name(self.stem)
return self.with_name(stem)
elif not stem:
raise ValueError(f"{self!r} has an empty name")
elif suffix.startswith('.') and len(suffix) > 1:
return self.with_name(self.stem + suffix)
return self.with_name(stem + suffix)
else:
raise ValueError(f"Invalid suffix {suffix!r}")

Expand Down
7 changes: 0 additions & 7 deletions Lib/test/test_pathlib/test_pathlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -327,13 +327,6 @@ def test_with_stem_empty(self):
self.assertRaises(ValueError, P('a/b').with_stem, '')
self.assertRaises(ValueError, P('a/b').with_stem, '.')

def test_with_suffix_empty(self):
# Path doesn't have a "filename" component.
P = self.cls
self.assertRaises(ValueError, P('').with_suffix, '.gz')
self.assertRaises(ValueError, P('.').with_suffix, '.gz')
self.assertRaises(ValueError, P('/').with_suffix, '.gz')

def test_relative_to_several_args(self):
P = self.cls
p = P('a/b')
Expand Down
5 changes: 2 additions & 3 deletions Lib/test/test_pathlib/test_pathlib_abc.py
Original file line number Diff line number Diff line change
Expand Up @@ -977,9 +977,8 @@ def test_with_suffix_windows(self):
def test_with_suffix_empty(self):
P = self.cls
# Path doesn't have a "filename" component.
self.assertEqual(P('').with_suffix('.gz'), P('.gz'))
self.assertEqual(P('.').with_suffix('.gz'), P('..gz'))
self.assertEqual(P('/').with_suffix('.gz'), P('/.gz'))
self.assertRaises(ValueError, P('').with_suffix, '.gz')
self.assertRaises(ValueError, P('/').with_suffix, '.gz')

def test_with_suffix_seps(self):
P = self.cls
Expand Down

0 comments on commit 809eed4

Please sign in to comment.