Advanced Lesson 4
Python Decorators
Chapter 2: Python decorators
Don't repeat yourself
Here is our decorator from the previous page again:
1 2 3 4 5 6 |
|
And we have decided that our gift should always be wrapped for Christmas:
1 2 3 4 5 6 |
|
In the code above, you might notice yourself saying gift
over and over. Line 4 alone has two mentions of gift
! As much as I love gifts, let’s try to reduce the repetition.
In Python, you can replace Line 4 by annotating gift()
with @christmas_decorator
instead. So the following code is the same as the one above.
1 2 3 4 5 |
|
Try this out yourself! You will see that your gift will be Christmas-ready! 🎄🎁
As a summary, a @decorator
on a func_name()
is a cleaner way of writing func_name = decorator(func_name)
! That’s it really!