简体   繁体   中英

ModuleNotFoundError: No module named <module> on importlib import_module

I am trying to create a module hooker, that corrects module name while importing a module, here is the small prototype:

from sys import meta_path, modules
from importlib import import_module


class Hook:
    spellcheck = {"maht": "math", "randon": "random", "ramdom": "random"}

    def find_module(self, module, _):
        if module in self.spellcheck:
            return self

    def load_module(self, module):
        modules[module] = import_module(self.spellcheck[module])
        return modules[module]


meta_path.clear()
meta_path.append(Hook())

import randon
import maht

The error:

Traceback (most recent call last):
  File "/home/yagiz/Desktop/spellchecker.py", line 20, in <module>
    import randon
  File "/home/yagiz/Desktop/spellchecker.py", line 13, in load_module
    modules[module] = import_module(self.spellcheck[module])
  File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
ModuleNotFoundError: No module named 'random'

Current machine, ubuntu 18.04 and python 3.6.9 also i tried with newer versions of python

It is all about meta_path.clear() , just remove it.

By using the clear function, you are clearing meta_path from the builtin modules, so even the builtin module random couldn't be loaded.

Edit:

As discussed through comments, you can provide a misspelling error message instead of accepting loading the misspelled module. This can be done by updating your Hook class to:

class Hook:
    spellcheck = {"maht": "math", "randon": "random", "ramdom": "random"}
    def find_module(self, module, _):
        if module in self.spellcheck:
            return self
    def load_module(self, module):
        raise ImportError(f"No module named '{module}'. Did you mean '{self.spellcheck[module]}'?")

Now, if you import one of the misspelled modules:

import randon

Output:

ImportError: No module named 'randon'. Did you mean 'random'?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM