| 1151 | ) |
| 1152 | |
| 1153 | def __get__(self, instance, owner=None): |
| 1154 | if instance is None: |
| 1155 | return self |
| 1156 | if self.attrname is None: |
| 1157 | raise TypeError( |
| 1158 | "Cannot use cached_property instance without calling __set_name__ on it.") |
| 1159 | try: |
| 1160 | cache = instance.__dict__ |
| 1161 | except AttributeError: # not all objects have __dict__ (e.g. class defines slots) |
| 1162 | msg = ( |
| 1163 | f"No '__dict__' attribute on {type(instance).__name__!r} " |
| 1164 | f"instance to cache {self.attrname!r} property." |
| 1165 | ) |
| 1166 | raise TypeError(msg) from None |
| 1167 | val = cache.get(self.attrname, _NOT_FOUND) |
| 1168 | if val is _NOT_FOUND: |
| 1169 | val = self.func(instance) |
| 1170 | try: |
| 1171 | cache[self.attrname] = val |
| 1172 | except TypeError: |
| 1173 | msg = ( |
| 1174 | f"The '__dict__' attribute on {type(instance).__name__!r} instance " |
| 1175 | f"does not support item assignment for caching {self.attrname!r} property." |
| 1176 | ) |
| 1177 | raise TypeError(msg) from None |
| 1178 | return val |
| 1179 | |
| 1180 | __class_getitem__ = classmethod(GenericAlias) |
| 1181 | |