如何在六个中添加自定义重命名?

How to add custom renames in six?

根据文档,六个支持adding custom renames to six.moves:

six.add_move(item)

Add item to the six.moves mapping. item should be a MovedAttribute or MovedModule instance.

并且:

class six.MovedModule(name, old_mod, new_mod)

Create a mapping for six.moves called name that references different modules in Python 2 and 3. old_mod is the name of the Python 2 module. new_mod is the name of the Python 3 module.

但是,此代码为我生成了 ImportError

from six import add_move, MovedModule
add_move(MovedModule('mock', 'mock', 'unittest.mock'))
from six.moves.mock import MagicMock

当我 运行 在 Python 3.4.2 上使用六个 1.9.0 时,我收到此错误:

Traceback (most recent call last):
  File "test_six_moves.py", line 2, in <module>
    from six.moves.mock import MagicMock
ImportError: No module named 'six.moves.mock'

内置动作运行良好。我如何让它工作?

您无法从移动中导入名称。使用:

from __future__ import print_function

from six import add_move, MovedModule
add_move(MovedModule('mock', 'mock', 'unittest.mock'))

from six.moves import mock
print(mock.MagicMock)

这会给你:

# Python 2
<class 'mock.MagicMock'>

# Python 3
<class 'unittest.mock.MagicMock'>

请注意,从移动中导入适用于 six 附带的移动。例如:from six.moves.configparser import ConfigParser 有效。

这段代码(来自six.py)是为什么:

for attr in _moved_attributes:
    setattr(_MovedItems, attr.name, attr)
    if isinstance(attr, MovedModule):
        _importer._add_module(attr, "moves." + attr.name)

事实上,如果您 运行 以下内容(当然不建议干预私有属性),您的导入将起作用:

import six
mod = six.MovedModule('mock', 'mock', 'unittest.mock')
six.add_move(mod)
six._importer._add_module(mod, "moves." + mod.name)