Last active
May 20, 2026 17:48
-
-
Save DavidCEllis/a8507205c4fac982251981d9a861ec93 to your computer and use it in GitHub Desktop.
Lazy Import Helpers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Tools to help discover and resolve PEP-810 lazy imports | |
| import sys | |
| import types | |
| def get_all_lazy_imports( | |
| *, | |
| exclude_imports: set[tuple[types.ModuleType, str]] | None = None | |
| ) -> list[tuple[types.ModuleType, str]]: | |
| if sys.version_info < (3, 14): | |
| return [] | |
| if exclude_imports is None: | |
| exclude_imports = set() | |
| return [ | |
| (module, name) | |
| for module in sys.modules.values() | |
| for name, obj in module.__dict__.items() | |
| if isinstance(obj, types.LazyImportType) | |
| and (module, name) not in exclude_imports | |
| ] | |
| def resolve_all_lazy_imports() -> list[tuple[types.ModuleType, str, Exception]]: | |
| """ | |
| A rather brute force function that loops over all loaded modules, | |
| checks the module globals for any `LazyImport` objects and resolves | |
| all discovered lazy imports. | |
| This will also resolve lazy imports in new modules imported while | |
| resolving lazy imports. | |
| This returns a list of (module, name, exception) tuples for failed imports. | |
| """ | |
| if sys.version_info < (3, 14): | |
| return | |
| failed_imports = set() | |
| failed_imports_reasons = [] | |
| while pending := get_all_lazy_imports(exclude_imports=failed_imports): | |
| for module, name in pending: | |
| try: | |
| getattr(module, name) | |
| except Exception as e: | |
| failed_imports.add((module, name)) | |
| failed_imports_reasons.append((module, name, e)) | |
| return failed_imports_reasons |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment