Skip to content

Fix loader handling of sys.modules #68284

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

Open
wants to merge 2 commits into
base: 3007.x
Choose a base branch
from

Conversation

lkubb
Copy link
Contributor

@lkubb lkubb commented Aug 23, 2025

What does this PR do?

Makes the LazyLoader reload already loaded modules instead of replacing them.

What issues does this PR fix or reference?

Fixes: #68281

Previous Behavior

Since e579012 (#65032), a new loader always created new modules and overwrote existing ones in sys.modules.
This could cause unexpected behavior because parts of the loader code assumed that a cached function in their _dict always belongs to the corresponding module in sys.modules (details: #68281 (comment))

New Behavior

Modules are reloaded instead of replaced when possible, which aligns with the behavior in 3006.x (I think, please feel free to correct me and let's see what the test suite says).

Merge requirements satisfied?

Commits signed with GPG?

Yes

Commit e579012
migrated away from the deprecated `load_module` to `exec_module`.
The latter does not reload modules like the deprecated function.

Since the loader assumes modules in `sys.modules` are never replaced, but
reloaded, ensure that's the case. There are likely better solutions in
theory, but this commit quickly reverts to the legacy behavior the
loader is used to.

If we replace modules instead, a mismatch between the cached functions
in a LazyLoader instance and the ones found on modules in `sys.modules`
can develop when we instantiate nested loaders of the same type and
load the same module with both.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant