How to Implement Time-Based Cache in Python: Best Practices and Examples?

20 Replies, 1201 Views

Yo! If you’re trying to implement time-based cache Python, I’d say go with `cachetools` like others mentioned. But if you wanna roll your own, you can combine `@lru_cache` with a timestamp check.

Something like this:

```python
import time
from functools import lru_cache

cache = {}
CACHE_TTL = 300 # 5 minutes

def get_cached_value(key):
if key in cache and time.time() - cache[key]['timestamp'] < CACHE_TTL:
return cache[key]['value']
return None
```

It’s a bit manual but works if you don’t wanna add extra dependencies.

Messages In This Thread



Users browsing this thread: 1 Guest(s)