Member-only story
Why You Should Use Python Decorator
Introduction
Decorator is one of the very important features in Python, and you may have seen it many places in Python code, for instance, the functions with annotation like @classmethod, @staticmethod, @property etc. By definition, decorator is a function that extends the functionality of another function without explicitly modifying it. It makes the code shorter and meanwhile improve the readability. In this article, I will be sharing with you how we shall use the Python decorators.
Basic Syntax
If you have checked my this article about the Python closure, you may still remember that we have discussed about Python allows to pass in a function into another function as argument. For example, if we have the below functions:
add_log — to add log to inspect all the positional and keyword arguments of a function before actually calling it
send_email — to accept some positional and keyword arguments for sending out emails
def add_log(func):
def log(*args, **kwargs):
for arg in args:
print(f"{func.__name__} - args: {arg}")
for key, val in kwargs.items():
print(f"{func.__name__} - {key}, {val}")
return func(*args, **kwargs)
return log