Skip to content

Commit

Permalink
Add deny list for modules to be skipped on AST generation (#2399)
Browse files Browse the repository at this point in the history
  • Loading branch information
Jamie- authored Mar 25, 2024
1 parent 4a094d7 commit a2921b3
Show file tree
Hide file tree
Showing 4 changed files with 18 additions and 0 deletions.
6 changes: 6 additions & 0 deletions ChangeLog
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,12 @@ Release date: TBA
Closes #1015
Refs pylint-dev/pylint#4696

* Adds ``module_denylist`` to ``AstroidManager`` for modules to be skipped during AST
generation. Modules in this list will cause an ``AstroidImportError`` to be raised
when an AST for them is requested.

Refs pylint-dev/pylint#9442


What's New in astroid 3.1.1?
============================
Expand Down
4 changes: 4 additions & 0 deletions astroid/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ class AstroidManager:
"optimize_ast": False,
"max_inferable_values": 100,
"extension_package_whitelist": set(),
"module_denylist": set(),
"_transform": TransformVisitor(),
}

Expand All @@ -70,6 +71,7 @@ def __init__(self) -> None:
self.extension_package_whitelist = AstroidManager.brain[
"extension_package_whitelist"
]
self.module_denylist = AstroidManager.brain["module_denylist"]
self._transform = AstroidManager.brain["_transform"]

@property
Expand Down Expand Up @@ -200,6 +202,8 @@ def ast_from_module_name( # noqa: C901
# importing a module with the same name as the file that is importing
# we want to fallback on the import system to make sure we get the correct
# module.
if modname in self.module_denylist:
raise AstroidImportError(f"Skipping ignored module {modname!r}")
if modname in self.astroid_cache and use_cache:
return self.astroid_cache[modname]
if modname == "__main__":
Expand Down
1 change: 1 addition & 0 deletions astroid/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,4 +74,5 @@ def brainless_manager():
m._mod_file_cache = {}
m._transform = transforms.TransformVisitor()
m.extension_package_whitelist = set()
m.module_denylist = set()
return m
7 changes: 7 additions & 0 deletions tests/test_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -383,6 +383,13 @@ def test_raises_exception_for_empty_modname(self) -> None:
with pytest.raises(AstroidBuildingError):
self.manager.ast_from_module_name(None)

def test_denied_modules_raise(self) -> None:
self.manager.module_denylist.add("random")
with pytest.raises(AstroidImportError, match="random"):
self.manager.ast_from_module_name("random")
# and module not in the deny list shouldn't raise
self.manager.ast_from_module_name("math")


class IsolatedAstroidManagerTest(resources.AstroidCacheSetupMixin, unittest.TestCase):
def test_no_user_warning(self):
Expand Down

0 comments on commit a2921b3

Please sign in to comment.