2626import sys
2727import warnings
2828from pathlib import Path
29- from typing import Optional , Set , Generator , Tuple , List
29+ from typing import Optional , Set , Generator , Tuple , Sequence , Iterable , Union
3030
3131from .line import (
3232 current_word ,
4949
5050
5151class ModuleGatherer :
52- def __init__ (self , path : Optional [Path ] = None , skiplist = None ) -> None :
53- # The cached list of all known modules
52+ def __init__ (
53+ self ,
54+ paths : Optional [Iterable [Union [str , Path ]]] = None ,
55+ skiplist : Optional [Sequence [str ]] = None ,
56+ ) -> None :
57+ """Initialize module gatherer with all modules in `paths`, which should be a list of
58+ directory names. If `paths` is not given, `sys.path` will be used."""
59+
60+ # Cached list of all known modules
5461 self .modules : Set [str ] = set ()
55- # List of (st_dev, st_ino) to compare against so that paths are not repeated
62+ # Set of (st_dev, st_ino) to compare against so that paths are not repeated
5663 self .paths : Set [Tuple [int , int ]] = set ()
5764 # Patterns to skip
58- self .skiplist = skiplist if skiplist is not None else tuple ()
65+ self .skiplist : Sequence [str ] = (
66+ skiplist if skiplist is not None else tuple ()
67+ )
5968 self .fully_loaded = False
60- self .find_iterator = self .find_all_modules (path )
69+
70+ if paths is None :
71+ self .modules .update (sys .builtin_module_names )
72+ paths = sys .path
73+
74+ self .find_iterator = self .find_all_modules (
75+ (Path (p ).resolve () if p else Path .cwd () for p in sys .path )
76+ )
6177
6278 def module_matches (self , cw : str , prefix : str = "" ) -> Set [str ]:
6379 """Modules names to replace cw with"""
@@ -191,8 +207,7 @@ def find_modules(self, path: Path) -> Generator[str, None, None]:
191207 except (ImportError , OSError , SyntaxError ):
192208 continue
193209 except UnicodeEncodeError :
194- # Happens with Python 3 when there is a filename in some
195- # invalid encoding
210+ # Happens with Python 3 when there is a filename in some invalid encoding
196211 continue
197212 else :
198213 if is_package :
@@ -205,16 +220,13 @@ def find_modules(self, path: Path) -> Generator[str, None, None]:
205220 yield f"{ name } .{ subname } "
206221 yield name
207222
208- def find_all_modules (self , path = None ):
223+ def find_all_modules (
224+ self , paths : Iterable [Path ]
225+ ) -> Generator [None , None , None ]:
209226 """Return a list with all modules in `path`, which should be a list of
210227 directory names. If path is not given, sys.path will be used."""
211228
212- if path is None :
213- self .modules .update (sys .builtin_module_names )
214- path = sys .path
215-
216- for p in path :
217- p = Path (p ).resolve () if p else Path .cwd ()
229+ for p in paths :
218230 for module in self .find_modules (p ):
219231 self .modules .add (module )
220232 yield
0 commit comments