Skip to main content

Lazy accessor and other tools for deferred evaluation.

Project description

Lazyutils provides a few simple utilities for lazy evaluation of code.

Lazy attribute

The lazy decorator defines an attribute with deferred initialization:

class Vec:
    def __init__(self, x, y):
        self.x, self.y = x, y

    @lazy
    def magnitude(self):
        print('computing...')
        return math.sqrt(x**2 + y**2)

Now the “magnitude” attribute is initialized and cached upon first use:

>>> v = Vec(3, 4)
>>> v.magnitude
computing...
5.0

The attribute is writable and apart from the deferred initialization, it behaves just like any regular Python attribute.

>>> v.magnitude = 42
>>> v.magnitude
42

Lazy attributes can be useful either to simplify the implementation of the __init__ method of objects that initialize a great number or variables or as an optimization that delays potentially expensive computations that may not be necessary in the object’s lifecycle.

Delegation

The delegate_to() function delegates some attribute to an attribute during the class definition:

class Arrow:
    magnitude = delegate_to('vector')

    def __init__(self, vector, start=Vec(0, 0)):
        self.vector = radius
        self.start = start

Now, the .magnitude attribute of Arrow instances is delegated to .vector.magnitude. Delegate fields are useful in class composition when one wants to expose a few selected attributes from the inner objects. delegate_to() handles attributes and methods with no distinction.

>>> a = Arrow(Vec(6, 8))
>>> a.magnitude
magnitude...
10.0

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

lazyutils-0.2.1.tar.gz (5.3 kB view details)

Uploaded Source

File details

Details for the file lazyutils-0.2.1.tar.gz.

File metadata

  • Download URL: lazyutils-0.2.1.tar.gz
  • Upload date:
  • Size: 5.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No

File hashes

Hashes for lazyutils-0.2.1.tar.gz
Algorithm Hash digest
SHA256 b39b9655ac8b216811774a27d1587720ab6dc4cc0a78f1c4f03e9208956c8847
MD5 c4c2ca5b61289ceaba6bc34ab4cd77b7
BLAKE2b-256 34f39c70d7709f1827d82b0ab367d6fdaf8f449891aa57e6506cbc2af3cf8212

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