wuug python

A simple python decorator

Here is a very simple python function that requires no libraries, implements some of the deepest python magic and is still remarkably easy to understand:


def memoize_property(f):
    """A lightweight decorator that combines @property and memoization"""
    assert f.__name__
    class Memoize(object):
        # This class implements the non-data descriptor protocol
        # The computed value is memoized to the object instance thus
        # overriding the __get__ method on subsequent accesses
        def __get__(descriptor,instance,owner):
            value = f(instance)
            setattr(instance,f.__name__,value)
            return value
    return Memoize()

It was designed to be used a decorator anywhere you might find yourself creating recursive defintiions:

Syndicate content