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

2024-10-02 10:30:47 发布

您现在位置:Python中文网/ 问答频道 /正文

根据文档,有六种支持adding custom renames到{a2}:

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

当我使用6个1.9.0在Python 3.4.2上运行它时,会出现以下错误:

^{pr2}$

内置的动作效果很好。我怎么才能让它工作?在


Tags: ofthenameaddmodnewmoveis
1条回答
网友
1楼 · 发布于 2024-10-02 10:30:47

不能从移动中导入名称。使用:

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)

这将为您提供:

^{pr2}$

请注意,从移动中导入适用于six附带的那些。例如:from six.moves.configparser import ConfigParser起作用。在

这段代码(来自^{})就是为什么:

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)

相关问题 更多 >

    热门问题