Decorator with parameters

ast ast at invalid
Mon Apr 6 04:31:05 EDT 2020


Hello

I wrote a decorator to add a cache to functions.
I realized that cache dictionnary could be defined
as an object attribute or as a local variable in
method __call__.
Both seems to work properly.
Can you see any differences between the two variants ?

from collection import OrderedDict

class Memoize1:
     def __init__(self, size=None):
         self.size = size
         self.cache = OrderedDict()     ### cache defined as an attribute
     def __call__(self, f):
         def f2(*arg):
             if arg not in self.cache:
                 self.cache[arg] = f(*arg)
                 if self.size is not None and len(self.cache) >self.size:
                     self.cache.popitem(last=False)
             return self.cache[arg]
         return f2

# variant

class Memoize2:
     def __init__(self, size=None):
         self.size = size
     def __call__(self, f):
         cache = OrderedDict()      ### cache defined as a local variable
         def f2(*arg):
             if arg not in cache:
                 cache[arg] = f(*arg)
                 if self.size is not None and len(cache) > self.size:
                     cache.popitem(last=False)
             return cache[arg]
         return f2

@Memoize1(16)
def fibo1(n):
     if n < 2: return n
     return fibo1(n-2)+fibo1(n-1)


@Memoize2(16)
def fibo2(n):
     if n < 2: return n
     return fibo2(n-2)+fibo2(n-1)


More information about the Python-list mailing list