Skip to content

Commit

Permalink
Implement .replace.
Browse files Browse the repository at this point in the history
Ref #214
  • Loading branch information
jaraco committed Jul 27, 2024
1 parent 66992c3 commit 3232088
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
1 change: 1 addition & 0 deletions newsfragments/214.feature.1.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Implement .replace.
35 changes: 35 additions & 0 deletions path/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
import importlib
import itertools
import os
import pathlib
import re
import shutil
import sys
Expand Down Expand Up @@ -1310,6 +1311,40 @@ def renames(self, new):
os.renames(self, new)
return self._next_class(new)

def replace(self, target_or_old: Path | str, *args) -> Path:
"""
Replace a path or substitute substrings.
Implements both pathlib.Path.replace and str.replace.
If only a target is supplied, rename this path to the target path,
overwriting if that path exists.
>>> dest = Path(getfixture('tmp_path'))
>>> orig = dest.joinpath('foo').touch()
>>> new = orig.replace(dest.joinpath('fee'))
>>> orig.exists()
False
>>> new.exists()
True
..seealso:: :meth:`pathlib.Path.replace`
If a second parameter is supplied, perform a textual replacement.
>>> Path('foo').replace('o', 'e')
Path('fee')
>>> Path('foo').replace('o', 'l', 1)
Path('flo')
..seealso:: :meth:`str.replace`
"""
return self._next_class(
super().replace(target_or_old, *args)
if args
else pathlib.Path(self).replace(target_or_old)
)

#
# --- Create/delete operations on directories

Expand Down

0 comments on commit 3232088

Please sign in to comment.