Skip to content

GH-114610: Fix pathlib.PurePath.with_stem('') handling of file extensions #114612

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Feb 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion Lib/pathlib/_abc.py
Original file line number Diff line number Diff line change
Expand Up @@ -292,7 +292,14 @@ def with_name(self, name):

def with_stem(self, stem):
"""Return a new path with the stem changed."""
return self.with_name(stem + self.suffix)
suffix = self.suffix
if not suffix:
return self.with_name(stem)
elif not stem:
# If the suffix is non-empty, we can't make the stem empty.
raise ValueError(f"{self!r} has a non-empty suffix")
else:
return self.with_name(stem + suffix)

def with_suffix(self, suffix):
"""Return a new path with the file suffix changed. If the path
Expand All @@ -303,6 +310,7 @@ def with_suffix(self, suffix):
if not suffix:
return self.with_name(stem)
elif not stem:
# If the stem is empty, we can't make the suffix non-empty.
raise ValueError(f"{self!r} has an empty name")
elif suffix.startswith('.') and len(suffix) > 1:
return self.with_name(stem + suffix)
Expand Down
2 changes: 2 additions & 0 deletions Lib/test/test_pathlib/test_pathlib_abc.py
Original file line number Diff line number Diff line change
Expand Up @@ -932,6 +932,8 @@ def test_with_stem_empty(self):
self.assertEqual(P('/').with_stem('d'), P('/d'))
self.assertEqual(P('a/b').with_stem(''), P('a/'))
self.assertEqual(P('a/b').with_stem('.'), P('a/.'))
self.assertRaises(ValueError, P('foo.gz').with_stem, '')
self.assertRaises(ValueError, P('/a/b/foo.gz').with_stem, '')

def test_with_stem_seps(self):
P = self.cls
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Fix bug where :meth:`pathlib.PurePath.with_stem` converted a non-empty path
suffix to a stem when given an empty *stem* argument. It now raises
:exc:`ValueError`, just like :meth:`pathlib.PurePath.with_suffix` does when
called on a path with an empty stem, given a non-empty *suffix* argument.