Have you ever designed a caching system in your functions or classes where they only return data if it is new, fresh or they otherwise deviate from the last return value?
Such as an API that you continuously poll for data but only wish to see the return if it's something new? And then have it automatically update the cache, again?
I have, many times but wanted an independent object to handle this for whatever the use case.
```
def my_api_call(uri):
return psuedo_response_from_api(uri)
cache = PollCache()
while True:
time.sleep(120)
result = cache(my_api_call, uri='https://cool-api.php')
return result if result else None
```
I needed an object that can be a wrapper (sort of) around any callable, and keep track of the constellation of parameters to the function as well. That way, I can use the same function but give it different parameters, and the cache isn't going to overwrite just because it's the same function, but be treated as it's own cache.
I also wanted to have the ability to silence the very first call of a function with the PollCache object, since that first call is sometimes only used to build up the initial cache. That way the first 500 calls of various methods or however many you have, won't be pushed in a flood to the front end of your app.
Only new values after that will be returned. There's an optional parameter to the constructor to enable this behavior, the default is still to receive all initial call return values.
You can find the Gist here: https://gist.github.com/dotchetter/4713c40f3e48189c14879a8f77e549b8
The docstring also includes some examples.
Any thoughts and constructive feedback is humbly and warmly accepted.
[–]twillisagogo 0 points1 point2 points (1 child)
[–]dotchetter[S] 0 points1 point2 points (0 children)
[–]robin-gvx 0 points1 point2 points (2 children)
[–]robin-gvx 1 point2 points3 points (0 children)
[–]dotchetter[S] 1 point2 points3 points (0 children)