Why You Should Use Python Decorator

<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

Basic Syntax

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
def send_email(subject, to, **kwargs):
#send email logic
print(f"email sent to {to} with subject {subject}.")
sender = add_log(send_email) 
sender("hello", "contact@codeforests.com", attachment="debug.log", urgent_flag=True)

Python decorator as a function

class PermissionDenied(Exception): 
pass
def permission_required(func):
whitelist = ["John", "Jane", "Joe"]
def wrapper(*args, **kwargs):
user = args[0]
if not user in whitelist:
raise PermissionDenied
func(*args, **kwargs)

return wrapper
@permission_required 
def read_file(user, file_path):
with open(file_path, "r") as f:
#print out the first line of the file
print(f.readline())
read_file("John", r"C:\pwd.txt")
read_file("Johnny", r"C:\pwd.txt")

Use of the functools.wraps

from functools import wraps 
def permission_required(func):
...
@wraps(func)
def wrapper(*args, **kwargs):
...
return wrapper

Python decorator as a class

from functools import update_wrapper class PermissionRequired: 
def __init__(self, func):
self._whitelist = ["John", "Jane", "Joe"]
update_wrapper(self, func)
self._func = func
def __call__(self, *args, **kwargs):
user = args[0]
if not user in self._whitelist:
raise PermissionDenied
return self._func(*args, **kwargs)
@PermissionRequired def read_file(user, file_path): 
with open(file_path, "r") as f:
#print out the first line of the file
print(f.readline())

Conclusion

Resources and tutorials for python, data science and automation solutions

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store