Member-only story
Python decorators: The Magic in Your Code
Decorators are common in Python’s world. You can see them in Django, Flask, FastAPI, etc. You can also create your own or use built-in decorators. So, it’s good to know how they work to have a better understanding of how they are used, for example, in web frameworks.
A decorator is a callable that takes another function as an argument (the decorated function).
A decorator may perform some processing with the decorated function, and returns it or replaces it with another function or callable object.
Basics
def greeter(say_hi):
def wrapper():
print("running wrapper() start")
print(say_hi)
print("running wrapper() end")
return wrapper()
greeter("Hey buddy")
"""
running wrapper() start
Hey buddy
running wrapper() end
"""
Cool, we just nested a function inside another function and called the nested function from within the outer function. So what?
def greeter(say_hi):
def wrapper():
print("running wrapper() start")
print(say_hi)
print("running wrapper() end")
return wrapper
result = greeter("Hey buddy")
print(result) # <function greeter.<locals>.wrapper at 0x1022909a0>