Created
January 8, 2026 13:42
-
-
Save stuaxo/b4113c9664e83d7ec630f990f5927769 to your computer and use it in GitHub Desktop.
Module level property
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from functools import cache | |
| class CachedModuleProperty(object): | |
| """ | |
| A decorator for functions, on the module level that makes them lazily loaded. | |
| python 3.14 will have native lazy loading modules so this won't be needed | |
| then. | |
| """ | |
| def __init__(self, func): | |
| """ | |
| :param func: The function to decorate. | |
| Passed in functions are cached using functools.cache. | |
| """ | |
| object.__setattr__(self, "_factory", cache(func)) | |
| @property | |
| def _wrapped(self): | |
| """Invoke the cached factory to get the real object.""" | |
| return object.__getattribute__(self, "_factory")() | |
| def __dir__(self): | |
| """Call through to __dir__ in the proxied object.""" | |
| return dir(self._wrapped) | |
| @property | |
| def __class__(self): | |
| """Call through to __class__ in the proxied object.""" | |
| return self._wrapped.__class__ | |
| def __getattr__(self, name): | |
| return getattr(self._wrapped, name) | |
| def __repr__(self): | |
| """Call through to repr in the proxied object.""" | |
| return repr(self._wrapped) | |
| cached_module_property = CachedModuleProperty |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment