Update PEP 562 with an example (#418)

This adds an example of module __getattr__ usage that implements lazy imports to Rationale of PEP 562.
This commit is contained in:
Ivan Levkivskyi 2017-09-13 01:20:27 +02:00 committed by Guido van Rossum
parent 184d7c7fee
commit 93e46775f0
1 changed files with 25 additions and 0 deletions

View File

@ -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.