summaryrefslogtreecommitdiffstats
path: root/Lib/pathlib
diff options
context:
space:
mode:
authorBarney Gale <barney.gale@gmail.com>2024-02-24 19:37:03 (GMT)
committerGitHub <noreply@github.com>2024-02-24 19:37:03 (GMT)
commite3dedeae7abbeda0cb3f1d872ebbb914635d64f2 (patch)
treef4d9a7a39a371d142907e29340420751fbd9f79e /Lib/pathlib
parent53c5c17e0a97ee06e511c89f1ca6ceb38fd06246 (diff)
downloadcpython-e3dedeae7abbeda0cb3f1d872ebbb914635d64f2.zip
cpython-e3dedeae7abbeda0cb3f1d872ebbb914635d64f2.tar.gz
cpython-e3dedeae7abbeda0cb3f1d872ebbb914635d64f2.tar.bz2
GH-114610: Fix `pathlib.PurePath.with_stem('')` handling of file extensions (#114612)
Raise `ValueError` if `with_stem('')` is called on a path with a file extension. Paths may only have an empty stem if they also have an empty suffix.
Diffstat (limited to 'Lib/pathlib')
-rw-r--r--Lib/pathlib/_abc.py10
1 files changed, 9 insertions, 1 deletions
diff --git a/Lib/pathlib/_abc.py b/Lib/pathlib/_abc.py
index 27c6b4e..44fea52 100644
--- a/Lib/pathlib/_abc.py
+++ b/Lib/pathlib/_abc.py
@@ -313,7 +313,14 @@ class PurePathBase:
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
@@ -324,6 +331,7 @@ class PurePathBase:
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)