1616TYPE_CHECKING = False
1717
1818if TYPE_CHECKING :
19+ from types import ModuleType
1920 from typing import Any , Iterable , Iterator , Mapping
2021
2122
@@ -110,17 +111,7 @@ def _find_modules(self, path: str, prefix: str) -> list[str]:
110111 modules : Iterable [pkgutil .ModuleInfo ]
111112 imported_module = sys .modules .get (path .split ('.' )[0 ])
112113 if imported_module :
113- # Module already imported: only look in its location,
114- # even if a module with the same name would be higher in path
115- imported_path = (imported_module .__spec__
116- and imported_module .__spec__ .origin )
117- if not imported_path :
118- # Module imported but no spec/origin: propose no suggestions
119- return []
120- if os .path .basename (imported_path ) == "__init__.py" : # package
121- imported_path = os .path .dirname (imported_path )
122- import_location = os .path .dirname (imported_path )
123- modules = list (pkgutil .iter_modules ([import_location ]))
114+ modules = self ._find_already_imported_module_specs (imported_module )
124115 else :
125116 modules = self .global_cache
126117
@@ -145,6 +136,32 @@ def _is_stdlib_module(self, module_info: pkgutil.ModuleInfo) -> bool:
145136 return (isinstance (module_info .module_finder , FileFinder )
146137 and module_info .module_finder .path == self ._stdlib_path )
147138
139+ def _find_already_imported_module_specs (self , imported_module : ModuleType ) -> list [pkgutil .ModuleInfo ]:
140+ # Module already imported: only look in its location,
141+ # even if a module with the same name would be higher in path
142+ module_location = self ._get_module_location (imported_module )
143+ if not module_location :
144+ # If we cannot find the module source, propose no suggestions
145+ return []
146+ import_location = os .path .dirname (module_location )
147+ return list (pkgutil .iter_modules ([import_location ]))
148+
149+ def _get_module_location (self , imported_module : ModuleType ) -> str | None :
150+ spec = imported_module .__spec__
151+ if not spec :
152+ return None
153+ if not spec .has_location :
154+ if spec .origin == "frozen" : # See Tools/build/freeze_modules.py
155+ return os .path .join (self ._stdlib_path , f"{ spec .name } .py" )
156+ return None
157+ if not spec .origin :
158+ return None
159+ if imported_module .__package__ :
160+ # Package: the module location is the parent folder
161+ return os .path .dirname (spec .origin )
162+ else :
163+ return spec .origin
164+
148165 def is_suggestion_match (self , module_name : str , prefix : str ) -> bool :
149166 if prefix :
150167 return module_name .startswith (prefix )
0 commit comments