#20 - Python Decorators

#20 - Python Decorators

By Ifeanyi Omeata


Topics:


1. Using Decorators
2. Using multiple Decorators on a single function
3. Using Decorators with parameters
4. Using a Decorator for multiple functions
5. Using functools.wraps
6. Using Decorators on Class methods
7. Call Method
8. Defining a Decorator Class


1. Using Decorators


>>Return to Menu
Decorators change the behaviour of existing functions or Classes. Decorator is any callable Python object that is used to modify a function or a Class.

def decorator_div(func):
    def wrapper(a,b):
        if a < b:
            a,b = b,a
        return func(a,b)
    return wrapper

@decorator_div
def div(a,b):
    return a/b

#div = div_decorator(div)
print(div(2,4))

image.png


2. Using multiple Decorators on a single function


>>Return to Menu

def split_div(func):
    def wrapper():
        str = func()
        return str.split()
    return wrapper

def upper_div(func):
    def wrapper2():
        str2 = func()
        return str2.upper()
    return wrapper2

@split_div
@upper_div
def greeting():
    return "good morning"

#div = div_decorator(div)
print(greeting())

image.png


3. Using Decorators with parameters


>>Return to Menu

def greeting_decorator(expr):
    def wrapper(func):
        def inner():            
            return f"{expr}, {func()}"
        return inner
    return wrapper

@greeting_decorator('Hello')
def greeting():
    return "good morning"

#div = div_decorator(div)
print(greeting())

image.png


4. Using a Decorator for multiple functions


>>Return to Menu

def solve_decorator(func):
    def wrapper(*args):
        list1 = []
        list1 = args[1:]
        for i in list1:
            if i==0:
                return "Give proper input!!!"
        return func(*args)    
    return wrapper

@solve_decorator
def sol1(a,b):
    return a/b

@solve_decorator
def sol2(a,b,c):
    return a/b/c

print(sol1(10,5))
print(sol2(10,0,5))

image.png


5. Using functools.wraps


>>Return to Menu
Without functools.wraps:

import functools

def decorator_greet(func): 
    #@functools.wraps(func)
    def inner():
        sttr = func()
        return sttr.upper()
    return inner

@decorator_greet
def greet():
    return "good morning"

print(greet.__name__)
print(greet())

image.png With functools.wraps:

import functools

def decorator_greet(func): 
    @functools.wraps(func)
    def inner():
        sttr = func()
        return sttr.upper()
    return inner

@decorator_greet
def greet():
    return "good morning"

print(greet.__name__)
print(greet())

image.png


6. Using Decorators on Class methods


>>Return to Menu

def check_user(method):
    def wrapper(self_w):
        if self_w.name == 'Bob':
            return "Hey, you are the admin: 'Bob'."
        else:
            return method(self_w)
    return wrapper

class Auth:
    def __init__(self,name):
        self.name = name
    @check_user
    def report(self):
        return f"Entered user is: {self.name}."    

user = Auth("James")
print(user.report())

user = Auth("Bob")
print(user.report())

image.png


7. Call Method


>>Return to Menu
This is used to call an object in method form.

class Auth:
    def __init__(self,name):
        self.name = name

    def __call__(self):
        return f"Entered user is: {self.name}."    

user = Auth("James")
print(user())

image.png


8. Defining a Decorator Class


>>Return to Menu

class Auth_decorator:
    def __init__(self,func):
        self.func = func
    def __call__(self):
        return self.func().upper()    

@Auth_decorator
def greeting():
    return "good morning"

print(greeting())

image.png

Another Example:

class Validate_decorator:
    def __init__(self,func):
        self.func = func
    def __call__(self,*args, **kwargs):
        list1 = []
        list1 = args[1:]  
        for i in list1:
            if i == 0:
                return "Error: You can't divide by Zero."
        return self.func(*args, **kwargs)

@Validate_decorator
def operator(a,b):
    return a/b

@Validate_decorator
def operator2(a,b,c):
    return a/b/c

print(operator(10,0))
print(operator(10,2))
print(operator2(10,5,0))
print(operator2(10,2,2))

image.png

#End


Hope you enjoyed this! :) Follow me for more contents...


Get in Touch:
ifeanyiomeata.com

Youtube: youtube.com/c/IfeanyiOmeata
Linkedin: linkedin.com/in/omeatai
Twitter: twitter.com/iomeata
Github: github.com/omeatai
Stackoverflow: stackoverflow.com/users/2689166/omeatai
Hashnode: hashnode.com/@omeatai
Medium: medium.com/@omeatai
© 2022