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

Clean sys.modules if TYPE_CHECKING=True import fails #11645

Merged
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
8 changes: 7 additions & 1 deletion sphinx/ext/autodoc/importer.py
Expand Up @@ -3,6 +3,7 @@
from __future__ import annotations

import importlib
import sys
import traceback
import typing
from typing import TYPE_CHECKING, Any, Callable, NamedTuple
Expand Down Expand Up @@ -82,13 +83,18 @@ def import_object(modname: str, objpath: list[str], objtype: str = '',
objpath = list(objpath)
while module is None:
try:
orig_modules = frozenset(sys.modules)
try:
# try importing with ``typing.TYPE_CHECKING == True``
typing.TYPE_CHECKING = True
module = import_module(modname, warningiserror=warningiserror)
except ImportError:
# if that fails (e.g. circular import), retry with
# ``typing.TYPE_CHECKING == False``
# ``typing.TYPE_CHECKING == False`` after reverting
# changes made to ``sys.modules`` by the failed try
for m in [m for m in sys.modules if m not in orig_modules]:
sys.modules.pop(m)

typing.TYPE_CHECKING = False
module = import_module(modname, warningiserror=warningiserror)
finally:
Expand Down
1 change: 1 addition & 0 deletions tests/roots/test-ext-autodoc/circular_import/__init__.py
@@ -0,0 +1 @@
from circular_import.c import SomeClass
1 change: 1 addition & 0 deletions tests/roots/test-ext-autodoc/circular_import/a.py
@@ -0,0 +1 @@
X = 42
4 changes: 4 additions & 0 deletions tests/roots/test-ext-autodoc/circular_import/b.py
@@ -0,0 +1,4 @@
import typing

if typing.TYPE_CHECKING:
from circular_import import SomeClass
6 changes: 6 additions & 0 deletions tests/roots/test-ext-autodoc/circular_import/c.py
@@ -0,0 +1,6 @@
import circular_import.a
import circular_import.b


class SomeClass:
X = circular_import.a.X
13 changes: 13 additions & 0 deletions tests/test_ext_autodoc.py
Expand Up @@ -2024,6 +2024,19 @@ def test_autodoc_TYPE_CHECKING(app):
]


@pytest.mark.sphinx('html', testroot='ext-autodoc')
def test_autodoc_TYPE_CHECKING_circular_import(app):
options = {"members": None,
"undoc-members": None}
actual = do_autodoc(app, 'module', 'circular_import', options)
assert list(actual) == [
'',
'.. py:module:: circular_import',
'',
]
assert sys.modules["circular_import"].a is sys.modules["circular_import.a"]


@pytest.mark.sphinx('html', testroot='ext-autodoc')
def test_singledispatch(app):
options = {"members": None}
Expand Down