Be careful while using @lru_cache on the method

Don’t just cache everything

Be careful while using @lru_cache on the method
Photo by Kelly Sikkema on Unsplash

There are a few reasons why you might not want to use the @lru_cache decorator in a class method.

First, the @lru_cache decorator is intended for use with pure functions, meaning functions that always return the same output for a given input and have no side effects. Class methods are not necessarily pure, since they can have side effects and their behavior can depend on the state of the object they are called on. Using @lru_cache on a non-pure class method could lead to unexpected results, such as cached return values that are no longer valid because the object's state has changed.

Second, the @lru_cache decorator only works on functions that have positional arguments. If a class method is called with keyword arguments, @lru_cache will not cache the return value, and the method will be executed every time it is called. This could result in poor performance if the method is computationally expensive.

Finally, using @lru_cache on a class method can make the behavior of the method difficult to understand, since the caching behavior is not explicitly stated in the method's definition. This can make the code more difficult to read and maintain.

In general, it is best to avoid using @lru_cache on class methods unless you are sure that the method is pure and will always be called with positional arguments. Instead, you can use the functools.lru_cache function directly to cache the return value of the method, but this will require you to manage the cache manually.

Subscribe to CodeCraft by Anyesh | Programming, ML & AI Tutorials

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe