Skip to content

Commit

Permalink
Optimize exception handling in import_module() (#2224)
Browse files Browse the repository at this point in the history
Pass `use_cache` value to ast_from_module_name()
  • Loading branch information
jacobtylerwalls authored Jun 27, 2023
1 parent d4f4452 commit 2f8b636
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 2 deletions.
6 changes: 5 additions & 1 deletion astroid/nodes/scoped_nodes/scoped_nodes.py
Original file line number Diff line number Diff line change
Expand Up @@ -445,7 +445,11 @@ def import_module(
# skip here
if relative_only:
raise
return AstroidManager().ast_from_module_name(modname)
# Don't repeat the same operation, e.g. for missing modules
# like "_winapi" or "nt" on POSIX systems.
if modname == absmodname:
raise
return AstroidManager().ast_from_module_name(modname, use_cache=use_cache)

def relative_to_absolute_name(self, modname: str, level: int | None) -> str:
"""Get the absolute module name for a relative import.
Expand Down
17 changes: 16 additions & 1 deletion tests/test_scoped_nodes.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
import unittest
from functools import partial
from typing import Any
from unittest.mock import patch

import pytest

Expand All @@ -29,8 +30,9 @@
util,
)
from astroid.bases import BoundMethod, Generator, Instance, UnboundMethod
from astroid.const import IS_PYPY, PY38
from astroid.const import IS_PYPY, PY38, WIN32
from astroid.exceptions import (
AstroidBuildingError,
AttributeInferenceError,
DuplicateBasesError,
InconsistentMroError,
Expand Down Expand Up @@ -244,6 +246,19 @@ def test_import_2(self) -> None:
finally:
del sys.path[0]

@patch(
"astroid.nodes.scoped_nodes.scoped_nodes.AstroidManager.ast_from_module_name"
)
def test_import_unavailable_module(self, mock) -> None:
unavailable_modname = "posixpath" if WIN32 else "ntpath"
module = builder.parse(f"import {unavailable_modname}")
mock.side_effect = AstroidBuildingError

with pytest.raises(AstroidBuildingError):
module.import_module(unavailable_modname)

mock.assert_called_once()

def test_file_stream_in_memory(self) -> None:
data = """irrelevant_variable is irrelevant"""
astroid = builder.parse(data, "in_memory")
Expand Down

0 comments on commit 2f8b636

Please sign in to comment.