Skip to content

[builtins] fix return type of __lazy_import__() to a union - #16748

Open
JadenV15 wants to merge 1 commit into
python:mainfrom
JadenV15:main
Open

JadenV15 wants to merge 1 commit into
python:mainfrom
JadenV15:main

Conversation

@JadenV15

@JadenV15 JadenV15 commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

closes #16747

@JadenV15 JadenV15 changed the title [builtins] fix return type of __lazy_import__() to a union; closes #16747 [builtins] fix return type of __lazy_import__() to a union Nov 9, 2026
@github-actions

Copy link
Copy Markdown
Contributor

According to mypy_primer, this change has no effect on the checked open source code. 🤖🎉

@srittau

srittau commented Nov 10, 2026

Copy link
Copy Markdown
Collaborator

In what situations would it return a module? The PEP only says it return a types.LazyImportType object, and a brief glance on the implementation seems to agree, although I might have overlooked a code path.

@JadenV15

JadenV15 commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor Author

@JelleZijlstra

Copy link
Copy Markdown
Member

Yeah, it can return a regular module if lazy imports are disabled.

More generally, it can return anything at all if you manually put something in sys.modules, or if there's an import hook doing funny things. Therefore, there's an argument that the return type should be object (or Any).

Should we change the return type to object? I can see that going either way, but if you're manually calling __lazy_import__ you're already poking into internals and should be prepared for edge cases, so I'd favor using object to force users calling this function to confront those edge cases.

@JadenV15

Copy link
Copy Markdown
Contributor Author

@JelleZijlstra That's an interesting take.

It reminds me of a quote by wise Tim Peters re metaclasses (see here):

Metaclasses are deeper magic that 99% of users should never worry about it. If you wonder whether you need them, you don't (the people who actually need them know with certainty that they need them, and don't need an explanation about why).

It feels applicable to any "advanced" language feature, really. If you're using __lazy_import__ or other dynamic machinery, we expect that you know exactly why you need it and how to use it. We're not hand-holding here; you should be the one to RTFM.

I guess I disagree with you then, because the people using __lazy_import__ should be aware of the edge cases (either because they're the ones intentionally introducing them, or because they've read the warning on the docs (not up yet)) and shouldn't need a VS Code annotation popup to teach them that.

This branch has not been deployed

No deployments
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.

Fix return type of __lazy_import__() (again)

3 participants