本文介绍了通过sys.modules提供虚拟包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
说我有一个包mylibrary。
Say I have a package "mylibrary".
我想让mylibrary.config可用于导入,可以是动态创建的模块,也可以是模块从一个完全不同的地方导入,然后基本上挂载在mylibrary命名空间内。
I want to make "mylibrary.config" available for import, either as a dynamically created module, or a module imported from an entirely different place that would then basically be "mounted" inside the "mylibrary" namespace.
即,我这样做:
import sys, types
sys.modules['mylibrary.config'] = types.ModuleType('config')
鉴于此设置:
>>> import mylibrary.config # -> works
>>> from mylibrary import config
<type 'exceptions.ImportError'>: cannot import name config
甚至更奇怪:
>>> import mylibrary.config as X
<type 'exceptions.ImportError'>: cannot import name config
所以似乎使用直接导入工作,其他形式则不然。是否有可能使这些工作?
So it seems that using the direct import works, the other forms do not. Is it possible to make those work as well?
推荐答案
您需要将模块不仅修补到sys.modules,但也进入其父模块:
You need to monkey-patch the module not only into sys.modules, but also into its parent module:
>>> import sys,types,xml
>>> xml.config = sys.modules['xml.config'] = types.ModuleType('xml.config')
>>> import xml.config
>>> from xml import config
>>> from xml import config as x
>>> x
<module 'xml.config' (built-in)>
这篇关于通过sys.modules提供虚拟包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!