python - 如何反向移植像 str.removeprefix 这样的方法?

标签 python

引入 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

最佳答案

事实:

  • 猴子修补内置函数介于困难和不可能之间,这通常是一件好事
  • 无论如何你都需要提供一个回退实现,那么有条件地使用内置方法的意义何在,冒着不同 Python 版本之间行为差异的风险

结论:

如果您需要支持较旧的 Python 版本,请按照只有您希望支持的最低版本可用的方式进行开发。 IE。如果您将 Python 3.6 设置为最低要求版本,则仅使用 Python 3.6 中可用的功能并将较新版本中的任何内容视为不存在,因为事实上它至少存在于您的一个版本中想要支持。

关于python - 如何反向移植像 str.removeprefix 这样的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67883073/

相关文章:

python - jinja2 从字符串 : TypeError: no loader for this environment specified 加载模板

python - 有没有更短的方法可以通过 mod 来做到这一点,我想把一个词的每个其他字母都变成大写。让它像这样

python - 让 Python 使用我目录中的代码(不是/usr/...)

python - 将时间范围转置为时间矩阵的最快方法

python - Google App Engine 不支持 Geopy?

python - 使用 matplotlib 绘制交互式直方图?

python - Django filestorage 保存方法根据文件名创建路径

python - pandas groupby的求和结果

python - Python 是否有计算多项式系数的函数?

python - 如何将多个字段传递给搜索功能?在 Odoo 9