get_lazy_attribute
FunctionPrivateSource
attr: Any | None = get_lazy_attribute(
module: ModuleType, attr: str, parent: str
)
Get an attribute of a lazy module. This attribute will not be loaded if it is not accessed.
If the provided module is invalid, will return None.
danger
Note that the attribute returned by this function needs to be a callable one. To be specific, this function is mainly designed for getting a lazy-loaded class from a lazy-loaded module.
Arguments
Requires
| Argument | Type | Required | |
|---|---|---|---|
module | ModuleType | The lazy module where the attribute will be accessed. | |
attr | str | The attribute name used for locating the attribute. | |
parent | str | The name of the parent module where the attribute will be attached. |
Returns
| Argument | Type | |
|---|---|---|
attr | Any | None | A lazy callable attribute. If it is not called, the attribtue will not be loaded. If the attribute cannot be located, return None. |
Example
Load a class only when it is accessed
- Codes
- Results
lazy_load_a_class.py
from typing import TYPE_CHECKING
from syncstream import utils
if TYPE_CHECKING:
import html
import html.parser as hparser
from html.parser import HTMLParser
else:
html = utils.lazy_import("html", package=None)
hparser = utils.lazy_import("parser", package="html", dependencies=("html",))
HTMLParser = utils.get_lazy_attribute(hparser, "HTMLParser", __name__)
print(html, hparser)
print(HTMLParser)
print(html, hparser)
print(HTMLParser())
print(html, hparser)
<LazyModule html from "/usr/local/lib/python3.12/html/__init__.py"> <LazyModule html.parser from "/usr/local/lib/python3.12/html/parser.py">
<LazyAttribute HTMLParser from "html.parser">
<LazyModule html from "/usr/local/lib/python3.12/html/__init__.py"> <LazyModule html.parser from "/usr/local/lib/python3.12/html/parser.py">
<html.parser.HTMLParser object at 0x7f4416dfb380>
<module 'html' from '/usr/local/lib/python3.12/html/__init__.py'> <module 'html.parser' from '/usr/local/lib/python3.12/html/parser.py'>