DEV Community

Cover image for Python lazy loading of an attribute
Tib
Tib

Posted on

Python lazy loading of an attribute

(Image from Adrian Swancar)

It's not something complex but it's very useful anyway to do not wait or stress your infrastructure... for nothing!

Lazy loading (and caching) of an attribute

The idea is to have an empty attribute that will get its value only when accessed the first time. To illustrate, I used a class Gift with an attribute price that is slow to compute:

import time

class Gift():
    _price = None

    def __init__(self, what):
        self.what = what

    def costly_computation(self):
        print("Costly computation")
        time.sleep(2)
        return 10

    @property
    def price(self):
        if not self._price:
            self._price = self.costly_computation()
        return self._price
Enter fullscreen mode Exit fullscreen mode

The costly computation will only affect when accessing the attribute, and it will happen only one time (first access) 😃

See it in action

>>> from gift import *
>>> g = Gift("Sunglasses")
>>> g.price
Costly computation
# ...
# ... freezes a bit
# ...
10
>>> g.price
10
Enter fullscreen mode Exit fullscreen mode

That's all 😙

Top comments (0)