临时删除python modu

2024-06-16 17:56:26 发布

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

我正在尝试从中临时删除一个python模块系统模块这样我就可以把它作为测试用例的一部分导入(模拟出各种系统函数),然后再放回去。(是的,这有点疯狂,我可能最终会重组代码,而不是,但现在我很好奇…)

我可以移除模块并重新导入它,但我似乎无法在完成后将其放回原始模块。(也许这是不可能的吗?)我写了一个测试用例来验证这个想法:

class Test(unittest.TestCase):

    def test_assumptions(self):
        import meta.common.fileutils as fu1
        del(sys.modules["meta.common.fileutils"])
        import meta.common.fileutils
        del(sys.modules["meta.common.fileutils"])
        sys.modules["meta.common.fileutils"] = fu1 # I hoped this would set the module back
        import meta.common.fileutils as fu2
        self.assertEqual(fu1, fu2)  # assert fails, fu2 is a new copy of module :-(

有人能告诉我为什么它会失败吗?在

使用其中一个答案建议的pop()进行编辑也会失败:

^{pr2}$

Tags: 模块importselfmodules系统assys测试用例
2条回答

在我看来,这里的问题和包裹有关。特别是,对于位于包中的模块(例如meta.common),有两种方法可以访问它:通过sys.modules和通过父包的字典(即meta.common.__dict__)。在我看来,import meta.common.fileutils as fu2行是从meta.common.__dict__得到fu2的值,而不是从sys.modules得到的。在

所以解决办法:除了猴子打补丁系统模块,您还应该monkey修补父包。一、 e.加上这样的内容:

>>> import meta.common
>>> meta.common.fileutils = fu1

就在sys.modules["meta.common.fileutils"] = fu1行之前。在

{epython{eecdm>实际上是。在

将原始module对象存储在局部变量中,使用^{}删除模块并返回它:

orig = sys.modules.pop('meta.common.fileutils')

然后,在恢复它时,只需将该对象放回sys.modules

^{pr2}$

相关问题 更多 >