【问题标题】:How to use python modules that were renamed 3 in a cross compatible way?如何以交叉兼容的方式使用重命名为 3 的 python 模块?
【发布时间】:2010-07-17 09:19:29
【问题描述】:

有几个modules that were renamed in Python 3,我正在寻找一种解决方案,可以让您的代码在两种 python 风格中工作。

在 Python 3 中,__builtin__ 被重命名为 builtins。示例:

import __builtin__
#...
__builtin__.something # appearing multiple times ("something" may vary)

【问题讨论】:

    标签: python python-2.x python-3.x


    【解决方案1】:

    Benjamin Peterson 的six 可能就是您想要的。六个“提供了简单的实用程序来解决 Python 2 和 Python 3 之间的差异”。例如:

    from six.moves import builtin  # works for both python 2 and 3
    

    【讨论】:

    • 谢谢,这解决了更多与 py3 相关的问题。您可以稍微改进一下答案,包括对该模块的简短描述(仅供其他读者使用)。备注:六非常小,很容易包含在你的包中,以最小化依赖。
    • 时间机器又来了:我刚刚做到了。
    • 这不再适用于 6-1.0b1。试试import six; six.moves.builtin
    【解决方案2】:

    您可以使用嵌套的try .. except-blocks 来解决问题:

    try:
        name = __builtins__.name
    except NameError:
        try:
            name = builtins.name
        except NameError:
            name = __buildins__.name
            # if this will fail, the exception will be raised
    

    这不是真正的代码,只是一个示例,但name 将具有正确的内容,与您的版本无关。在块内部,您还可以import newname as oldname 或将值从新的全局builtins 复制到旧的__buildin__

    try:
        __builtins__ = builtins
    except NameError:
        try:
            __builtins__ = buildins # just for example
        except NameError:
            __builtins__ = __buildins__
            # if this will fail, the exception will be raised
    

    现在您可以像以前的 python 版本一样使用__builtins__

    希望对你有帮助!

    【讨论】:

    • 抱歉,“某事”可能会有所不同。我修改了问题以澄清这一点。
    猜你喜欢
    • 2023-03-14
    • 2014-08-10
    • 2021-12-27
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    • 2017-06-25
    • 2016-10-09
    • 2020-06-04
    相关资源
    最近更新 更多