Skip to content

gh-161708: Document the __lazy_import__ built-in function - #161762

Open
RoryGlenn wants to merge 4 commits into
python:mainfrom
RoryGlenn:gh-161708-document-lazy-import
Open

RoryGlenn wants to merge 4 commits into
python:mainfrom
RoryGlenn:gh-161708-document-lazy-import

Conversation

@RoryGlenn

@RoryGlenn RoryGlenn commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

Document __lazy_import__ for programmatic lazy imports at module scope, including its arguments, namespace requirements, lazy proxy behavior and eager fallback. Link the entry from the language reference and built-in functions table.

Use a direct function reference in the table, widen its fourth column and remove the obsolete lazy-import substitution. Preserve the local type links and describe the eager result as __import__ would return it.

Sphinx lint, a fresh HTML build with warnings treated as errors, and rendered wording/table/link checks passed. Runtime tests were not run for this documentation-only change.

Related PR #161716 covers the C docstring; this PR covers the reference documentation.

Prepared with OpenAI Codex assistance.

Validation

  • GIT_NO_LAZY_FETCH=1 git --no-optional-locks diff --check 039658b302bb0bf4caca95671cc8008741d466de HEAD -- Doc/builtins/functions.rst — exit 0
  • /cache/cpython-pr-161762-docs/bin/sphinx-lint --enable=default-role Doc/builtins/functions.rst Doc/reference/simple_stmts.rst — exit 0
  • make -C Doc html VENVDIR=/cache/cpython-pr-161762-docs JOBS=4 SPHINXOPTS='--fresh-env --write-all' — exit 0
  • `python3 -B - <<'PY'
    import html
    from pathlib import Path
    import re

root = Path('Doc/build/html')
functions_path = root / 'builtins/functions.html'
reference_path = root / 'reference/simple_stmts.html'
functions = functions_path.read_text(encoding='utf-8')
reference = reference_path.read_text(encoding='utf-8')
for anchor in ('func-lazy-import', 'lazy_import__'):
assert functions.count(f'id="{anchor}"') == 1, anchor

table = re.search(r'<table\b.?', functions, re.DOTALL).group()
cells = re.findall(r'<td\b.
?', table, re.DOTALL)
assert len(cells) == 4
assert 'href="#lazy_import__"' in cells[3]
assert 'href="#func-lazy-import"' not in table
last_column = html.unescape(re.sub(r'<[^>]*>', '', cells[3]))
assert last_column.index('import()') < last_column.index('lazy_import()')
for anchor in re.findall(r'href="#([^"]+)"', table):
assert functions.count(f'id="{anchor}"') == 1, anchor
for anchor in ('func-dict', 'func-list', 'func-range'):
assert f'href="#{anchor}"' in table, anchor

section = functions.split('id="lazy_import__"', 1)[1].split('', 1)[0]
visible = ' '.join(html.unescape(re.sub(r'<[^>]>', '', section)).split())
for wording in (
'Use this function for programmatic lazy imports.',
'Otherwise, use a lazy import statement.',
'The function must be called at module scope.',
'Calling it from a function or class body raises SyntaxError.',
'dictionary containing a builtins entry.',
'If locals is omitted or None, it defaults to globals.',
'result as import() would do.',
):
assert wording in visible, wording
assert 'normally a types.ModuleType instance' not in visible
assert 'Use a substitution because' not in html.unescape(re.sub(r'<[^>]
>', '', functions))
assert 'id="lazy-imports"' in reference
for origin, href in (
(functions_path, '../reference/simple_stmts.html#lazy-imports'),
(functions_path, '../library/types.html#types.LazyImportType'),
(functions_path, '../library/sys.html#sys.set_lazy_imports_filter'),
(reference_path, '../builtins/functions.html#lazy_import__'),
):
assert f'href="{href}"' in origin.read_text(encoding='utf-8'), href
target, anchor = href.split('#', 1)
assert (origin.parent / target).read_text(encoding='utf-8').count(f'id="{anchor}"') == 1, href
print('Rendered wording, table, anchors and links passed')
PY` — exit 0

  • `python3 -B - <<'PY'
    import html
    from pathlib import Path
    import re

root = Path('Doc/build/html')
functions_path = root / 'builtins/functions.html'
reference_path = root / 'reference/simple_stmts.html'
functions = functions_path.read_text(encoding='utf-8')
reference = reference_path.read_text(encoding='utf-8')
for anchor in ('func-lazy-import', 'lazy_import__'):
assert functions.count(f'id="{anchor}"') == 1, anchor

table = re.search(r'<table\b.?', functions, re.DOTALL).group()
cells = re.findall(r'<td\b.
?', table, re.DOTALL)
assert len(cells) == 4
assert 'href="#lazy_import__"' in cells[3]
assert 'href="#func-lazy-import"' not in table
last_column = html.unescape(re.sub(r'<[^>]*>', '', cells[3]))
assert last_column.index('import()') < last_column.index('lazy_import()')
for anchor in re.findall(r'href="#([^"]+)"', table):
assert functions.count(f'id="{anchor}"') == 1, anchor
for anchor in ('func-dict', 'func-list', 'func-range'):
assert f'href="#{anchor}"' in table, anchor

section = functions.split('id="lazy_import__"', 1)[1].split('', 1)[0]
visible = ' '.join(html.unescape(re.sub(r'<[^>]>', '', section)).split())
for wording in (
'Use this function for programmatic lazy imports.',
'Otherwise, use a lazy import statement.',
'The function must be called at module scope.',
'Calling it from a function or class body raises SyntaxError.',
'dictionary containing a builtins entry.',
'If locals is omitted or None, it defaults to globals.',
'result as import() would do.',
):
assert wording in visible, wording
assert 'normally a types.ModuleType instance' not in visible
assert 'Use a substitution because' not in html.unescape(re.sub(r'<[^>]
>', '', functions))
assert 'id="lazy-imports"' in reference
for origin, href in (
(functions_path, '../reference/simple_stmts.html#lazy-imports'),
(functions_path, '../library/types.html#types.LazyImportType'),
(functions_path, '../library/sys.html#sys.set_lazy_imports_filter'),
(reference_path, '../builtins/functions.html#lazy_import__'),
):
assert f'href="{href}"' in origin.read_text(encoding='utf-8'), href
target, anchor = href.split('#', 1)
assert (origin.parent / target).read_text(encoding='utf-8').count(f'id="{anchor}"') == 1, href
print('PASS: direct function link, four-column table, all local table links, retained anchors and namespace guidance, eager-result wording and language-reference links')
PY` — exit 0

Prepared with AI assistance (Codex gpt-6.1-sol). Independent automated review and verification passed for source tree f7aa0e966cb039f01b1880a5b7bd34efcabed90f. This is automated review. Upstream CI is pending until GitHub reports its result.

@bedevere-app bedevere-app Bot added docs Documentation in the Doc dir skip news labels Nov 10, 2026
@github-project-automation github-project-automation Bot moved this to Todo in Docs PRs Nov 10, 2026
@read-the-docs-community

read-the-docs-community Bot commented Nov 10, 2026 •

Copy link
Copy Markdown

Documentation build overview

📚 cpython-previews | 🛠️ Build #35872802 | 📁 Comparing da4ac43 against main (2f0e294)

  🔍 Preview build  

49 files changed · ± 49 modified

± Modified

Comment thread Doc/builtins/functions.rst Resolved
Signed-off-by: Rory Glenn <glennrory@gmail.com>
@RoryGlenn

Copy link
Copy Markdown
Contributor Author

Automated contribution follow-up (Codex):

Separated func-lazy-import from the preceding substitution group and added its own source comment explaining the table width and the trailing _ link to the existing target. The generated table and anchors are unchanged; the fresh HTML build and Sphinx lint pass.

@RoryGlenn
RoryGlenn marked this pull request as ready for review November 11, 2026 18:37
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-11T18:40:05.190981Z 4d01f7f Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

Comment thread Doc/builtins/functions.rst Resolved
Comment thread Doc/builtins/functions.rst Resolved
@JadenV15

JadenV15 commented Nov 13, 2026 •

Copy link
Copy Markdown

Something else before we merge: currently importlib.__import__ is marked as discouraged in favour of import_module:

Note Programmatic importing of modules should use import_module() instead of this function.

Should we explicitly say that __lazy_import__ isn't discouraged and is the recommended way? AFAIK there is no importlib.lazy_import_module.

Signed-off-by: Rory Glenn <glennrory@gmail.com>
@RoryGlenn

Copy link
Copy Markdown
Contributor Author

Updated in 039658b to explicitly recommend __lazy_import__ for programmatic lazy imports. The entry also keeps the module-scope restriction and points to the lazy import statement for other uses.

Comment thread Doc/builtins/functions.rst Resolved
Comment thread Doc/builtins/functions.rst Resolved
Comment thread Doc/builtins/functions.rst Resolved
Comment thread Doc/builtins/functions.rst Resolved
Signed-off-by: Rory Glenn <glennrory@gmail.com>
@RoryGlenn

Copy link
Copy Markdown
Contributor Author

Automated contribution follow-up (Codex):

Updated the table to use the function role, widened its fourth column and removed the lazy-import substitution and comment. Both published function anchors remain available.

The older type-substitution comment remains relevant: those substitutions keep entries such as dict, list and range linked to this page's explicit targets, whose descriptions use noindex.

Adopted the suggested eager-result wording. The false-filter branch calls the same eager-import helper as import.

Kept the explicit namespace description after checking the source: lazy_import defaults locals to globals and requires a dictionary with an existing builtins entry. exec can inherit frame locals, accepts frozendict globals, and supplies missing builtins for dictionary globals.

Sphinx lint, fresh HTML and rendered table/link checks passed. Prepared with OpenAI Codex assistance.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

awaiting review docs Documentation in the Doc dir skip news

Projects

Status: Todo

Development

Successfully merging this pull request may close these issues.

4 participants