pythonpython-3.xtypeerrorpython-lru-cache

TypeError when using lru_cache with class inheritance in Python 3.8


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.


Solution

  • 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.