Skip to content

Commit

Permalink
Raise ImportError on circular import (#2040)
Browse files Browse the repository at this point in the history
Co-authored-by: Michael Jones <4087139+mikeedjones@users.noreply.github.com>
  • Loading branch information
Kludex and mikeedjones authored Jul 9, 2023
1 parent 495ea74 commit bcbf441
Show file tree
Hide file tree
Showing 4 changed files with 19 additions and 1 deletion.
4 changes: 4 additions & 0 deletions tests/importer/circular_import_a.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# Used by test_importer.py
from .circular_import_b import foo # noqa

bar = 123
4 changes: 4 additions & 0 deletions tests/importer/circular_import_b.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# Used by test_importer.py
from .circular_import_a import bar # noqa

foo = 123
10 changes: 10 additions & 0 deletions tests/importer/test_importer.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,3 +41,13 @@ def test_no_import_needed() -> None:

instance = import_from_string(TemporaryFile)
assert instance == TemporaryFile


def test_circular_import_error() -> None:
with pytest.raises(ImportError) as exc_info:
import_from_string("tests.importer.circular_import_a:bar")
expected = (
"cannot import name 'bar' from partially initialized module "
"'tests.importer.circular_import_a' (most likely due to a circular import)"
)
assert expected in str(exc_info.value)
2 changes: 1 addition & 1 deletion uvicorn/importer.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ def import_from_string(import_str: Any) -> Any:

try:
module = importlib.import_module(module_str)
except ImportError as exc:
except ModuleNotFoundError as exc:
if exc.name != module_str:
raise exc from None
message = 'Could not import module "{module_str}".'
Expand Down

0 comments on commit bcbf441

Please sign in to comment.