Member-only story

Why You Should Use Python Decorator

codeforests
5 min readAug 7, 2020

--

<span>Photo by <a href=”https://unsplash.com/@wsheng1011?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCo
Photo by Han Wei Sheng on Unsplash

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

--

--

codeforests
codeforests

Written by codeforests

Resources and tutorials for python, data science and automation solutions

No responses yet