Understanding Python Decorators
Decorators are not magic, they are functions that wrap functions. Here is the mental model that finally made them click for me. Decorators confused me for a long time because every tutorial I read started with the @ syntax and worked backward to explain what it does. The @ symbol is the last thing to learn, not the first. A decorator is a function that takes a function and returns a function. Everything else follows from that single sentence. Once I internalized it, the @ syntax stopped being mysterious. Functions Are Values The prerequisite to understanding decorators is understanding that functions in Python are values, just like integers or strings. You can assign a function to a variable, pass it as an argument, and return it from another function. This is not a special feature of decorators; it is how Python works. def greet(name): return f'Hello {name}' say_hello = greet # assign the function to a new name print(say_hello('Alice')) # Hello Alice # Pass a function as an argument def apply(func, value): return func(value) print(apply(greet, 'Bob')) # Hello Bob Once you accept that a function can be passed around, a decorator is…