有几个模块在 Python 3 中被重命名,我正在寻找一种解决方案,可以让你的代码在两种python 风格中都工作。
在 Python 3 中,__builtin__
被重命名为builtins
. 例子:
import __builtin__
#...
__builtin__.something # appearing multiple times ("something" may vary)
有几个模块在 Python 3 中被重命名,我正在寻找一种解决方案,可以让你的代码在两种python 风格中都工作。
在 Python 3 中,__builtin__
被重命名为builtins
. 例子:
import __builtin__
#...
__builtin__.something # appearing multiple times ("something" may vary)
本杰明彼得森的六个可能是您正在寻找的。六个“提供了简单的实用程序来解决 Python 2 和 Python 3 之间的差异”。例如:
from six.moves import builtin # works for both python 2 and 3
您可以通过使用嵌套块来解决问题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 版本一样使用了。
希望能帮助到你!