Command Palette

Search for a command to run...

Hectal
Phase 13: Python Internals and Performance
Python · Exercise 2 of 6 PreviousNext
Advanced

Write your own cached_property

Write a class lazy that works as a decorator for a method, like functools.cached_property. The first read of the attribute calls the method, and the result is stored on the instance. Later reads must not call the method again.

It must be a non-data descriptor (define __get__, do not define __set__). Reading it on the class (Report.total) must return the lazy object itself. Store the value in the instance's __dict__ under the method's name.

What Check tests

  1. The first read returns the computed value
  2. Several reads call the method only once
  3. The value is stored in the instance __dict__
  4. A falsy result (such as 0) is cached too
  5. Deleting the attribute makes it compute again
  6. Each instance has its own value
  7. Reading it on the class returns the descriptor
  8. It is a non-data descriptor
  9. The program prints Computed: 1

Stuck? One hint at a time

The solution unlocks after your first Check. Try first: that is where the learning happens.

main.py
Sign in to run your code.

Output

Press Run to see what your program prints.