簡體   English   中英

如何清除memoize緩存?

[英]How can the memoize cache be cleared?

我使用以下裝飾器來緩存純函數返回:

def memoize(obj):
    cache = obj.cache = {}

    @functools.wraps(obj)
    def memoizer(*args, **kwargs):
        if args not in cache:
            cache[args] = obj(*args, **kwargs)
        return cache[args]
    return memoizer

它工作得很好,但我遇到了單元測試的問題,例如:

class TestFoo(unittest.TestCase):

    def setUp(self):
        # clear the cache here
        pass

    @patch('module1.method1')
    def test_method1_1(self, method1):
        method1.return_value = ""
        d = module1.method2()
        self.assertTrue(len(d) == 0)

    @patch('module1.method1')
    def test_method1_2(self, method1):
        method1.return_value = "TEST1234"
        d = module1.method2()
        self.assertTrue(len(d) == 2)

我的問題是module1.method1memoize修飾,因此從一個測試到另一個測試,它的返回值被緩存,並且不會隨后的method1.return_value = "..."賦值而改變。

如何清除memoize緩存? 當我弄清楚這一點時,我會清除測試用例的setUp方法中的緩存。

裝飾器通過在函數中注入一個字典來工作

您可以手動清除該字典:

@memoize
def square (x):
  return x*x

square(2)
square(3)

print square.__dict__
# {'cache': {(2,): 4, (3,): 9}}

square.cache.clear()
print square.__dict__
# {'cache': {}}

您可以在TearUp方法中使用module1.method1.cache.clear()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM