Search code examples
pythonpython-3.xdecoratorstatic-methodspython-decorators

How do I properly decorate a `classmethod` with `functools.lru_cache`?


I tried to decorate a classmethod with functools.lru_cache. My attempt failed:

import functools
class K:
    @functools.lru_cache(maxsize=32)
    @classmethod
    def mthd(i, stryng: str): \
        return stryng

obj = K()

The error message comes from functools.lru_cache:

TypeError: the first argument must be callable

Solution

  • A class method is, itself, not callable. (What is callable is the object return by the class method's __get__ method.)

    As such, you want the function decorated by lru_cache to be turned into a class method instead.

    @classmethod
    @functools.lru_cache(maxsize=32)
    def mthd(cls, stryng: str):
        return stryng