Skip to main content

Practice ยท 2 of 2

Implement cached_property

Implement a non-data descriptor CachedProperty that computes once and caches per instance: - constructed with the computing function: CachedProperty(fn) - first access calls fn(instance) and caches the result in instance.__dict__ under the attribute name (use __set_name__ to learn it) - later accesses return the cached value WITHOUT calling fn again (track call count via a list wrapper in the test) - because it is non-data, a later direct assignment obj.name = x overrides the cache โ€” that behavior must work

Difficulty: advanced

Back to lesson: Practice: Descriptor Practice