Codzy

Decorators

In Python, a function is a value like any other: you can pass it to another function. A decorator is a function that takes a function and returns an improved version of it.

You apply it with @ right above the definition: @shout before def greet is the same as writing greet = shout(greet). It's used to add behaviour (timing, permission checks, logging…) without changing the original function.

def shout(func):
    def wrapper(name):
        return func(name).upper() + "!"
    return wrapper

@shout
def greet(name):
    return "hello " + name

print(greet("sara"))

Start the lesson