@@ -108,12 +108,18 @@ def _find_modules(self, path: str, prefix: str) -> list[str]:
108108 if path is None :
109109 return []
110110
111- modules : Iterable [pkgutil .ModuleInfo ]
111+ modules : Iterable [pkgutil .ModuleInfo ] = self . global_cache
112112 imported_module = sys .modules .get (path .split ('.' )[0 ])
113113 if imported_module :
114- modules = self ._find_already_imported_module_infos (imported_module )
115- else :
116- modules = self .global_cache
114+ # Filter modules to those who name and specs match the
115+ # imported module to avoid invalid suggestions
116+ spec = imported_module .__spec__
117+ if spec :
118+ modules = [mod for mod in modules
119+ if mod .name == spec .name
120+ and mod .module_finder .find_spec (mod .name ) == spec ]
121+ else :
122+ modules = []
117123
118124 is_stdlib_import : bool | None = None
119125 for segment in path .split ('.' ):
@@ -136,32 +142,6 @@ def _is_stdlib_module(self, module_info: pkgutil.ModuleInfo) -> bool:
136142 return (isinstance (module_info .module_finder , FileFinder )
137143 and module_info .module_finder .path == self ._stdlib_path )
138144
139- def _find_already_imported_module_infos (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-
165145 def is_suggestion_match (self , module_name : str , prefix : str ) -> bool :
166146 if prefix :
167147 return module_name .startswith (prefix )
0 commit comments