youknowone / ring

Python cache interface with clean API and built-in memcache & redis + asyncio support.
http://ring-cache.readthedocs.io/en/latest/
Other
480 stars 37 forks source link

Metaclass argument in class definition breaks caching for constructor #196

Closed nonamethanks closed 1 year ago

nonamethanks commented 1 year ago

Might be a very niche case, but caching a class's constructor doesn't work:

import ring

class A(type):
    pass 

class B(metaclass=A):
    @ring.lru()
    def __new__(cls, *args, **kwargs):
        return super().__new__(cls)

    def __init__(self, a, b):
        self.a = a 
        self.b = b

    def __str__(self):
        return f"{self.__class__.__name__}[{self.a}_{self.b}]"

b1 = B(1, 2)
b2 = B(2, 3)

This raises: TypeError: The given value '<class '__main__.B'>' of type '<class '__main__.A'>' is not a key-compatible type. Add __ring_key__(), __str__() or __hash__().

But that's not correct: B has a defined __str__.

youknowone commented 1 year ago

The value is not an instance of B, but the type B which is instance of A. So you need A.__str__

nonamethanks commented 1 year ago

Ah, you're right, I see what the problem is with the code.