Demonstrate and test cache invalidation
authorDaniel Greenfeld <pydanny@gmail.com>
Sun, 18 May 2014 18:55:02 +0000 (11:55 -0700)
committerDaniel Greenfeld <pydanny@gmail.com>
Sun, 18 May 2014 18:55:02 +0000 (11:55 -0700)
README.rst
tests/test_cached_property.py

index ffd395c8124801be3b17829516fdc3af0f652cc7..108667241d5e09fc6e27c8ed209bcea9a1100b5a 100644 (file)
@@ -84,6 +84,28 @@ Now when we run it the price stays at $550.
 
 Why doesn't the value of `monopoly.boardwalk` change? Because it's a **cached property**!
 
+Invalidating the Cache
+----------------------
+
+Results of cached functions can be invalidated by outside forces. Let's demonstrate how to force the cache to invalidate:
+
+.. code-block:: python
+
+    >>> monopoly = Monopoly()
+    >>> monopoly.boardwalk
+    550
+    >>> monopoly.boardwalk
+    550
+    >>> # invalidate the cache
+    >>> del m.boardwalk
+    >>> # request the boardwalk property again
+    >>> m.boardwalk
+    600
+    >>> m.boardwalk
+    600
+
+
+
 Credits
 --------
 
index ec789ffdd64fd51977e62d0c86199d00d05d9771..1e6f31ad230a0f871830d562d4546cae43c9ecb1 100755 (executable)
@@ -41,4 +41,27 @@ class TestCachedProperty(unittest.TestCase):
 
         # The cached version demonstrates how nothing new is added
         self.assertEqual(c.add_cached, 1)
-        self.assertEqual(c.add_cached, 1)
\ No newline at end of file
+        self.assertEqual(c.add_cached, 1)
+
+    def test_reset_cached_property(self):
+
+        class Check(object):
+
+            def __init__(self):
+                self.total = 0
+
+            @cached_property
+            def add_cached(self):
+                self.total += 1
+                return self.total
+
+        c = Check()
+
+        # Run standard cache assertion
+        self.assertEqual(c.add_cached, 1)
+        self.assertEqual(c.add_cached, 1)
+
+        # Reset the cache.
+        del c.add_cached
+        self.assertEqual(c.add_cached, 2)
+        self.assertEqual(c.add_cached, 2)