How can I clear the memoize cache?

I use the following decorator to cache a pure function:

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

This works very well, but I ran into a problem with unit tests, such as:

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)

My problem is that it module1.method1is decorated memoize, and therefore from one test to another its return value is cached and does not change with subsequent method1.return_value = "..."assignments.

How can I clear the memoize cache? When I find out, I cleared the cache in the setUp method of the test case.

+4
source share
1 answer

The decorator works by inserting dictionaries into a function

You can manually clear this line:

@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': {}}

You can use module1.method1.cache.clear()in the TearUp method

+3

Source: https://habr.com/ru/post/1585107/


All Articles