hyped.common.lazy_module module¶
This module defines the LazyModule class for lazy loading of module attributes.
The LazyModule class provides a mechanism for lazy loading attributes of a
module. Lazy loading is a design pattern that defers the initialization of an object
until the point at which it is needed, thereby improving startup performance and
reducing memory consumption.
The LazyModule class extends Python’s built-in ModuleType and
overrides methods to handle the deferred import of attributes. This is particularly
useful for modules that contain many submodules or attributes, but where not all of
them are needed immediately.
Key Features: - Lazy Loading: Attributes are loaded only when accessed, rather than at module
import time.
Dynamic Import: Uses
importlibto dynamically import modules when an attribute is accessed.Custom __dir__: Includes lazy-loaded attributes in the list of available attributes.
- Usage Example:
```python import sys from hyped.common.lazy_module import LazyModule
- lazy_imports = {
‘foo’: ‘module_foo’, ‘bar’: ‘module_bar’
}
- lazy_module = LazyModule(
‘lazy_module’, ‘A lazy-loaded module’, ‘/path/to/module.py’, ‘spec’, lazy_imports
)
# Accessing ‘foo’ will trigger the import of ‘module_foo’ foo_value = lazy_module.foo ```
This module is particularly useful for applications where modules have many
dependencies, but not all are needed right away. By using LazyModule,
you can improve performance and resource management.
- class hyped.common.lazy_module.LazyModule(name: str, doc: str, module_file: str, module_spec: str, lazy_imports: dict[str, str] = {}, lazy_modules: dict[str, str] = {})[source]¶
Bases:
ModuleTypeA module type that supports lazy loading of its attributes.
This class allows for lazy loading of submodules or attributes by deferring their import until they are actually accessed. This can help improve startup times and reduce memory usage in cases where not all components of a module are needed immediately.