Advertisement
Beginner Python, Decorators

What is a decorator, and how does the @decorator_name syntax relate to a plain function call?

Short answer

A decorator is a function that takes another function as input and returns a (usually modified or wrapped) function as output; `@decorator_name` above a function definition is pure syntactic sugar for `func = decorator_name(func)`, applied immediately after the function is…

Save Python mock interview
Advertisement
AModel answer
A decorator is a function that takes another function as input and returns a (usually modified or wrapped) function as output; `@decorator_name` above a function definition is pure syntactic sugar for `func = decorator_name(func)`, applied immediately after the function is defined.
def shout(func):
    def wrapper():
        return func().upper()
    return wrapper

@shout
def greet():
    return "hello"

print(greet())  # "HELLO" -- greet was replaced by shout's wrapper
Real-world example
Automatically adding logging, timing, or access-control behavior to a function without modifying its internal code.
Likely follow-ups
  • What is the exact equivalent, non-decorator-syntax way of writing '@shout' above 'def greet():'?
Related topics