Skip to content

Commit 93e4677

Browse files
ilevkivskyigvanrossum
authored andcommitted
Update PEP 562 with an example (#418)
This adds an example of module __getattr__ usage that implements lazy imports to Rationale of PEP 562.
1 parent 184d7c7 commit 93e4677

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

pep-0562.rst

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,31 @@ on module *instances*. For example::
4747

4848
from lib import old_function # Works, but emits the warning
4949

50+
Another widespread use case for ``__getattr__`` would be lazy submodule
51+
imports. Consider a simple example::
52+
53+
# lib/__init__.py
54+
55+
import importlib
56+
57+
__all__ = ['submod', ...]
58+
59+
def __getattr__(name):
60+
if name in __all__:
61+
return importlib.import_module("." + name, __name__)
62+
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
63+
64+
# lib/submod.py
65+
66+
print("Submodule loaded")
67+
class HeavyClass:
68+
...
69+
70+
# main.py
71+
72+
import lib
73+
lib.submodule.HeavyClass # prints "Submodule loaded"
74+
5075
There is a related proposal PEP 549 that proposes to support instance
5176
properties for a similar functionality. The difference is this PEP proposes
5277
a faster and simpler mechanism, but provides more basic customization.

0 commit comments

Comments
 (0)