summaryrefslogtreecommitdiff
path: root/astroid/manager.py
diff options
context:
space:
mode:
authorTorsten Marek <shlomme@gmail.com>2014-11-15 16:55:39 +0100
committerTorsten Marek <shlomme@gmail.com>2014-11-15 16:55:39 +0100
commit5c7e9667c353ceb1d5e3d1b5982443dd23c19700 (patch)
treeb5c8fdd0598bbc1f908bb487146dc98f97948a50 /astroid/manager.py
parente7a7daf811d3be43bebeec36b1343d66b0f9afb8 (diff)
downloadastroid-5c7e9667c353ceb1d5e3d1b5982443dd23c19700.tar.gz
Generalize hooks for resolving imports that cannot be resolved normally,
and use the functionality in brain/py2gi.
Diffstat (limited to 'astroid/manager.py')
-rw-r--r--astroid/manager.py18
1 files changed, 18 insertions, 0 deletions
diff --git a/astroid/manager.py b/astroid/manager.py
index 2f5b555..1e6d36d 100644
--- a/astroid/manager.py
+++ b/astroid/manager.py
@@ -88,6 +88,7 @@ class AstroidManager(OptionsProviderMixIn):
self.astroid_cache = {}
self._mod_file_cache = {}
self.transforms = collections.defaultdict(list)
+ self._failed_import_hooks = []
def ast_from_file(self, filepath, modname=None, fallback=True, source=False):
"""given a module name, return the astroid object"""
@@ -144,6 +145,13 @@ class AstroidManager(OptionsProviderMixIn):
if filepath is None:
raise AstroidBuildingException("Unable to load module %s" % (modname,))
return self.ast_from_file(filepath, modname, fallback=False)
+ except AstroidBuildingException as e:
+ for hook in self._failed_import_hooks:
+ try:
+ return hook(modname)
+ except AstroidBuildingException:
+ pass
+ raise e
finally:
os.chdir(old_cwd)
@@ -290,6 +298,16 @@ class AstroidManager(OptionsProviderMixIn):
"""Unregister the given transform."""
self.transforms[node_class].remove((transform, predicate))
+ def register_failed_import_hook(self, hook):
+ """"Registers a hook to resolve imports that cannot be found otherwise.
+
+ `hook` must be a function that accepts a single argument `modname` which
+ contains the name of the module or package that could not be imported.
+ If `hook` can resolve the import, must return a node of type `astroid.Module`,
+ otherwise, it must raise `AstroidBuildingException`.
+ """
+ self._failed_import_hooks.append(hook)
+
def transform(self, node):
"""Call matching transforms for the given node if any and return the
transformed node.