Memoization in Python using decorators

In this tutorial, you are going to learn about Memoization using decorators with Python code examples.

What is Memoization?

Memoization is an approach of listing transitional results. It is used to avoid frequent calculations to accelerate program execution and also used to improve the program that uses recursion.

What is the Decorator?

A decorator is a design pattern that is used to add functionality to the code without changing its structure. Decorators are called before the function which you want to decorate with new functionality.

def memoizeexample(a):
    transitionalresult = {}
    def vary(x):
        if x not in transitionalresult:            
            transitionalresult[x] = a(x)
        return transitionalresult[x]
    return vary
def fibonacci(num):
    if num == 0:
        return 0
    elif num == 1:
        return 1
        return fibonacci(num-1) + fibonacci(num-2)


After we run the code, we will able to see the output given below:

Fibonacci(10) = 55

Fibonacci(20) = 6765

Program Explanation:

Now let’s see what we did in our code step by step:

  1. Create a function named memoizeexample with passing arguments. It stores transitional results in created memory named transitionalresult.
  2. Create another function named vary which is used to access the transitionalresult memory.
  3. If variable x is not present in memory it equals the transitionalresult and first definition. It returns the transitionalresult and returns vary.
  4. Create another function named fibonacci with passing argument num.
  5. If num equals zero it returns zero.
  6. If num equals to one it returns one.
  7. Otherwise, it returns the addition of number which is subtracted with -1 and subtracted with -2.
  8. Print Fibonacci of the number which you want by entering the number.


This is about the explanation of Memoization and Decorators in Python. I hope, you understood and learn something useful.

Leave a Reply

Your email address will not be published. Required fields are marked *