-
-
Notifications
You must be signed in to change notification settings - Fork 2.2k
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
Sphinx 7.2 autodoc fails to import some modules that use typing.TYPE_CHECKING
#11642
Comments
Hi Matt, thanks for the detailed report! Would you consider opening a PR with your suggested fix please? It seems reasonable to me. A |
This is probably crazy, but since I've had the idea I might as well suggest it: another option might be importing the module twice, first with |
I haven't looked into how A |
IIRC, one issue with the reload is that it re-executes the module. In particular if you patched the module using an extension I am not entirely sure that the module will be patched again. |
Closed in #11645 |
Describe the bug
Sphinx 7.2's autodoc sets
typing.TYPE_CHECKING = True
before importing a module. If that fails, it setstyping.TYPE_CHECKING = False
and retries. It's possible for the first failing import to leave things in a state where the second import won't succeed.How to Reproduce
With a virtualenv with Sphinx installed activated, run:
You'll see that the last command fails if Sphinx >7.2 is installed, and succeeds if Sphinx 7.1 is installed.
Environment Information
Sphinx extensions
`sphinx.ext.autodoc`
Additional context
Obviously the minimal reproducer above is pretty contrived, but it's representative of a real error that we saw inside an actual code base.
For the reproducer above, the issue boils down to this: after the first import with
typing.TYPE_CHECKING = True
,sys.modules
has a"package.a"
key but not a"package"
key. When we do the second import withtyping.TYPE_CHECKING = False
, theimport package.a
statement returns the module associated with the"package.a"
key insys.modules
, but doesn't assignsys.modules["package"].a = sys.modules["package.a"]
like an import ordinarily would, because it believes the module has already been successfully imported. Because of that, the later attribute access ofsys.modules["package"].a
fails.I think the sanest thing to do might be to save a shallow copy of
sys.modules
before trying the import withtyping.TYPE_CHECKING = True
and, if that import fails, restore the oldsys.modules
before retrying withtyping.TYPE_CHECKING = False
. I don't think side effects from the failingTYPE_CHECKING = True
import should be visible to the second import attempt.The text was updated successfully, but these errors were encountered: