[PYTHON] A simple cache of values in the property decorator. Read only. Note that it keeps caching until the object is deleted.

def cached_ro_property(f):
    cache = [None]
    def _cached_ro_property(*args, **kargs):
        if cache[0]:
            return cache[0]
        cache[0] = f(*args, **kargs)
        return cache[0]
    return property(_cached_ro_property)


from django.test import TestCase
import mox


class TestCachedRoProperty(TestCase):
    """Test for cached_ro_property decorator."""
    
    def setUp(self):
        self.m = mox.Mox()

    def tearDown(self):
        self.m.UnsetStubs()
        self.m = None

    def test_call_1(self):
        """Simple call."""

        from decorators import cached_ro_property

        # Procuder function that should be called once.
        producer = self.m.CreateMockAnything()
        producer().AndReturn(30)

        class C(object):
            @cached_ro_property
            def f(self):
                return producer()

        self.m.ReplayAll()
        c = C()

        self.assertEqual(c.f, 30)
        self.assertEqual(c.f, 30)
        self.m.VerifyAll()

    def test_call_2(self):
        """Check that property function reference self."""

        from decorators import cached_ro_property

        # Procuder function that should be called once.
        producer = self.m.CreateMockAnything()
        producer().AndReturn(30)

        class C(object):
            @cached_ro_property
            def f(self):
                return self.g()
            def g(self):
                return producer()

        self.m.ReplayAll()
        c = C()

        self.assertEqual(c.f, 30)
        self.assertEqual(c.f, 30)
        self.m.VerifyAll()

Recommended Posts

A simple cache of values in the property decorator. Read only. Note that it keeps caching until the object is deleted.
A simple reason why the return value of round (2.675,2) is 2.67 in python (it should be 2.68 in reality ...)
A simple mock server that simply embeds the HTTP request header in the body of the response and returns it.
Create a simple app that incorporates the Fetch API of Ajax requests in Flask and explain it quickly
The background of the characters in the text image is overexposed to make it easier to read.
A script that keeps looking up until the URL is bookmarked with Hatena Bookmark
[Note] A shell script that checks the CPU usage of a specific process in a while loop.