How to replace (instead of fully recomputing) memoized results in Flask-Cache

  flask, flask-cache, python

Let’s say I want users to complete an action every day, so I keep track of a current_streak and longest_streak.

current_streak = get_current_streak(user_id)
longest_streak = get_longest_streak(user_id)

Instead of recomputing the longest_streak every time the user asks for it, I cache it indefinitely, and recompute it only when I see that current_streak exceeds the longest_streak

@cache.memoize(timeout=99999)
def _get_longest_streak(user_id: int) -> int:
    pass

def get_longest_streak(user_id: int) -> int:
    current_streak = get_current_streak(user_id)
    longest_streak = _get_longest_streak(user_id)

    if current_streak > longest_streak:
        cache.delete_memoized(_get_longest_streak, user_id)
        return _get_longest_streak(user_id)
    
    return longest_streak

But it seems I could do this more efficiently with something like this:

def get_longest_streak(user_id: int) -> int:
    current_streak = get_current_streak(user_id)
    longest_streak = _get_longest_streak(user_id)

    if current_streak > longest_streak:
        cache.replace_memoized(_get_longest_streak, user_id, current_streak) # <--
        return _get_longest_streak(user_id)
    
    return longest_streak

Is it possible? Worthwhile? Or am I looking for needless optimizations?

Source: Python Questions

LEAVE A COMMENT