cachier icon indicating copy to clipboard operation
cachier copied to clipboard

Cachier cannot cache class methods

Open shanghaiyangming opened this issue 5 years ago • 3 comments

class A: @cachier() def B(self): do something Rewrite the cache every time, instead of reading the cache, the expiration time is set immediately, I doubt whether it is because the self parameter will change every time, how can I solve it?

shanghaiyangming avatar May 26 '20 02:05 shanghaiyangming

Sounds like an important use case. Would you care to investigate it and attempt to solve this with a PR? :)

shaypal5 avatar Sep 07 '20 08:09 shaypal5

If the self is not used in the method, it could be defined as static with @staticmethod decorator.

from cachier import cachier
from time import sleep
class A:
    @staticmethod
    @cachier()
    def B():
        sleep(5)
        return True

If some attribute of the object is used, we could use a separate static method, to which we move all the logic.

from cachier import cachier
from time import sleep
class A:
    x = 4

    def B(self):
        return self._C(self.x)

    @staticmethod
    @cachier()
    def _C(x):
        sleep(5)
        return x

If the outcome of the method is very dependant of a complex state of an object, the method is probably not meant to be cached OR it should be broken down into simple, cacheable functions.

elguitar avatar Nov 21 '20 21:11 elguitar

One could argue that given identical state of an object, the cache should work. However, two user-defined objects are not considered equal, if they do not point to the exact same object in the memory. For example pickling creates a new object every time. Example:

>>> import pickle
>>> a
<__main__.A object at 0x7f15f7aa1640>
>>> {a: 1} # This is fine
{<__main__.A object at 0x7f15f7aa1640>: 1}
>>> pickle.loads(pickle.dumps({a: 1})) # The key of the dict is not the same anymore
{<__main__.A object at 0x7f15f7aa17f0>: 1}

This actually has the effect on cachier, that the cache does not work, if one of the arguments is an user-defined object.

elguitar avatar Nov 21 '20 21:11 elguitar