拦截模块导入以从配置文件加载模块

时间:2019-03-25 02:24:59

标签: python python-2.7 python-import python-module

我正在做一个项目。不幸的是,由于兼容性问题,Python 2。我想在一个模块中提供基本功能,然后能够有一个由配置文件指定的自定义模块,如果存在,它将覆盖基本模块。

tll/
  __init__.py  
  custom.py

这是我目前正在做的事情:

path = '/path/to/other/custom.py' # actually from a config file but doesn't matter
import imp

class Config:
    def __init__(self):
        if path != '':
            self.custom = imp.load_source('tll.custom', path)
        else:
            import tll.custom
            self.custom = tll.custom

这可行,但是我想知道是否可以在不使用其他类的情况下做到这一点。我想做类似的事情:

# in tll/custom.py

path = ConfigurationManager().get('customisation')
if path is not None:
    import imp
    module = imp.load_source('tll.custom', path)
    return module

... 

# and then the base functions down here

对此有任何想法吗?

0 个答案:

没有答案
相关问题