From cf79157e3f7230c1cfbdef030a32902a51e352ea Mon Sep 17 00:00:00 2001 From: Daniel Greenfeld Date: Sun, 18 May 2014 11:55:02 -0700 Subject: [PATCH] Demonstrate and test cache invalidation --- README.rst | 22 ++++++++++++++++++++++ tests/test_cached_property.py | 25 ++++++++++++++++++++++++- 2 files changed, 46 insertions(+), 1 deletion(-) diff --git a/README.rst b/README.rst index ffd395c..1086672 100644 --- a/README.rst +++ b/README.rst @@ -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 -------- diff --git a/tests/test_cached_property.py b/tests/test_cached_property.py index ec789ff..1e6f31a 100755 --- a/tests/test_cached_property.py +++ b/tests/test_cached_property.py @@ -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) -- 2.30.2