Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions Doc/library/importlib.rst
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,16 @@ ABC hierarchy::
.. versionchanged:: 3.4
Returns ``None`` when called instead of :data:`NotImplemented`.

.. method:: discover(parent=None)

An optional method which searches for possible specs with given *parent*
module spec. If *parent* is *None*, :meth:`PathEntryFinder.discover` will
search for top-level modules.

Returns an iterable of possible specs.

.. versionadded:: next


.. class:: PathEntryFinder

Expand Down Expand Up @@ -307,6 +317,16 @@ ABC hierarchy::
:meth:`importlib.machinery.PathFinder.invalidate_caches`
when invalidating the caches of all cached finders.

.. method:: discover(parent=None)

An optional method which searches for possible specs with given *parent*
module spec. If *parent* is *None*, :meth:`PathEntryFinder.discover` will
search for top-level modules.

Returns an iterable of possible specs.

.. versionadded:: next


.. class:: Loader

Expand Down
36 changes: 36 additions & 0 deletions Lib/importlib/_bootstrap_external.py
Original file line number Diff line number Diff line change
Expand Up @@ -1323,6 +1323,21 @@ def find_spec(cls, fullname, path=None, target=None):
else:
return spec

@classmethod
def discover(cls, parent=None):
if parent is None:
path = sys.path
else:
path = parent.submodule_search_locations

for entry in path:
if not isinstance(entry, str):
continue
if (finder := cls._path_importer_cache(entry)) is None:
continue
if discover := getattr(finder, 'discover', None):
yield from discover(parent)

@staticmethod
def find_distributions(*args, **kwargs):
"""
Expand Down Expand Up @@ -1472,6 +1487,27 @@ def path_hook_for_FileFinder(path):

return path_hook_for_FileFinder

def _find_children(self):
for entry in _os.scandir(self.path):
if entry.name == _PYCACHE:
continue
# packages
if entry.is_dir() and '.' not in entry.name:
yield entry.name
# files
if entry.is_file():
yield from [
entry.name.removesuffix(suffix)
for suffix, _ in self._loaders
if entry.name.endswith(suffix)
]

def discover(self, parent=None):
module_prefix = f'{parent.name}.' if parent else ''
for child_name in self._find_children():
if spec := self.find_spec(module_prefix + child_name):
yield spec

def __repr__(self):
return f'FileFinder({self.path!r})'

Expand Down
17 changes: 17 additions & 0 deletions Lib/importlib/abc.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,15 @@ def invalidate_caches(self):
This method is used by importlib.invalidate_caches().
"""

def discover(self, parent=None):
"""An optional method which searches for possible specs with given *parent*.
If *parent* is *None*, MetaPathFinder.discover will search for top-level modules.

Returns an iterable of possible specs.
"""
return ()


_register(MetaPathFinder, machinery.BuiltinImporter, machinery.FrozenImporter,
machinery.PathFinder, machinery.WindowsRegistryFinder)

Expand All @@ -58,6 +67,14 @@ def invalidate_caches(self):
This method is used by PathFinder.invalidate_caches().
"""

def discover(self, parent=None):
"""An optional method which searches for possible specs with given *parent*.
If *parent* is *None*, PathEntryFinder.discover will search for top-level modules.

Returns an iterable of possible specs.
"""
return ()

_register(PathEntryFinder, machinery.FileFinder)


Expand Down
17 changes: 17 additions & 0 deletions Lib/traceback.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import keyword
import tokenize
import io
import importlib.util
import _colorize

from contextlib import suppress
Expand Down Expand Up @@ -1124,6 +1125,10 @@ def __init__(self, exc_type, exc_value, exc_traceback, *, limit=None,
self._str += (". Site initialization is disabled, did you forget to "
+ "add the site-packages directory to sys.path "
+ "or to enable your virtual environment?")
else:
suggestion = _compute_suggestion_error(exc_value, exc_traceback, module_name)
if suggestion:
self._str += f". Did you mean: '{suggestion}'?"
elif exc_type and issubclass(exc_type, (NameError, AttributeError)) and \
getattr(exc_value, "name", None) is not None:
wrong_name = getattr(exc_value, "name", None)
Expand Down Expand Up @@ -1672,6 +1677,18 @@ def _compute_suggestion_error(exc_value, tb, wrong_name):
d = [x for x in d if x[:1] != '_']
except Exception:
return None
elif isinstance(exc_value, ModuleNotFoundError):
try:
if parent_name := wrong_name.rpartition('.')[0]:
parent = importlib.util.find_spec(parent_name)
else:
parent = None
d = []
for finder in sys.meta_path:
if discover := getattr(finder, 'discover', None):
d += [spec.name for spec in discover(parent)]
except Exception:
return None
elif isinstance(exc_value, ImportError):
try:
mod = __import__(exc_value.name)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Introduced :meth:`MetaPathFinder.discover` and
:meth:`PathEntryFinder.discover`.
Loading