Decorators with parameters – Fizz Buzz game

First, I will define a numbers function that returns a dictionary, where the keys are integers in the range given as the argument to the function (from start to end inclusive).

numbers() function source code:

def numbers(start, end):
    dict = {}
    for number in range(start, end + 1):
        dict[number] = ''
    return dict

The function can be modified using the decorators with parameters.

My decorator function that modifies dictionary values:

def fizzbuzz(number, message):
    def decor(func):
        def wrapper(*args):
            dict = func(*args)
            for key in dict:
                if not (key % number):
                    dict[key] += message
            return dict
        return wrapper
    return decor

Function numbers() definition with the decorator:

@fizzbuzz(5, 'BUZZ')
@fizzbuzz(3, 'FIZZ')
def numbers(start, end):
    dict = {}
    for number in range(start, end + 1):
        dict[number] = ''
    return dict

Calling the numbers function will not change, e.g. to display dictionary values ​​with keys from 0 to 15:

print(numbers(0, 15))

Modification by using a decorator is done behind the scenes.

Leave a Reply

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