Skip to content

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