Chapter 2: Python decorators

Decorators with parameters

face Josiah Wang

What if our decorator itself needs some arguments? For example, I might want to allow the decorator to repeat a function an arbitrary number of times.

Well, that requires a bit more work. You will have to wrap your decorator further in another function. Don’t worry too much about this one - you will unlikely need to do this! (My head is spinning too!)

def n_repeat(times):
    def repeat(func):
        def wrapper(*args, **kwargs):
            for i in range(times):
                func(*args, **kwargs)
        return wrapper
    return repeat

@n_repeat(5) # Pass in times as argument
def greet(message, firstname, lastname):
    print(f"{message}, {firstname} {lastname}!")

@n_repeat(times=3) # You can also use keyword arguments
def sing(line):
    print(line)

sing("We wish you a Merry Christmas...")
greet("Happy New Year", "Josiah", "Wang")

print(sing) # <function n_repeat.<locals>.repeat.<locals>.wrapper at 0x7f9e0198c430>

You should get "We wish you a Merry Christmas..." repeated 3 times, and "Happy New Year, Josiah Wang!" repeated 5 times.