【问题标题】:Replacing an imported module dependency替换导入的模块依赖项
【发布时间】:2015-05-21 16:54:14
【问题描述】:

As described here,在python中可以使用sys.modules替换当前的模块实现:

import somemodule

import sys
del sys.modules['somemodule']
sys.modules['somemodule'] = __import__('somefakemodule')

但是如果import somemodule在另一个导入模块的代码中完成就不行了:

在这个例子中:

自定义模块

import somemodule

def f():
    print(somemodule.someFunction())

客户代码

from CustomModule import f

import sys
del sys.modules['somemodule']
sys.modules['somemodule'] = __import__('somefakemodule')    

f() #Will use `somemodule.someFunction`

f 的调用将使用somemodule.someFunction,而不是somefakemodule.someFunction

是否可以让CustomModule 在不更改其代码的情况下将其对somemodule 的使用替换为somefakemodule?即来自ClientCode

【问题讨论】:

    标签: python python-2.7 module


    【解决方案1】:

    somemodule替换为somefakemodule之前导入CustomModule

    import sys
    del sys.modules['somemodule']
    sys.modules['somemodule'] = __import__('somefakemodule')    
    
    from CustomModule import f
    

    这样,当CustomModule 执行时

    import somemodule
    

    Python 会在sys.modules 中找到somemodule 并返回缓存的模块somefakemodule

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-12-13
      • 2023-03-29
      • 1970-01-01
      • 2017-03-02
      • 2011-02-18
      • 2013-08-15
      • 2020-10-27
      相关资源
      最近更新 更多