Skip to content

sharedmethodcache

Frederik Hennig requested to merge da15siwa/pystencils:sharedmethodcache into master

Added a per-instance method cache decorator, which can be shared among multiple methods with the same signature.

sharedmethodcache allows memoization similarily to functools.cache, but for instance methods of classes. The cache dictionary is added as a member to the method's owning instance. Further, multiple methods with the same signature (up to kwargs) may use the same cache dict by specifying the same cache_id. This makes sense for methods that produce the same results on identical inputs, but by different computational paths.

This decorator is currently employed in lbmpy!113 (merged) by abstract_equilibrium.py, but surely, more use cases will follow.

Example:

class Fib:
    def __init__(self):
        self.fib_rec_called = 0
        self.fib_iter_called = 0

    @sharedmethodcache("fib_cache")
    def fib_rec(self, n):
        self.fib_rec_called += 1
        return 1 if n <= 1 else self.fib_rec(n-1) + self.fib_rec(n-2)

    @sharedmethodcache("fib_cache")
    def fib_iter(self, n):
        self.fib_iter_called += 1
        f1, f2 = 0, 1
        for i in range(n):
            f2 = f1 + f2
            f1 = f2 - f1
        return f2


>>> fib = Fib()
>>> fib.fib_rec(13)
377
>>> fib.fib_cache
{(1,): 1,
 (0,): 1,
 (2,): 2,
 (3,): 3,
 (4,): 5,
 (5,): 8,
 (6,): 13,
 (7,): 21,
 (8,): 34,
 (9,): 55,
 (10,): 89,
 (11,): 144,
 (12,): 233,
 (13,): 377}
>>> fib.fib_rec_called
14
>>> fib.fib_iter(11)
144
>>> fib.fib_iter_called
0

Merge request reports