Skip to main content

Properties are a very useful feature of Python, effectively allowing an attribute to masquerade as a method (with no arguments other than self). However, sometimes we want to store the results of an expensive computation in an attribute. The straightforward way to do it would be something like the following:

import time

def do_some_big_calculation():
    """Simulating some ginormous calculation going on somewhere..."""
    print("{}: Calculations started...".format(time.time))
    time.sleep(5)
    print("{}: Calculations complete!".format(time.time))
    return 42

class SomeClass(object):

    def __init__(self):
        self.calculation_value = do_some_big_calculation()

And that certainly works. However, this means that whenever you instantiate an object from SomeClass, you’ll perform this calculation each time. That could be problematic…

So, what we really want is for this calculation to only be done when it’s needed. In other words, what we want is for this attribute to be lazy.

To do that, you can create a property, and a “private” attribute, named _calculation_value, used to cache the result, like so:

class SomeOtherClass(object):

@property
def calculation_value(self):

    if not hasattr(self, "_calculation_value"):
        self._calculation_value = do_some_big_calculation()

    return self._calculation_value

This package essentially reduces this down to a decorator:

import lazy_property

class YetAnotherClass(object):

    @lazy_property.LazyProperty
    def calculation_value(self):

        return do_some_big_calculation()

And when called, the “calculation” is only done once:

In [5]:yac = YetAnotherClass()

In [6]: yac.calculation_value
1440798443.228256: Calculations started...
1440798448.229179: Calculations complete!
Out[6]: 42

In [7]: yac.calculation_value
Out[7]: 42

Note, however, that this property is not writable:

In [8]: yac.calculation_value = "something_else"
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-8-0bbfd01ac59a> in <module>()
----> 1 yac.calculation_value = "something_else"

AttributeError: can't set attribute

That’s what the LazyWritableProperty is for.

class SomethingElse(object):

@lazy_property.LazyWritableProperty
def overwritable_calculation_value(self):

    return do_some_big_calculation()
In [9]: se = SomethingElse()

In [10]: se.overwritable_calculation_value
1440798779.27305: Calculations started...
1440798784.274711: Calculations complete!
Out[10]: 42

In [11]: se.overwritable_calculation_value
Out[11]: 42

In [12]: se.overwritable_calculation_value = "foo"

In [13]: se.overwritable_calculation_value
Out[13]: 'foo'

Installation

It’s up on PyPI:

pip install lazy-property

Or, to do it the hard way, clone this repo, enter the directory into which you cloned the repo, and do a

python setup.py install

Wait…isn’t this a solved problem?

Well, yes, but I couldn’t find a lazy attribute implementation that clearly implemented laziness in the (fairly simple) way discussed above.

Metadata

Release files for lazy-property 0.0.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for lazy-property 0.0.1
File Size Uploaded Provenance
lazy-property-0.0.1.tar.gz 3.2 kB Without provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for lazy-property 0.0.1
File Interpreter ABI Platform
lazy_property-0.0.1-py2.py3-none-any.whl Python 3, Python 2 none any Details

Total release size: 5.7 kB

Release files / lazy-property-0.0.1.tar.gz

Download URL lazy-property-0.0.1.tar.gz
Size 3.2 kB
Tags Source
SHA-256 checksum
How to use checksums
3a1cd36949b323468731ba569e169415a609d5904d53fffe982055fbe67b1180
BLAKE2b-256 checksum
How to use checksums
1c9755bf318faf296b254a20e80657b439b019fd809d4aabc1e55d7788f75401
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No

Release files / lazy_property-0.0.1-py2.py3-none-any.whl

Download URL lazy_property-0.0.1-py2.py3-none-any.whl
Size 2.4 kB
Tags Python 2 Python 3
SHA-256 checksum
How to use checksums
907b3a9e653771f4d0bcafd0fbfcdac8aaade85b31ed7eccd1cbfe59c59b149f
BLAKE2b-256 checksum
How to use checksums
4f87871a1522823d2bba3e8fd8cdea0f5eb7fa7596889f1ed73167d895127046
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No

Security for lazy-property 0.0.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.0.1 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page