[Python] Using lru_cache on a class that has a classmethod

Discussão em 'Python' iniciado por Stack, Junho 13, 2025.

  1. Stack

    Stack Membro Participativo

    I want to cache instances of a class because the constructor is complicated and repeated uses won't alter the contents. This works great. However, I want to create a classmethod to clear the cache. In the real code, clear will also clear file cache in addition to memory cache.

    The following is an MWE that works, except for calling the clear

    from functools import lru_cache

    @lru_cache(maxsize=None)
    class MyClass:
    def __init__(self, x):
    print(f"Initializing with {x}")
    self.x = x

    @classmethod
    def clear(cls):
    print('clearing cache')
    cls.cache_clear()

    a = MyClass(1)
    b = MyClass(1)
    print(a is b)
    try: MyClass.clear()
    except Exception as e: print(e) # <-- 'classmethod' object is not callable
    # MyClass.cache_clear() does work however
    c = MyClass(1)

    Continue reading...

Compartilhe esta Página