Skip to main content

Practice · 2 of 2

Implement cached_property

CHALLENGE
Difficulty: advanced+25 XP

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

Back to lesson: Practice: Descriptor Practice