DEV Community

Cover image for Python lazy loading of an attribute
Tib
Tib

Posted on

7

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 😙

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay