_util.py 1.0 KB

12345678910111213141516171819202122232425262728293031323334
  1. _missing = object()
  2. class cached_property(property): # pragma: no cover
  3. """
  4. Import from:
  5. https://github.com/pallets/werkzeug/blob/master/werkzeug/utils.py
  6. """
  7. # implementation detail: A subclass of python's builtin property
  8. # decorator, we override __get__ to check for a cached value. If one
  9. # choses to invoke __get__ by hand the property will still work as
  10. # expected because the lookup logic is replicated in __get__ for
  11. # manual invocation.
  12. def __init__(self, func, name=None, doc=None):
  13. self.__name__ = name or func.__name__
  14. self.__module__ = func.__module__
  15. self.__doc__ = doc or func.__doc__
  16. self.__func__ = func
  17. def __set__(self, obj, value):
  18. obj.__dict__[self.__name__] = value
  19. def __get__(self, obj, type=None):
  20. if obj is None:
  21. return self
  22. value = obj.__dict__.get(self.__name__, _missing)
  23. if value is _missing:
  24. value = self.__func__(obj)
  25. obj.__dict__[self.__name__] = value
  26. return value