Posts about decorators
- decorators 1 (this one)
- decorators 2 – arguments to decorator
- decorator 3 – more complex decorator
- decorator 4 – reduce to extend functionality with decorators
One useful things are decorators. At the beginning can be a little intimidating and can confuse you, but are very simple to use once you get them. I made the most simple script I could make for this tutorial (code on github repository python_cheatsheet/decorator.py).
What is a decorator?
It is a function/decorator that can be used more times by different functions using simply a @ and the function name before the function that want to use the decorator
The flow chart of the usage of decorator:
- make a decorator function that gets another function as argument and that has an inner function that has the arguments of the other function
- the decorator function returns the innerfunction
- the other functions have the @ followed by the name of the decorator funcion before the def statement
- when you call the other functions, they will be passed to the decorator and the arguments will be passed to the inner function of the decorator
- the code in the other functions is executed
- the code in the inner function of the decorator is excuted
This way all the other functions will use the same code in the decorator in common, saving code and organizing code better. The code is also more mantainable.
The example
# decorators def print_it(fn): def show_result(a, b): print(f"{fn.__name__}({a},{b}) is = to {fn(a, b)}") return show_result @print_it def add(a, b): return a + b @print_it def subt(a, b): print("This is subt") return a - b @print_it def mult(a, b): print("This is mult") return a * b @print_it def div(a, b): print("This is div") return a // b # add(5, 4) # 9 # print("Let's go to the other one") # subt(2, 3) # -1 div(10, 5)
output
This is div div(10,5) is = to 2 >>>
The video
Subscribe to the newsletter for updates
Tkinter templates
My youtube channel
Twitter: @pythonprogrammi - python_pygame