import AttributeError:'NoneType'对象没有属性'modules'

时间:2016-06-02 13:23:34

标签: python import module

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

_submodule_by_name = {
        name: modulename
        for modulename in _submodule_exports
        for name in _submodule_exports[modulename] }

import types
import sys
import importlib

class OnDemandModule(types.ModuleType):
    def __getattr__(self, name):
        modulename = _submodule_by_name.get(name)
        if modulename:
            module = importlib.import_module(modulename, __package__)
            print('Loaded', name)
            value = getattr(module, name)
            setattr(self, name ,value)
            return value
        raise AttributeError('No attribute %s' % name)

# old_module = sys.modules[__name__]
print sys.modules[__name__]

newmoudle = OnDemandModule(__name__)
newmoudle.__dict__.update(globals())
newmoudle.__all__ = list(_submodule_by_name)
sys.modules[__name__] = newmoudle
# the following line cause the error
maintain_module = sys.modules[__name__]

上面的代码来自名为“cycles_import”的目录中的__init__.py。当我导入这个模块时,我得到了这个:

screenshot showing AttributeError

我在这个.py文件的最开头做了一个“import sys”模块。为什么“sys”未被识别为导入模块?

0 个答案:

没有答案