Skip to main content

Makes properties lazy (ie evaluated only when called)

Project description

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.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

lazy-property-0.0.1.tar.gz (3.2 kB view details)

Uploaded Source

Built Distribution

lazy_property-0.0.1-py2.py3-none-any.whl (2.4 kB view details)

Uploaded Python 2Python 3

File details

Details for the file lazy-property-0.0.1.tar.gz.

File metadata

  • Download URL: lazy-property-0.0.1.tar.gz
  • Upload date:
  • Size: 3.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No

File hashes

Hashes for lazy-property-0.0.1.tar.gz
Algorithm Hash digest
SHA256 3a1cd36949b323468731ba569e169415a609d5904d53fffe982055fbe67b1180
MD5 c77b36ddcdc4f5cca622da4d2a8caba0
BLAKE2b-256 1c9755bf318faf296b254a20e80657b439b019fd809d4aabc1e55d7788f75401

See more details on using hashes here.

File details

Details for the file lazy_property-0.0.1-py2.py3-none-any.whl.

File metadata

File hashes

Hashes for lazy_property-0.0.1-py2.py3-none-any.whl
Algorithm Hash digest
SHA256 907b3a9e653771f4d0bcafd0fbfcdac8aaade85b31ed7eccd1cbfe59c59b149f
MD5 b82df387778069ddf108c2e9e0db86d1
BLAKE2b-256 4f87871a1522823d2bba3e8fd8cdea0f5eb7fa7596889f1ed73167d895127046

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page