Decorator

noun

say it: “DEK-uh-ray-ter” /ˈdɛkəˌreɪtər/

Something that wraps extra behavior around a function without changing the function's own code, applied with @name on the line above it.

What is a decorator?

A decorator wraps extra behavior around a function without changing the function's own code. You apply it with @name on the line above.

def log_call(func):
    def wrapper(*args):
        print(f"Calling {func.__name__}")
        return func(*args)
    return wrapper

@log_call
def place_order(item):
    print(f"Ordered {item}")

place_order("pizza")  # Calling place_order, then Ordered pizza

In a sentence

  • “@dataclass is a decorator that writes methods for a class.”
  • “The @log_call decorator prints a line every time place_order runs.”

Level: Freelancer · More Python terms at this level

Updated