Skip to content

Instantly share code, notes, and snippets.

@stuaxo
Created January 8, 2026 13:42
Show Gist options
  • Select an option

  • Save stuaxo/b4113c9664e83d7ec630f990f5927769 to your computer and use it in GitHub Desktop.

Select an option

Save stuaxo/b4113c9664e83d7ec630f990f5927769 to your computer and use it in GitHub Desktop.
Module level property
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