5

My understanding is that functools @cache decorator will memoize on the arguments. However for instance methods of a class, the arguments include 'self'. Would that have any performance impact?

class Test:
    def __init__(self):
        self.cache = {}

    def test(self, a, b):
        result = self.cache.get((a,b))
        if result is None:
            result = a + b
            self.cache[(a,b)] = result
        return result

Would the above perform worse than simply decorating test() with @functools.cache?

Ben
  • 159
  • 8
  • 1
    This is not a "class method". This is an *instance method*. – juanpa.arrivillaga Oct 10 '21 at 23:22
  • When you say "class method" you're not referring to methods decorated by `classmethod`, are you? A `classmethod` normally binds to the class, not to an individual instance. – Blckknght Oct 10 '21 at 23:22
  • 3
    "Would the above perform worse than simply decorating test() with @functools.cache?" This seems like an empirical question... did you try profiling the code? Because that would give you your answer – juanpa.arrivillaga Oct 10 '21 at 23:27
  • Since functools.cache is the same as lru_cache(maxsize=None), check out [Python functools lru_cache with class methods: release object](https://stackoverflow.com/questions/33672412/python-functools-lru-cache-with-class-methods-release-object) on how to properly use it to avoid passing self. – DarrylG Oct 10 '21 at 23:30
  • Thanks, I've edited the question to specifically refer to instance methods. @DarrylG looking at the link it seems like there is no official solution to avoid passing self, and I should implement some sort of workaround manually? – Ben Oct 11 '21 at 03:02
  • @Ben -- seems that way. The link provided possible workarounds. – DarrylG Oct 11 '21 at 03:06
  • 1
    You don't want to avoid passing `self`. You're using `self`. – Mad Physicist Oct 11 '21 at 21:41

0 Answers0