Implement cached_property

easy
Checkpoint challenge
Solve this to show you know the material and jump straight to Unit 10. Everything before it counts as cleared.

functools.cached_property computes an attribute once per instance and then returns the stored value. Build your own.

Implement a descriptor class cached_property(func):

  • On first access, call func(instance), store the result in the instance's __dict__ under the attribute's name (learned via __set_name__) and return it. Because the descriptor is a non-data descriptor (it defines no __set__), later lookups find the instance attribute first and never call the descriptor again.
  • Accessed on the class, it returns the descriptor itself.
  • Each instance has its own cached value.

Also implement invalidate(obj, name): drop the cached value so the next access recomputes it (doing nothing if it isn't cached).

#descriptors#caching#classes2 visible + 1 hidden tests
solution.py · Python 3.13
Loading editor…
Run your code to see results. ⌘↵ to run · ⌘⇧↵ to submit
Implement cached_property · TechGradify