python / python/cpython

Names that have been resolved are not consistently removed from sys.lazy_modules

Open
#155,695 11 comments 0 reactions 1 assignee View on GitHub

@johnslavik is already working on this.

Since Sep 11, 2026.

interpreter-core topic-lazy-imports type-bug
Dominant language
Python
Stars
77.2k
Forks
35.9k
PR merge metrics
PR metrics pending

Description

Bug report

Bug description:

I'm slightly hesitant to raise this because there's still discussion over what sys.lazy_modules should be. The documentation for sys.lazy_modules currently states:

When a lazily imported module is accessed for the first time, its name is removed from this set.

In at least two cases I'm aware of names are not being removed. Names may also not be modules, but I'd consider that a documentation issue while I believe the failure to remove names is a bug.


Names of modules that have previously been resolved will be re-added, but not removed when resolved again.

import sys
mods = sys.lazy_modules.copy()
def get_lazy():
    return sorted(sys.lazy_modules - mods)

lazy import x  # added
print(get_lazy())
x  # removed
print(get_lazy())
lazy import x  # added again
x  # not removed
print(get_lazy())
['x']
[]
['x']

Here I think the issue is adding x back to sys.lazy_modules when it's already in sys.modules.


Names that are not modules are not removed:

import sys
mods = sys.lazy_modules.copy()
def get_lazy():
    return sorted(sys.lazy_modules - mods)

lazy from x import X
print(get_lazy())
X
print(get_lazy())  # Should be empty
['x', 'x.X']
['x.X']
CPython versions tested on:

3.15, CPython main branch

Operating systems tested on:

No response

Linked PRs
  • gh-157714

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.