File tree Expand file tree Collapse file tree 1 file changed +25
-0
lines changed Expand file tree Collapse file tree 1 file changed +25
-0
lines changed Original file line number Diff line number Diff line change @@ -47,6 +47,31 @@ on module *instances*. For example::
47
47
48
48
from lib import old_function # Works, but emits the warning
49
49
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
+
50
75
There is a related proposal PEP 549 that proposes to support instance
51
76
properties for a similar functionality. The difference is this PEP proposes
52
77
a faster and simpler mechanism, but provides more basic customization.
You can’t perform that action at this time.
0 commit comments