Python: function memoization

In this article we will see how to implement Python function memoization.

Memoization is a pattern aimed at optimizing the performance of a function that performs an expensive computational task. The principle behind this pattern involves the creation of a cache where we can store the results in order to avoid to repeat the task if the function input is the same.

We can implement such a pattern using a dictionary as a cache like this.

import math

func_cache = {}

def memoized_func(num=1):
    if num in func_cache:
        return func_cache[num]
    result = math.factorial(num)
    func_cache[num] = result
    return result    

Whenever the function is executed, if the input is already present in the dictionary as a key, its value is returned and the task is not executed. Conversely, if the key does not exist, the task is executed and the result is stored in the dictionary using the input value passed to the function as the key.

Back to top