Today I Learned

A Hashrocket project

Decorator Factory vs Decorator

I’ve discovered decorator factories and they are cool!

Decorating a function in python is easy. Watch as I yell when a function gets called.

def yell(func):
    def yeller(*args):
        print("YARGH")
        func(*args)
    return yeller

@yell
def hi(name):
    print(f'hi {name}')

hi("Bob")
# YARGH
# hi Bob

What if I always wanted to say hi to Bob, and wanted to configure that via a decorator. Could I do that?

@yell("Bob")
def hi(name):
    print(f'hi {name}')

# TypeError: 'str' object is not callable

Instead of just passing an argument to a decorator, I need to create a function that will return a decorator, a decorator factory.

def yell(name):
    def decorate(func):
        def yeller():
            print("YARGH")
            func(name) 
        return yeller
    return decorate

@yell("Bob")
def hi(name):
    print(f'hi {name}')

hi()
# YARGH
# hi Bob

So this time, I created a function that returned a decorator which in turn returns a function that wraps the decorated function and calls the decorated function with the argument passed in to the decorator factory. Very russion doll. Fun.