Factor out logic to generate ModuleNotFoundError in importlib?

Open
#100,208 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
2/5
Estimated time
1-3 hours
Newbie friendliness
48/100
Issue type
Feature
Clarity
Clearly specified
Activity status
Stale
Tech stack
python
Domain
backend

Research direction

Start by locating the _find_and_load_unlocked entry point and the existing _ERR_MSG and ModuleNotFoundError construction. Factor that construction into _get_module_not_found_error(name), replace the direct construction in the missing-spec path, and verify that the resulting error still carries the module name while remaining suitable for monkey patching.

Written by the indexing model from the issue text.

Description

stdlib type-feature

Feature or enhancement

PEP 534 discusses improving error messages for standard library modules. We like to do this in Pyodide because some stdlib modules either are removed or are not included by default but can be installed. If someone tries to import these modules, we want to print some extra info about why the import is failing.

The following patch is a simple change that makes it easy to monkey patch _get_module_not_found_error to improve the ModuleNotFound errors:

+def _get_module_not_found_error(name):
+    return ModuleNotFoundError(_ERR_MSG.format(name), name=name)
+
 def _find_and_load_unlocked(name, import_):
     path = None
     parent = name.rpartition('.')[0]
@@ -1001,7 +1004,7 @@ def _find_and_load_unlocked(name, import_):
             raise ModuleNotFoundError(msg, name=name) from None
     spec = _find_spec(name, path)
     if spec is None:
-        raise ModuleNotFoundError(_ERR_MSG.format(name), name=name)
+        raise _get_module_not_found_error(name)
     else:
         module = _load_unlocked(spec)
     if parent:

In Pyodide since we are fairly tightly coupled to the Python version we would be okay with risking the possibility that this gets rearranged in the future.

Pitch

It would be nice to apply this patch. See the Pyodide PR: https://github.com/pyodide/pyodide/pull/3263

Previous discussion

PEP 534

Dominant language
Python
Stars
77.2k
Forks
36k
Avg merge
1d 9h
Merged PRs (30d)
558

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from python/cpython

All issues in python/cpython

Similar issues

More Python issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.