pep562

raw JSON →
1.1 verified Fri May 01 auth: no python deprecated

Backport of PEP 562 (customizing module __getattr__ and __dir__) for Python 2.7, 3.5, and 3.6. Current version 1.1, last updated in 2019. Low release cadence.

pip install pep562
error ImportError: No module named pep562
cause The library is not installed.
fix
Run pip install pep562 and ensure the environment is activated.
error AttributeError: module 'your_module' has no attribute '__getattr__'
cause `patch_module` was not called, or the function is not defined as a module-level __getattr__.
fix
Call pep562.patch_module(__name__) and define a top-level function named __getattr__.
deprecated PEP 562 is natively supported in Python 3.7+. This backport is only needed for Python <= 3.6.
fix Remove dependency and conditional imports when targeting Python >= 3.7.
gotcha The library must be imported and `patch_module` called before any other code that relies on __getattr__ or __dir__.
fix Ensure `import pep562; pep562.patch_module(__name__)` is executed early, preferably at the top of the module.

Patches the current module to support PEP 562 on Python < 3.7.

import sys

if sys.version_info < (3, 7):
    import pep562
    pep562.patch_module(__name__)

# Define module-level __getattr__ and __dir__
def __getattr__(name):
    if name == 'missing':
        return 'default'
    raise AttributeError(f"module {__name__!r} has no attribute {name!r}")

def __dir__():
    return ['existing']