Skip to content

Commit bcbf441

Browse files
Kludexmikeedjones
andauthored
Raise ImportError on circular import (#2040)
Co-authored-by: Michael Jones <[email protected]>
1 parent 495ea74 commit bcbf441

File tree

4 files changed

+19
-1
lines changed

4 files changed

+19
-1
lines changed

tests/importer/circular_import_a.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
# Used by test_importer.py
2+
from .circular_import_b import foo # noqa
3+
4+
bar = 123

tests/importer/circular_import_b.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
# Used by test_importer.py
2+
from .circular_import_a import bar # noqa
3+
4+
foo = 123

tests/importer/test_importer.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,3 +41,13 @@ def test_no_import_needed() -> None:
4141

4242
instance = import_from_string(TemporaryFile)
4343
assert instance == TemporaryFile
44+
45+
46+
def test_circular_import_error() -> None:
47+
with pytest.raises(ImportError) as exc_info:
48+
import_from_string("tests.importer.circular_import_a:bar")
49+
expected = (
50+
"cannot import name 'bar' from partially initialized module "
51+
"'tests.importer.circular_import_a' (most likely due to a circular import)"
52+
)
53+
assert expected in str(exc_info.value)

uvicorn/importer.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ def import_from_string(import_str: Any) -> Any:
1919

2020
try:
2121
module = importlib.import_module(module_str)
22-
except ImportError as exc:
22+
except ModuleNotFoundError as exc:
2323
if exc.name != module_str:
2424
raise exc from None
2525
message = 'Could not import module "{module_str}".'

0 commit comments

Comments
 (0)