zhengxiaowai
1/11/2017 - 4:04 PM

Python Package 自动导入 Module

Python Package 自动导入 Module

#!/usr/bin/env python
# -*- coding:utf-8 -*-

import sys
from types import ModuleType

all_by_module = {
    'spam.bar': ['Bar'],
    'spam.foo': ['Foo']
}

object_origins = {}
for module, items in all_by_module.items():
    for item in items:
        object_origins[item] = module


class OneModule(ModuleType):
    def __getattr__(self, name):
        if name in object_origins:
            module = __import__(object_origins[name], None, None, fromlist=[name])
            for extra_name in all_by_module[module.__name__]:
                setattr(self, extra_name, getattr(module, extra_name))
            return getattr(module, name)
        else:
            raise ImportError('Not Found {0} Module'.format(name))

# 保持引用,防止被 gc 干掉
old_module = sys.modules['spam']
new_module = OneModule('spam')
new_module.__dict__.update({
    '__file__':         __file__,
    '__package__':      'spam',
    '__path__':         __path__,
    '__doc__':          __doc__,
    '__version__':      '0.1.0',
    '__all__':          tuple(object_origins),
})
sys.modules['spam'] = new_module