Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Raise ImportError on circular import #2040

Merged
merged 1 commit into from
Jul 9, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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