medium +20 pts

Cached Property Manual

Build a manual cached property decorator that computes once and serves the same value.

Write a decorator `cached_property` that can be applied to a method of a class. When accessed as an attribute on an instance, the method is called once and its return value is stored on the instance for all subsequent accesses. The decorator must work correctly per instance (not share cache across instances). It must not interfere with attribute deletion or reassignment: if the attribute is deleted from the instance, the next access should recompute the property. It should raise the same exceptions as a normal property if the method raises. Define the decorator with the exact signature: ```python def cached_property(func): ... ``` The decorator should return a descriptor object (or use `property` with a caching getter). The cached value must be stored under attribute name `'_cached_' + func.__name__` on the instance. When the attribute is deleted, the cache is removed and recomputation occurs. The decorated method can be called directly via the class, e.g., `MyClass.method(instance)`, and should behave as a normal function in that case. Implement only the decorator and any helper classes/functions needed. Your code will be tested by applying the decorator to sample methods and checking behavior.

Constraints

- The decorated method must accept only `self` (no extra arguments). - The cache must be per instance. - The cache key is the attribute name `'_cached_' + func.__name__`. - The decorator must work for classes with `__slots__` if they include a `__dict__` slot. - Time complexity: O(1) amortized for attribute access after caching.

Example

>>> class Example:
...     @cached_property
...     def value(self):
...         print('computing')
...         return 42
>>> e = Example()
>>> e.value
computing
42
>>> e.value
42
>>> del e.value
>>> e.value
computing
42
>>> f = Example()
>>> f.value  # computes again for a new instance
computing
42
20 points ~25 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Use the descriptor protocol: `__get__`, `__set__`, `__delete__`.
Store the cached value in `obj.__dict__` under a unique key derived from the method name.
In `__get__`, check if the cache key exists in `obj.__dict__`; if not, compute and store.
In `__delete__`, remove the cache key if it exists; consider raising AttributeError if the attribute doesn't exist to mimic property behavior.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.