Last active
November 25, 2015 17:11
-
-
Save mccutchen/80116aeeabeb71e6e582 to your computer and use it in GitHub Desktop.
Simple in-memory cache decorator with TTL
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| def cached(ttl, cache={}): | |
| """ | |
| A decorator for nullary functions that caches their results in memory for a | |
| given number of seconds. | |
| """ | |
| def cached_decorator(f): | |
| key = f.__name__ | |
| def decorated(*args, **kwargs): | |
| if key in cache: | |
| result, ts = cache[key] | |
| if time.now() - ts < ttl: | |
| return result | |
| result = f(*args, **kwargs) | |
| cache[key] = (result, time.now()) | |
| return result | |
| return decorated | |
| return cached |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment