10000 Fix viewcode extension importing modules more than once by djhoese · Pull Request #13380 · sphinx-doc/sphinx · GitHub
[go: up one dir, main page]

Skip to content

Fix viewcode extension importing modules more than once #13380

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

Merged
merged 6 commits into from
Feb 21, 2025

Conversation

djhoese
Copy link
Contributor
@djhoese djhoese commented Feb 21, 2025

Purpose

This PR fixes the viewcode extension improperly importing modules to compute the full module name. This results in modules being imported more than once and increase memory usage and execution time. The primary issue was modules being imported/executed but not added to sys.modules to be reused.

This PR reverts some of the changes in #13195 to use importlib.import_module again to handle the complexity of importing modules and "caching" them in sys.modules to be reused. It does not break the feature added to #13195 of importing a module "alias" import. That is, accessing an imported module as another module's attribute (see #13195 and #13370 for details).

References

@AA-Turner AA-Turner merged commit 8ef0708 into sphinx-doc:master Feb 21, 2025
22 of 23 checks passed
Comment on lines +71 to +75
except BaseException as exc:
# Importing modules may cause any side effects, including
# SystemExit, so we need to catch all errors.
msg = f"viewcode failed to import '{mod_root}'."
raise ImportError(msg) from exc
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@AA-Turner There is an outer except Exception, does that count?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This has been wrong for a while, simple counterexample:

import sys
try:
    sys.exit()
except Exception:
    print('caught')

@AA-Turner
Copy link
Member

Thanks @djhoese!

A

@AA-Turner AA-Turner added this to the 8.2.x milestone Feb 23, 2025
@github-actions github-actions bot locked as resolved and limited conversation to collaborators Mar 24, 2025
@djhoese djhoese deleted the bugfix-viewcode-import-once branch July 2, 2025 18:08
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Sphinx 8.2.0 uses significantly more memory than 8.1.x
2 participants
0