1313import tokenize
1414import io
1515import importlib .util
16+ from importlib .machinery import ModuleSpec
1617import pathlib
1718import _colorize
1819
@@ -1125,16 +1126,14 @@ def __init__(self, exc_type, exc_value, exc_traceback, *, limit=None,
11251126 self ._str += f". Did you mean: '{ suggestion } ' ({ suggestion !a} )?"
11261127 elif exc_type and issubclass (exc_type , ModuleNotFoundError ):
11271128 module_name = getattr (exc_value , "name" , None )
1129+ analyse_sys_no_site = True
11281130 if module_name in sys .stdlib_module_names :
11291131 message = _MISSING_STDLIB_MODULE_MESSAGES .get (
11301132 module_name ,
11311133 f"Standard library module { module_name !r} was not found"
11321134 )
11331135 self ._str = message
1134- elif sys .flags .no_site :
1135- self ._str += (". Site initialization is disabled, did you forget to "
1136- + "add the site-packages directory to sys.path "
1137- + "or to enable your virtual environment?" )
1136+ analyse_sys_no_site = False
11381137 elif abi_tag := _find_incompatible_extension_module (module_name ):
11391138 self ._str += (
11401139 ". Although a module with this name was found for a "
@@ -1144,6 +1143,12 @@ def __init__(self, exc_type, exc_value, exc_traceback, *, limit=None,
11441143 suggestion = _compute_suggestion_error (exc_value , exc_traceback , module_name )
11451144 if suggestion :
11461145 self ._str += f". Did you mean: '{ suggestion } '?"
1146+ if analyse_sys_no_site and sys .flags .no_site :
1147+ if not self ._str .endswith (("." , "?" )):
1148+ self ._str += "."
1149+ self ._str += (" Site initialization is disabled, did you forget to "
1150+ "add the site-packages directory to sys.path "
1151+ "or to enable your virtual environment?" )
11471152 elif exc_type and issubclass (exc_type , AttributeError ) and \
11481153 getattr (exc_value , "name" , None ) is not None :
11491154 wrong_name = getattr (exc_value , "name" , None )
@@ -1758,7 +1763,10 @@ def _compute_suggestion_error(exc_value, tb, wrong_name):
17581763 d = []
17591764 for finder in sys .meta_path :
17601765 if discover := getattr (finder , 'discover' , None ):
1761- d += [spec .name for spec in discover (parent )]
1766+ try :
1767+ d += [spec .name for spec in discover (parent ) if isinstance (spec , ModuleSpec )]
1768+ except Exception :
1769+ continue
17621770 except Exception :
17631771 return None
17641772 elif isinstance (exc_value , ImportError ):
0 commit comments