Skip to content

Commit

Permalink
Update PEP 562 with an example (#418)
Browse files Browse the repository at this point in the history
This adds an example of module __getattr__ usage that implements lazy imports to Rationale of PEP 562.
  • Loading branch information
ilevkivskyi authored and gvanrossum committed Sep 12, 2017
1 parent 184d7c7 commit 93e4677
Showing 1 changed file with 25 additions and 0 deletions.
25 changes: 25 additions & 0 deletions pep-0562.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down

0 comments on commit 93e4677

Please sign in to comment.