0

Description: I am trying to use the lru_cache decorator from the functools module to cache instances of two classes, A and B, where B inherits from A. Here is my code:

from functools import lru_cache

@lru_cache(1)
class A:
    def __init__(self):
        pass

@lru_cache(1)
class B(A):
    pass

b = B()

However, when I run this code, I get the following error:

TypeError: lru_cache() missing required argument 'cache_info_type' (pos 4)

I am using Python 3.8, and I am not sure why I am getting this error. Can anyone help me understand what is causing this error and how to fix it? Thank you in advance for your help.

I tried to use the lru_cache decorator to cache instances of two classes, A and B, where B inherits from A. I expected the code to run without errors and to create a single instance of each class, which would be cached and reused if I created another instance of the same class. However, I encountered a TypeError with the message "lru_cache() missing required argument 'cache_info_type' (pos 4)", which I did not expect. I am not sure why this error occurred, and I am seeking help to understand the cause of the error and how to fix it.

Shawn
  • 3
  • 2

2 Answers2

0

I think lru_cache might not work with class,because class are not recalculated after creation.You can try to override the __new__ method to achieve your needs.

class A:
    def __init__(self):
        pass

class B(A):
    _instance = None

    def __new__(cls):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance

This is also similar to a singleton pattern

911
  • 542
  • 2
  • 12
0

When you do

@lru_cache(1)
class A:
    def __init__(self):
        pass

A is not the class you defined. A is an LRU caching wrapper.

When you then do

@lru_cache(1)
class B(A):
    pass

you are trying to inherit from the wrapper, not the class you defined.

user2357112
  • 260,549
  • 28
  • 431
  • 505