Python 3.9 introduced str.removeprefix(). I'm using it here as an example only.
Let's say, I would like to use this new feature in a library supposed to run on all supported Python versions (also 3.6, 3.7 and 3.8 as of now). I mean a direct usage: mystring.removeprefix('xy_')
.
I tried this:
if sys.version_info < (3,9):
def removeprefix_compat(self, prefix):
# implement removeprefix (or just copy it from PEP-616)
return 'TODO'
str.removeprefix = removeprefix_compat
but the result is: TypeError: can't set attributes of built-in/extension type 'str'
.
So it seems not possible until winter 2024/2025 (3.8 will be in EOL state). Is it really so?
UPDATE1 (based on links from @buran's comment):
This breaks things:
import json, builtins
class PatchedStr(str):
pass
builtins.str = PatchedStr
json.loads('"aaa"')
# TypeError: the JSON object must be str, bytes or bytearray, not str