cached_property.py 1.0 KB

1234567891011121314151617181920212223242526272829303132333435
  1. from typing import Any, Callable, TYPE_CHECKING
  2. if TYPE_CHECKING:
  3. standard_cached_property = None
  4. else:
  5. try:
  6. from functools import cached_property as standard_cached_property
  7. except ImportError: # Python < 3.8
  8. standard_cached_property = None
  9. if standard_cached_property:
  10. cached_property = standard_cached_property
  11. else:
  12. # Code taken from https://github.com/bottlepy/bottle
  13. class CachedProperty:
  14. """A cached property.
  15. A property that is only computed once per instance and then replaces itself with
  16. an ordinary attribute. Deleting the attribute resets the property.
  17. """
  18. def __init__(self, func: Callable) -> None:
  19. self.__doc__ = getattr(func, "__doc__")
  20. self.func = func
  21. def __get__(self, obj: object, cls: type) -> Any:
  22. if obj is None:
  23. return self
  24. value = obj.__dict__[self.func.__name__] = self.func(obj)
  25. return value
  26. cached_property = CachedProperty
  27. __all__ = ["cached_property"]