1

有几个模块在 Python 3 中被重命名,我正在寻找一种解决方案,可以让你的代码在两种python 风格中都工作。

在 Python 3 中,__builtin__被重命名为builtins. 例子:

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

2 回答 2

3

本杰明彼得森的六个可能是您正在寻找的。六个“提供了简单的实用程序来解决 Python 2 和 Python 3 之间的差异”。例如:

from six.moves import builtin  # works for both python 2 and 3
于 2010-07-17T09:26:56.543 回答
1

您可以通过使用嵌套块来解决问题try .. except

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

现在你可以__builtins__像以前的 python 版本一样使用了。

希望能帮助到你!

于 2010-07-17T09:26:33.690 回答