Skip to content

chore: add lazy imports to the pybind11 package - #6338

Open
henryiii wants to merge 2 commits into
pybind:masterfrom
henryiii:henryiii/chore/lazy-imports
Open

henryiii wants to merge 2 commits into
pybind:masterfrom
henryiii:henryiii/chore/lazy-imports

Conversation

@henryiii

@henryiii henryiii commented Dec 3, 2026 •

Copy link
Copy Markdown
Collaborator

Adding lazy imports. This was made will fully local AI and the flake8-lazy skill. :)

🤖 Human guided, AI assisted PR (using this skill). AI text below. 🤖

Description

Adopt flake8-lazy as a pre-commit
hook and apply it to the pybind11 package. This adds __lazy_modules__
(PEP 810) declarations that defer module-level imports used only inside
functions — _version, commands, and several stdlib modules in
__main__.py and setup_helpers.py — cutting import-time overhead.

  • setuptools/distutils are excluded from lazy recommendations via
    --lazy-exclude-modules, because setuptools monkeypatches distutils and a
    lazy import of a monkeypatched module is unsafe.
  • The __main__.py imports of _version/commands are made absolute so the
    generated declarations are absolute module names; a __spec__.parent
    reference would not type-check under mypy (__spec__ is
    Optional[ModuleSpec]).

Suggested changelog entry:

  • Added lazy imports (PEP 810) to the pybind11 package via flake8-lazy,
    deferring imports only used inside functions to cut import-time overhead.

Assisted-by: OpenCode:qwen3.8:27b-mlx

Adopt flake8-lazy as a pre-commit hook so `__lazy_modules__` declarations
stay correct over time, and apply it to the `pybind11` package. This defers
module-level imports that are only used inside functions (`_version`,
`commands`, and several stdlib modules in `__main__.py` and
`setup_helpers.py`), cutting import-time overhead.

setuptools and distutils are excluded from lazy recommendations: setuptools
monkeypatches distutils, so a lazy import of a monkeypatched module is
unsafe, and their submodules stay eager.

The `__main__.py` imports of `_version` and `commands` are made absolute so
the generated `__lazy_modules__` entries are absolute module names; a
`__spec__.parent` reference would not type-check under mypy because
`__spec__` is `Optional[ModuleSpec]`.

Assisted-by: OpenCode:qwen3.8:27b-mlx
Comment thread .pre-commit-config.yaml Resolved

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.

1 participant