decorator.py 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. # This Python file uses the following encoding: utf-8
  2. # @author runhey
  3. # github https://github.com/runhey
  4. from functools import wraps
  5. from typing import Callable, Generic, TypeVar
  6. T = TypeVar("T")
  7. class cached_property(Generic[T]):
  8. """
  9. cached-property from https://github.com/pydanny/cached-property
  10. Add typing support
  11. A property that is only computed once per instance and then replaces itself
  12. with an ordinary attribute. Deleting the attribute resets the property.
  13. Source: https://github.com/bottlepy/bottle/commit/fa7733e075da0d790d809aa3d2f53071897e6f76
  14. """
  15. def __init__(self, func: Callable[..., T]):
  16. self.func = func
  17. def __get__(self, obj, cls) -> T:
  18. if obj is None:
  19. return self
  20. value = obj.__dict__[self.func.__name__] = self.func(obj)
  21. return value
  22. def del_cached_property(obj, name):
  23. """
  24. Delete a cached property safely.
  25. Args:
  26. obj:
  27. name (str):
  28. """
  29. try:
  30. del obj.__dict__[name]
  31. except KeyError:
  32. pass
  33. def has_cached_property(obj, name):
  34. """
  35. Check if a property is cached.
  36. Args:
  37. obj:
  38. name (str):
  39. """
  40. return name in obj.__dict__