================
@@ -169,25 +198,32 @@ def __init__(self, enumeration, message):
 
 ### Structures and Utility Classes ###
 
+TInstance = TypeVar("TInstance")
+TResult = TypeVar("TResult")
+
 
-class CachedProperty:
+class CachedProperty(Generic[TInstance, TResult]):
     """Decorator that lazy-loads the value of a property.
 
     The first time the property is accessed, the original property function is
     executed. The value it returns is set as the new value of that instance's
     property, replacing the original method.
     """
 
-    def __init__(self, wrapped):
+    def __init__(self, wrapped: Callable[[TInstance], TResult]):
         self.wrapped = wrapped
         try:
             self.__doc__ = wrapped.__doc__
         except:
             pass
 
-    def __get__(self, instance, instance_type=None):
+    def __get__(self, instance: TInstance, instance_type: Any = None) -> 
TResult:
         if instance is None:
-            return self
+            property_name = self.wrapped.__name__
+            class_name = instance_type.__name__
+            raise TypeError(
+                f"'{property_name}' is not a static attribute of 
'{class_name}'"
+            )
----------------
DeinAlptraum wrote:

`CachedProperty` is a decorator used as a replacement for `@property` where the 
actual function might include heavier computations, so after the first call 
this caches the result of a decorated function as an attribute of the instance 
it belongs to.

The `if instance is None` case occurs only when trying to call this statically, 
i.e. when the decorated function is called on the class it belongs to, instead 
of on an instance. In that case the existing implementation returns the 
`CachedProperty` object, which... doesn't seem to make any sense. That object 
itself is useless, it is an implementation detail that the user is not supposed 
to see, so I can't think of a reason why this would return `self`. This would 
also make the type annotation more complicated, so I changed this to throw an 
error instead, when trying to access a property as if it were a static attribute

https://github.com/llvm/llvm-project/pull/98745
_______________________________________________
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits

Reply via email to