Skip to content

Commit b4697c1

Browse files
theartfulmahmoud
authored andcommitted
Add removeprefix to strutils for older python versions & fix test on windows
1 parent 6a8ac76 commit b4697c1

File tree

2 files changed

+20
-5
lines changed

2 files changed

+20
-5
lines changed

boltons/strutils.py

+15-1
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@
5757
'iter_splitlines', 'indent', 'escape_shell_args',
5858
'args2cmd', 'args2sh', 'parse_int_list', 'format_int_list',
5959
'complement_int_list', 'int_ranges_from_int_list', 'MultiReplace',
60-
'multi_replace', 'unwrap_text']
60+
'multi_replace', 'unwrap_text', 'removeprefix']
6161

6262

6363
_punct_ws_str = string.punctuation + string.whitespace
@@ -1273,3 +1273,17 @@ def unwrap_text(text, ending='\n\n'):
12731273
if ending is None:
12741274
return all_grafs
12751275
return ending.join(all_grafs)
1276+
1277+
def removeprefix(text: str, prefix: str) -> str:
1278+
r"""
1279+
Remove `prefix` from start of `text` if present.
1280+
1281+
Backport of `str.removeprefix` for Python versions less than 3.9.
1282+
1283+
Args:
1284+
text: A string to remove the prefix from.
1285+
prefix: The string to remove from the beginning of `text`.
1286+
"""
1287+
if text.startswith(prefix):
1288+
return text[len(prefix):]
1289+
return text

tests/test_fileutils.py

+5-4
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66

77
from boltons import fileutils
88
from boltons.fileutils import FilePerms, iter_find_files
9+
from boltons.strutils import removeprefix
910

1011

1112
# Directory of boltons source files (not ending with '/').
@@ -32,13 +33,13 @@ def test_fileperms():
3233

3334
def test_iter_find_files():
3435
def _to_baseless_list(paths):
35-
return [p.removeprefix(BOLTONS_PATH) for p in paths]
36+
return [removeprefix(p, BOLTONS_PATH).lstrip(os.path.sep) for p in paths]
3637

37-
assert '/fileutils.py' in _to_baseless_list(iter_find_files(BOLTONS_PATH, patterns=['*.py']))
38+
assert 'fileutils.py' in _to_baseless_list(iter_find_files(BOLTONS_PATH, patterns=['*.py']))
3839

3940
boltons_parent = os.path.dirname(BOLTONS_PATH)
40-
assert '/fileutils.py' in _to_baseless_list(iter_find_files(boltons_parent, patterns=['*.py']))
41-
assert '/fileutils.py' not in _to_baseless_list(iter_find_files(boltons_parent, patterns=['*.py'], max_depth=0))
41+
assert 'fileutils.py' in _to_baseless_list(iter_find_files(boltons_parent, patterns=['*.py']))
42+
assert 'fileutils.py' not in _to_baseless_list(iter_find_files(boltons_parent, patterns=['*.py'], max_depth=0))
4243

4344

4445
def test_rotate_file_no_rotation(tmp_path):

0 commit comments

Comments
 (0)