Decorators in Python is basically meta programming. To understand decorators in Python, some things will be clear:
function are high-order objects
you can pass functions as arguments
you can declare inner functions
Now, it’s elementary to create one decorator:
import time
def time_execution(function):
def wrapper():
start_time = time.time()
function()
end_time = time.time()
print("[{function}] Time Execution: {total_time}".format(
function=function.__name__,
total_time=str(end_time - start_time))
)
return wrapper
@time_execution
def main():
for n in range(0, 10000000):
pass
main()
First thing, we import the module time. Second, we use the sugar syntax “@”. This indicates to the Python that is a decorator. The core is the function “time_execution”. Her reception on function and involves the real function, called of “wrapper”. So, you first decorator works fine.
and that’s all folks!
If you have any doubts, problems or suggestions, just leave a message.