Skip to main content

Lazy attributes for Python objects

Project description

Package Contents

@lazy

A decorator to create lazy attributes.

Overview

Lazy attributes are computed attributes that are evaluated only once, the first time they are used. Subsequent uses return the results of the first call. They come handy when code should run

  • late, i.e. just before it is needed, and

  • once, i.e. not twice, in the lifetime of an object.

You can think of it as deferred initialization. The possibilities are endless.

Examples

The class below creates its store resource lazily:

from lazy import lazy

class FileUploadTmpStore(object):

    @lazy
    def store(self):
        location = settings.get('fs.filestore')
        return FileSystemStore(location)

    def put(self, uid, fp):
        self.store.put(uid, fp)
        fp.seek(0)

    def get(self, uid, default=None):
        return self.store.get(uid, default)

Another application area is caching:

class PersonView(View):

    @lazy
    def person_id(self):
        return self.request.get('person_id', -1)

    @lazy
    def person_data(self):
        return self.session.query(Person).get(self.person_id)

Credits

I first encountered this type of descriptor in the zope.cachedescriptors package, which is part of the Zope Toolkit.

Changelog

1.2 - 2014-04-19

  • Remove setuptools from install_requires because it isn’t. [stefan]

1.1 - 2012-10-12

  • Use functools.wraps() properly; the list of attributes changes with every version of Python 3. [stefan]

1.0 - 2011-03-24

  • Initial release.

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-1.2.zip (14.4 kB view details)

Uploaded Source

File details

Details for the file lazy-1.2.zip.

File metadata

  • Download URL: lazy-1.2.zip
  • Upload date:
  • Size: 14.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No

File hashes

Hashes for lazy-1.2.zip
Algorithm Hash digest
SHA256 127ea610418057b953f0d102bed83f2c367be13b59f8d0ddf3b8a86c7d31b970
MD5 02713784e0a92ff9b6af1df8863dd79d
BLAKE2b-256 010945e590953c798349f2b5b2d2c2d669bd2b909e254d75f4f70e55cde8edae

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