diff --git a/pep-0562.rst b/pep-0562.rst index d16f3b6eb67..93f35038742 100644 --- a/pep-0562.rst +++ b/pep-0562.rst @@ -47,6 +47,31 @@ on module *instances*. For example:: from lib import old_function # Works, but emits the warning +Another widespread use case for ``__getattr__`` would be lazy submodule +imports. Consider a simple example:: + + # lib/__init__.py + + import importlib + + __all__ = ['submod', ...] + + def __getattr__(name): + if name in __all__: + return importlib.import_module("." + name, __name__) + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") + + # lib/submod.py + + print("Submodule loaded") + class HeavyClass: + ... + + # main.py + + import lib + lib.submodule.HeavyClass # prints "Submodule loaded" + There is a related proposal PEP 549 that proposes to support instance properties for a similar functionality. The difference is this PEP proposes a faster and simpler mechanism, but provides more basic customization.