Now, I make all of the change in my module “friendly_module_not_found_error” to my cpython branch. Now I need some feedback:
Here is the effect of it:
Explanation
When import the module, if the module not found, the python will raise a ModuleNotFoundError.
In this change, if the error was raised from finding the top module, the message kept, but if it occured in submodule, the format of the message changed to “module ‘{parent}’ has no child module ‘{child}’”. If the parent module is not a package, the message add behind.
If it is a package, it will try to list all of the module under the top module:
For top module, it scan all of the path in sys.path and get all of the modules’ names lists without importing them. For child module, it will try to find the parent module to get the attribute “__path__” and get the module below it, or it will try to scan the sys.path to find the parent module and analyse.
For custom importhook, it needs a method “__find__” to find all of the module it can find(optional), or it will be ignored in suggesting. It needs a key argument “name” and default “None”. If the name is None, it needs to return all of the top modules. If the name is a module that it cannot find, it should return an empty list. If it can find, it should return all of the child module names. In this method, all of the importing are forbidden. If the Exception raised from it, if no ImportError in the whole exception (“__cause__”, “__context__”, “BaseExceptionGroup.exceptions”), it will be printed as a warning, or it will just print the traceback and tips that it mustn’t import in the method.
When running “python -m module”, the error message changed only when it raised when use importlib.util.find_spec to find the module or the result of the finding is None.
Benefit
At first, I only think that the benefit of the change is to help changing the wrong in the code. However, now it will add one:
When you have installed the right module from pip but spelled it wrong in the code (mainly from copying), the IDE (for example: PyCharm) will provide a button to fast install the package. But the typo are often associated with typosquatting attacks. If the installing fail, it is lucky, but the problem in code is still difficult to fix. However, if it successful, it is unlucky because it likely means that the attacking is successful. The suggesting in this project will provide another way (suggest a possible right module that can be imported) to fix the problem and avoid users to blindly install the wrong name module.
