feat: backport removeprefix and removesuffix functions for compatibility with Python <3.9

This commit is contained in:
2026-07-06 22:41:03 +08:00
parent 7e0f33be23
commit 6c007c0e35
2 changed files with 39 additions and 15 deletions
+33 -12
View File
@@ -301,32 +301,53 @@ def get_serial_pair(serial):
return None, None
def remove_prefix(s, prefix):
@t.overload
def removeprefix(s: str, prefix: str) -> str: ...
@t.overload
def removeprefix(s: bytes, prefix: bytes) -> bytes: ...
@t.overload
def removesuffix(s: str, suffix: str) -> str: ...
@t.overload
def removesuffix(s: bytes, suffix: bytes) -> bytes: ...
def removeprefix(s, prefix):
"""
Remove prefix of a string or bytes like `string.removeprefix(prefix)`, which is on Python3.9+
Backport `string.removeprefix(prefix)`, which is on Python>=3.9
Args:
s (str, bytes):
prefix (str, bytes):
s (str | bytes):
prefix (str | bytes):
Returns:
str, bytes:
str | bytes:
"""
return s[len(prefix):] if s.startswith(prefix) else s
if s.startswith(prefix):
return s[len(prefix):]
return s
def remove_suffix(s, suffix):
def removesuffix(s, suffix):
"""
Remove suffix of a string or bytes like `string.removesuffix(suffix)`, which is on Python3.9+
Backport `string.removesuffix(suffix)`, which is on Python>=3.9
Args:
s (str, bytes):
suffix (str, bytes):
s (str | bytes):
suffix (str | bytes):
Returns:
str, bytes:
str | bytes:
"""
return s[:-len(suffix)] if s.endswith(suffix) else s
# s[:-0] is empty string, so we need to check if suffix is empty
if suffix and s.endswith(suffix):
return s[:-len(suffix)]
return s
class IniterNoMinicap(u2.init.Initer):
+6 -3
View File
@@ -25,7 +25,7 @@ except KeyError:
logger.error('Patch pkg_resources failed, patch module does not exists')
def remove_suffix(s, suffix):
def removesuffix(s, suffix):
"""
Remove suffix of a string or bytes like `string.removesuffix(suffix)`, which is on Python3.9+
@@ -36,7 +36,10 @@ def remove_suffix(s, suffix):
Returns:
str, bytes:
"""
return s[:-len(suffix)] if s.endswith(suffix) else s
# s[:-0] is empty string, so we need to check if suffix is empty
if suffix and s.endswith(suffix):
return s[:-len(suffix)]
return s
class FakeDistributionObject:
@@ -71,7 +74,7 @@ class PackageCache:
# adbutils-0.11.0-py3.7.egg-info
res = re.match(r'^([a-zA-Z0-9._]+)-([a-zA-Z0-9._]+)-', file)
if res:
version = remove_suffix(res.group(2), '.dist')
version = removesuffix(res.group(2), '.dist')
# version = res.group(2)
obj = FakeDistributionObject(
dist=res.group(1),