Skip to main content
Version: 1.2.2

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

ArgumentTypeRequired
Description
moduleModuleTypeThe lazy module where the attribute will be accessed.
attrstrThe attribute name used for locating the attribute.
parentstrThe name of the parent module where the attribute will be attached.

Returns

ArgumentType
Description
attrAny | NoneA 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

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)