Reputation: 20618
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
Upvotes: 1
Views: 1537
Reputation: 1480
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'?
Upvotes: 2