Decorators In Python & How To Understand Them
# A step by step walkthrough

@something
def your_function(a, b):
# stuff^ You’ve probably seen something like this. The @something on top of our function is known as a decorator.
What The @ Means
Let’s say we have a simple function and a simple decorator.
@my_decorator
def my_function(x):
# stuffThis is the exact same as the following code:
def my_function(x):
# stuff
my_function = my_decorator(my_function)The @ simply provides us a way to make our code look more pretty. But what it is actually doing is in the second code block.
What a Decorator is
A decorator is a function that:
- Takes in a function
- Returns another function
Decorators are used to change how a function behaves.
def greet(name):
return 'hello ' + name^ Here, we have a simple greet function.
def add_exclamation(function):
def inner(*args):
return function(*args) + '!'
return inner
# ^ this function is a decorator function
# it adds one ! after its input function's return value^ and here, we have a simple decorator. Remember, a decorator itself is a function. It just takes in a function, and returns another function.
def add_exclamation(function):
def inner(*args):
return function(*args) + '!'
return inner
@add_exclamation
def greet(name):
return 'hello ' + name
print(greet('tim')) # hello tim!^ Our decorator and decorated function in action.
@add_exclamation
@add_exclamation
def greet(name):
return 'hello ' + name
print(greet('tim')) # hello tim!!^ Note that we can decorate a function more than once.
How This Works
@add_exclamation
def greet(name):
return 'hello ' + name
# THIS IS THE SAME AS
greet = add_exclamation(greet)def add_exclamation(function):
def inner(*args):
return function(*args) + '!'
return inner
# Tracing add_exclamation(greet)
function = greet
# inner becomes
def inner(*args):
return greet(*args) + '!'
# here is where the ! is added
# inner is then returned# Essentially
greet = inner
# where inner is
def inner(*args):
return greet(*args) + '!'And that is how decorators work on a very basic level.
Conclusion
Hope this was clear and helpful
Some Final words
If this story provided value to you, and you wish to show support, you could:
- Clap multiple times for this story (this really helps me out!)
- Consider signing up for a Medium membership using my link — it’s $5 per month and you get to read unlimited stories on Medium.
Sign up using my link here to read unlimited Medium articles.
Get my free Ebooks: https://zlliu.co/books
I write Python articles (sometimes other stuff) that the younger me would have wanted to read. Do join my email list to get notified whenever I publish.
More content at PlainEnglish.io.
Sign up for our free weekly newsletter. Follow us on Twitter, LinkedIn, YouTube, and Discord.
Interested in scaling your software startup? Check out Circuit.
