A Lazy Property
Write a decorator class lazy_property for methods, used like @property but with caching:
python
class Circle:
def __init__(self, r): self.r = r
@lazy_property
def area(self):
... # an expensive calculation
- The method runs once per instance, the first time
circle.areais read; later reads return the stored value without calling the method again. - Different instances have separate stored values.
- Reading the attribute on the class (
Circle.area) returns thelazy_propertyobject itself and does not fail.
Understand the problem
Learn the descriptor protocol.
What makes an object a descriptor?
- It is a function
- Its class defines
__get__(and maybe__set__,__delete__) - It is stored in a dictionary
When you read obj.name and the class attribute name has a __get__ method, Python calls __get__(descriptor, obj, type(obj)) and uses its result. Functions, property, classmethod and staticmethod all work that way.
A descriptor that defines only __get__ (a non-data descriptor) is used for obj.x. If obj.__dict__ also has an entry "x", which wins?
- The descriptor
- The instance
__dict__entry - It is an error
Lookup order: data descriptors (with __set__) first, then the instance __dict__, then non-data descriptors. So after you store the computed value in obj.__dict__["x"], later reads find it there and the descriptor is not called again. That is the whole trick of a lazy property.
When you read Circle.area on the class, what does __get__ receive as instance?
- The class
None- An empty object
For access through the class, instance is None and owner is the class. Return self (the descriptor) in that case, as property does.
Write the solution
Write the descriptor class.
class lazy_property:
# Write your code here.
pass
Hint 1: a question to ask yourself
Where can you store a computed value so that it belongs to one instance, and so that a normal attribute read finds it before the descriptor is asked again?
Hint 2: the shape of the answer
__init__(self, func) stores the function and its name. __get__(self, instance, owner=None): if instance is None return self; otherwise compute value = self.func(instance), store it with instance.__dict__[self.name] = value, and return it.
Reflect
Solution
class lazy_property:
def __init__(self, func):
self.func = func
self.name = func.__name__
self.__doc__ = func.__doc__
def __get__(self, instance, owner=None):
if instance is None:
return self
value = self.func(instance)
instance.__dict__[self.name] = value
return value
What this tests: the descriptor protocol (__get__), attribute lookup order, instance.__dict__, and writing a decorator as a class.
Why it works: the first read finds no entry in the instance __dict__, so Python asks the descriptor. The descriptor computes the value and writes it into the instance __dict__ under the same name. Every later read finds that entry first, so the method is never called again. Per instance, one calculation.
Why not store the value on the descriptor? The descriptor object belongs to the class, so it is shared by all instances. Storing the value there would give every circle the first circle's area.
In the standard library: functools.cached_property (Python 3.8+) does exactly this. Know it for real code; write your own here to learn how descriptors work.
Invalidating the cache: del obj.area removes the instance entry, so the next read computes again.
What an interviewer might ask next: Make a read-only version with __set__ that raises AttributeError. (That turns it into a data descriptor, which wins over the instance dict, so you must store the value elsewhere.)
VISIBLE = 3
CASES = [
('calls = []\nclass Circle:\n def __init__(self, r):\n self.r = r\n @lazy_property\n def area(self):\n calls.append(1)\n return 3 * self.r ** 2\nc = Circle(2)\nresult = (c.area, c.area, len(calls))', (12, 12, 1), 'computed once, read twice'),
('calls = []\nclass Circle:\n def __init__(self, r):\n self.r = r\n @lazy_property\n def area(self):\n calls.append(1)\n return 3 * self.r ** 2\nc = Circle(2)\nd = Circle(1)\nresult = (c.area, d.area, c.area, len(calls))', (12, 3, 12, 2), 'separate values per instance'),
('class Circle:\n @lazy_property\n def area(self):\n return 1\nresult = isinstance(Circle.area, lazy_property)', True, 'reading it on the class gives the descriptor'),
('calls = []\nclass A:\n @lazy_property\n def x(self):\n calls.append(1)\n return 5\na = A()\nresult = (len(calls), a.x, len(calls))', (0, 5, 1), 'nothing runs until the first read'),
('class A:\n @lazy_property\n def x(self):\n """The x."""\n return 5\nresult = A.x.__doc__', 'The x.', 'the docstring is kept'),
('calls = []\nclass A:\n @lazy_property\n def x(self):\n calls.append(1)\n return 5\na = A()\na.x\ndel a.x\na.x\nresult = len(calls)', 2, 'deleting the stored value makes it compute again'),
('class A:\n @lazy_property\n def x(self):\n return [1]\na = A()\nresult = a.x is a.x', True, 'the same stored object is returned'),
('class A:\n @lazy_property\n def x(self):\n return 7\na = A()\na.x = 99\nresult = a.x', 99, 'an assigned value replaces the cached one'),
]