| 1108 | ) |
| 1109 | |
| 1110 | def __get__(self, instance, owner=None): |
| 1111 | if instance is None: |
| 1112 | return self |
| 1113 | if self.attrname is None: |
| 1114 | raise TypeError( |
| 1115 | "Cannot use cached_property instance without calling __set_name__ on it.") |
| 1116 | try: |
| 1117 | cache = instance.__dict__ |
| 1118 | except AttributeError: # not all objects have __dict__ (e.g. class defines slots) |
| 1119 | msg = ( |
| 1120 | f"No '__dict__' attribute on {type(instance).__name__!r} " |
| 1121 | f"instance to cache {self.attrname!r} property." |
| 1122 | ) |
| 1123 | raise TypeError(msg) from None |
| 1124 | val = cache.get(self.attrname, _NOT_FOUND) |
| 1125 | if val is _NOT_FOUND: |
| 1126 | val = self.func(instance) |
| 1127 | try: |
| 1128 | cache[self.attrname] = val |
| 1129 | except TypeError: |
| 1130 | msg = ( |
| 1131 | f"The '__dict__' attribute on {type(instance).__name__!r} instance " |
| 1132 | f"does not support item assignment for caching {self.attrname!r} property." |
| 1133 | ) |
| 1134 | raise TypeError(msg) from None |
| 1135 | return val |
| 1136 | |
| 1137 | __class_getitem__ = classmethod(GenericAlias) |
| 1138 | |