Why Does Functools.lru_cache Not Cache __call__ While Working On Normal Methods
Solution 1:
This is due to the difference between class attributes and instance attributes. When accessing an attribute (such as method
) python first checks for an instance attribute. If you have not assigned to self.method
it will not find one. Then class attributes are checked, which is equivalent to self.__class__.method
. The value of this function is not changed by assigning to self.method
, that only updates the instance attribute.
However, b(1)
becomes b.__class__.__call__(b, 1)
which uses the original class definition of __call__
and b.__call__(1)
will be cached the same way as method
since it uses the instance definition.
Solution 2:
The original answer is really good.
I am attaching another solution of the problem.
methodtools.lru_cache
will work as you expect.
from methodtools import lru_cache
classtest:
@lru_cachedef__call__(self, x):
print('__call__', end=' ')
return x
It requires to install methodtools
via pip:
pip install methodtools
Post a Comment for "Why Does Functools.lru_cache Not Cache __call__ While Working On Normal Methods"