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:
parent
184d7c7fee
commit
93e46775f0
25
pep-0562.rst
25
pep-0562.rst
|
@ -47,6 +47,31 @@ on module *instances*. For example::
|
||||||
|
|
||||||
from lib import old_function # Works, but emits the warning
|
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
|
There is a related proposal PEP 549 that proposes to support instance
|
||||||
properties for a similar functionality. The difference is this PEP proposes
|
properties for a similar functionality. The difference is this PEP proposes
|
||||||
a faster and simpler mechanism, but provides more basic customization.
|
a faster and simpler mechanism, but provides more basic customization.
|
||||||
|
|
Loading…
Reference in New Issue