LRU + Time Expiration Decorator
00:00 In the previous lesson, I went off on a tangent and showed you how to write a decorator that takes arguments. In this lesson, I’ll be putting that into practice by writing a new LRU decorator that has time-based expiration.
00:15 Some data is time sensitive, and you don’t want to return it if it isn’t valid anymore. Think back to my example of a news site on the Web. The cache is handy for the logo, but if it caches the headline for too long, you might be reading about the Leafs winning the Cup. Okay, that’s a very specific hockey reference, and given the Web wasn’t invented the last time they won the Cup, it is impossible. Data could be stale is my point. Anyhow, to fix this, you want to include both LRU info as well as time-based info in your caching policy. Let’s go write some code that does just that.
Instead of writing my own LRU implementation, here I’m using the LRU call as a function. Notice how it gets invoked. The
maxsize argument goes first, then in a separate set of parentheses, the function being wrapped is given.
01:21 Think back to the previous lesson. When you’re implementing a decorator, its argument is the thing being wrapped. When you’re implementing a decorator with arguments, the argument is the decorator’s argument.
As I don’t need to store a reference to the thing being wrapped, I just replaced the thing being wrapped with the wrapped thing. Yeah, that was clear. When this line is called, the original function will be replaced with the wrapped function and the
func() will point the wrapped thing.
@lru_cache added a
.CacheInfo() method to the function being wrapped? It could do that because functions are objects. Well, I’m doing the same thing here. Instead of adding a method, I’m adding an attribute. That attribute is the lifetime of the cache as a
These lines are the pre-condition. They’ll get called before each invocation of the wrapped function. The pre-condition checks whether the cache has expired. If it has, then it uses the LRU cache’s
.cache_clear() method and sets a new expiration timestamp. After this, the actual LRU function gets invoked.
Become a Member to join the conversation.