Member-only story

Python decorators: The Magic in Your Code

Tomas Svojanovsky
4 min readJul 13, 2023

--

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.

Photo by Vinicius "amnx" Amano on Unsplash

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>

--

--

Tomas Svojanovsky
Tomas Svojanovsky

Written by Tomas Svojanovsky

I'm a full-stack developer. Programming isn't just my job but also my hobby. I like developing seamless user experiences and working on server-side complexities

No responses yet