Debian Codegraph @

src/graphql/pyutils/cached_property.py

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