Skip to content

Commit ae20ebb

Browse files
barneygaleaisk
authored andcommitted
pythonGH-113528: Deoptimise pathlib._abc.PurePathBase.name (python#113531)
Replace usage of `_from_parsed_parts()` with `with_segments()` in `with_name()`, and take a similar approach in `name` for consistency's sake.
1 parent 013d383 commit ae20ebb

File tree

2 files changed

+25
-7
lines changed

2 files changed

+25
-7
lines changed

Lib/pathlib/__init__.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -166,6 +166,25 @@ def __ge__(self, other):
166166
return NotImplemented
167167
return self._parts_normcase >= other._parts_normcase
168168

169+
@property
170+
def name(self):
171+
"""The final path component, if any."""
172+
tail = self._tail
173+
if not tail:
174+
return ''
175+
return tail[-1]
176+
177+
def with_name(self, name):
178+
"""Return a new path with the file name changed."""
179+
m = self.pathmod
180+
if not name or m.sep in name or (m.altsep and m.altsep in name) or name == '.':
181+
raise ValueError(f"Invalid name {name!r}")
182+
tail = self._tail.copy()
183+
if not tail:
184+
raise ValueError(f"{self!r} has an empty name")
185+
tail[-1] = name
186+
return self._from_parsed_parts(self.drive, self.root, tail)
187+
169188
def relative_to(self, other, /, *_deprecated, walk_up=False):
170189
"""Return the relative path to another path identified by the passed
171190
arguments. If the operation is not possible (because this is not

Lib/pathlib/_abc.py

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -313,10 +313,10 @@ def anchor(self):
313313
@property
314314
def name(self):
315315
"""The final path component, if any."""
316-
tail = self._tail
317-
if not tail:
316+
path_str = str(self)
317+
if not path_str or path_str == '.':
318318
return ''
319-
return tail[-1]
319+
return self.pathmod.basename(path_str)
320320

321321
@property
322322
def suffix(self):
@@ -360,11 +360,10 @@ def with_name(self, name):
360360
m = self.pathmod
361361
if not name or m.sep in name or (m.altsep and m.altsep in name) or name == '.':
362362
raise ValueError(f"Invalid name {name!r}")
363-
tail = self._tail.copy()
364-
if not tail:
363+
parent, old_name = m.split(str(self))
364+
if not old_name or old_name == '.':
365365
raise ValueError(f"{self!r} has an empty name")
366-
tail[-1] = name
367-
return self._from_parsed_parts(self.drive, self.root, tail)
366+
return self.with_segments(parent, name)
368367

369368
def with_stem(self, stem):
370369
"""Return a new path with the stem changed."""

0 commit comments

Comments
 (0)