Don't repeat yourself
Here is our decorator from the previous page again:
def christmas_decorator(func):
def wrapper():
print("wrapping")
func()
print("with a Christmas-y wrapper")
return wrapper
And we have decided that our gift should always be wrapped for Christmas:
def gift():
print("a toy")
gift = christmas_decorator(gift)
gift()
In the code above, you might notice yourself saying gift
over and over. As much as I love gifts, letβs try to reduce the repetition.
In Python, you can save yourself from typing gift = christmas_decorator(gift)
by annotating gift()
with @christmas_decorator
instead. So the following code is the same as the above.
@christmas_decorator
def gift():
print("a toy")
gift()
Try this out yourself! You will see that your gift will be Christmas-ready! ππ