Skip to content

Commit 4493399

Browse files
Prevent cache misses in do_import_module() (#2206)
If modname is None (default), it's okay to use the cache; there's no point in recreating the module ad nauseum. Co-authored-by: Leandro T. C. Melo <LTCMELO@GMAIL.COM>
1 parent bb0573d commit 4493399

File tree

2 files changed

+16
-2
lines changed

2 files changed

+16
-2
lines changed

astroid/nodes/_base_nodes.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -130,8 +130,11 @@ def do_import_module(self, modname: str | None = None) -> nodes.Module:
130130
# If the module ImportNode is importing is a module with the same name
131131
# as the file that contains the ImportNode we don't want to use the cache
132132
# to make sure we use the import system to get the correct module.
133-
# pylint: disable-next=no-member # pylint doesn't recognize type of mymodule
134-
if mymodule.relative_to_absolute_name(modname, level) == mymodule.name:
133+
if (
134+
modname
135+
# pylint: disable-next=no-member # pylint doesn't recognize type of mymodule
136+
and mymodule.relative_to_absolute_name(modname, level) == mymodule.name
137+
):
135138
use_cache = False
136139
else:
137140
use_cache = True

tests/test_inference.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
Uninferable,
2323
arguments,
2424
helpers,
25+
manager,
2526
nodes,
2627
objects,
2728
test_utils,
@@ -991,6 +992,16 @@ def test_import_as(self) -> None:
991992
self.assertIsInstance(inferred[0], nodes.FunctionDef)
992993
self.assertEqual(inferred[0].name, "exists")
993994

995+
def test_do_import_module_performance(self) -> None:
996+
import_node = extract_node("import importlib")
997+
import_node.modname = ""
998+
import_node.do_import_module()
999+
# calling file_from_module_name() indicates we didn't hit the cache
1000+
with unittest.mock.patch.object(
1001+
manager.AstroidManager, "file_from_module_name", side_effect=AssertionError
1002+
):
1003+
import_node.do_import_module()
1004+
9941005
def _test_const_inferred(self, node: nodes.AssignName, value: float | str) -> None:
9951006
inferred = list(node.infer())
9961007
self.assertEqual(len(inferred), 1)

0 commit comments

Comments
 (0)