MCPcopy Index your code
hub / github.com/ipython/ipython / try_import

Function try_import

IPython/core/completerlib.py:178–208  ·  view source on GitHub ↗

Try to import given module and return list of potential completions.

(mod: str, only_modules=False)

Source from the content-addressed store, hash-verified

176
177
178def try_import(mod: str, only_modules=False) -> List[str]:
179 """
180 Try to import given module and return list of potential completions.
181 """
182 mod = mod.rstrip('.')
183 try:
184 m = import_module(mod)
185 except:
186 return []
187
188 m_is_init = '__init__' in (getattr(m, '__file__', '') or '')
189
190 completions = []
191 if (not hasattr(m, '__file__')) or (not only_modules) or m_is_init:
192 completions.extend( [attr for attr in dir(m) if
193 is_importable(m, attr, only_modules)])
194
195 m_all = getattr(m, "__all__", [])
196 if only_modules:
197 completions.extend(attr for attr in m_all if is_possible_submodule(m, attr))
198 else:
199 completions.extend(m_all)
200
201 if m_is_init:
202 file_ = m.__file__
203 file_path = os.path.dirname(file_) # type: ignore
204 if file_path is not None:
205 completions.extend(module_list(file_path))
206 completions_set = {c for c in completions if isinstance(c, str)}
207 completions_set.discard('__init__')
208 return list(completions_set)
209
210
211#-----------------------------------------------------------------------------

Callers 3

test_tryimportMethod · 0.90
test_module_without_initFunction · 0.90
module_completionFunction · 0.85

Calls 3

is_importableFunction · 0.85
is_possible_submoduleFunction · 0.85
module_listFunction · 0.85

Tested by 2

test_tryimportMethod · 0.72
test_module_without_initFunction · 0.72

Used in the wild real call sites across dependent graphs

searching dependent graphs…