Skip to content

Commit

Permalink
Added .with_name and .with_stem.
Browse files Browse the repository at this point in the history
  • Loading branch information
jaraco committed Feb 4, 2024
1 parent b14a1c3 commit b84c47d
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 0 deletions.
1 change: 1 addition & 0 deletions newsfragments/+ceb93420.feature.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Added .with_name and .with_stem.
17 changes: 17 additions & 0 deletions path/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@
from . import matchers
from . import masks
from . import classes
from .compat.py38 import removesuffix


__all__ = ['Path', 'TempDir']
Expand Down Expand Up @@ -277,6 +278,14 @@ def stem(self):
base, ext = self.module.splitext(self.name)
return base

def with_stem(self, stem):
"""Return a new path with the stem changed.
>>> Path('/home/guido/python.tar.gz').with_stem("foo")
Path('/home/guido/foo.gz')
"""
return self.with_name(stem + self.suffix)

@property
def suffix(self):
"""The file extension, for example ``'.py'``."""
Expand Down Expand Up @@ -347,6 +356,14 @@ def drive(self):
""",
)

def with_name(self, name):
"""Return a new path with the name changed.
>>> Path('/home/guido/python.tar.gz').with_name("foo.zip")
Path('/home/guido/foo.zip')
"""
return self._next_class(removesuffix(self, self.name) + name)

def splitpath(self):
"""Return two-tuple of ``.parent``, ``.name``.
Expand Down
13 changes: 13 additions & 0 deletions path/compat/py38.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import sys


if sys.version_info < (3, 9):
def removesuffix(self, suffix):
# suffix='' should not call self[:-0].
if suffix and self.endswith(suffix):
return self[:-len(suffix)]
else:
return self[:]
else:
def removesuffix(self, suffix):
return self.removesuffix(suffix)

0 comments on commit b84c47d

Please sign in to comment.