【发布时间】:2021-06-08 07:19:08
【问题描述】:
Python 3.9 引入了str.removeprefix()。我在这里仅作为示例使用它。
比方说,我想在一个库中使用这个新功能,该库应该在所有支持的 Python 版本(目前也是 3.6、3.7 和 3.8)上运行。我的意思是直接使用:mystring.removeprefix('xy_')。
我试过这个:
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
但结果是:TypeError: can't set attributes of built-in/extension type 'str'。
所以在 2024/2025 年冬季之前似乎不可能(3.8 将处于 EOL 状态)。真的是这样吗?
UPDATE1(基于@buran 评论中的链接):
这会破坏事情:
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
【问题讨论】:
-
如果你想支持旧版本,你应该实现你自己的函数,可以在内部使用
str.removeprefix,否则使用你自己的算法作为后备,然后只需将其称为s = removeprefix(s)而不是实例方法即可。当然,如果您仍然提供自己的后备代码,那么有条件地使用该方法有什么意义呢?底线:如果您的代码需要与旧版本兼容,请忽略str.removeprefix的存在。仅当您的代码需要 Python 3.9+ 时才使用它。 -
@deceze 太可悲了。但是您的评论是一个答案,如果您发布它,我会接受它。
-
@deceze 重点是编写将来会成为标准的代码。
标签: python