degal/utils.py
author Tero Marttila <terom@fixme.fi>
Fri, 05 Jun 2009 19:30:53 +0300
changeset 59 fbbe956229cc
parent 44 533b7e8b5d3b
child 73 8897352630a5
permissions -rw-r--r--
remove old utils and write some new ones
"""
    Miscellaneous utilities
"""

import functools

class LazyProperty (property) :
    """
        Lazy-loaded properties
    """

    def __init__ (self, func) :
        """
            Initialize with no value
        """

        super(LazyProperty, self).__init__(func)

        self.value = None

    def run (self) :
        """
            Run the background func and return the to-be-cached value
        """

        return super(LazyProperty, self).__call__()

    def __call__ (self) :
        """
            Return the cached value if it exists, otherwise, call the func
        """

        if not self.value :
            # generate it
            self.value = self.run()

        return self.value

class LazyIteratorProperty (LazyProperty) :
    """
        A lazy-loaded property that automatically converts an iterator/genexp into a list.
    """

    def run (self) :
        """
            Wrap LazyProperty.run to return a list
        """

        return list(super(LazyIteratorProperty, self).run())

lazy_load = LazyProperty
lazy_load_iter = LazyIteratorProperty