Home > Back-end >  how i can change my function into decorator python?
how i can change my function into decorator python?

Time:09-27

in this code i checking the email and password validation

if email ends with {@gmail.com} and password length is 8 i print (hello user)

def login(email, password):
   valid_mail = "@gmail.com"
   print()
   if email[-10:] == valid_mail and len(str(password)) == 8:
       print(f'hello  {email} welcome back')
   else:
       print("invalid user")

now i want to change my login function to

def login(email, password):
  print(f' welcome {email }')

and with decorator function checking the condition if its true then print login function ,

def my_decorator(func):
    def wrapper_function(*args, **kwargs):
        if email[-10:] == "@gmail.com" and len(str(password)) == 8:
            return wrapper_function
        else:
            print("not user")
        return func(*args, **kwargs)

    return wrapper_function

i know it's wrong solution , i just learning python and a little confused ) please help me

CodePudding user response:

>>>
>>>
>>> email = ' [email protected]   '
>>> email.endswith('@gmail.com')
False
>>>
>>> email.strip()
'[email protected]'
>>>
>>> email.strip().endswith('@gmail.com')
True
>>>


def login(email):
    user = email.split('@')[0]
    print('hello ',user)

def my_decorator(email,password):
    email = email.strip()


    if email.endswith('@gmail.com') and len(password) == 8:
        login(email)
    else:
        print("invalid user")
    
my_decorator('[email protected]','@1234567')

my_decorator('[email protected]','123456789')

CodePudding user response:

A decorator can be implemented as a function with an inner function that act as a wrapper. The decorator takes in a function, wraps it, calls the input function, then returns the wrapper:

from functools import wraps


def my_decorator(func):
    
    @wraps(func)
    def wrapper_function(*args, **kwargs):
        email = kwargs.get("email", "")
        password = kwargs.get("password", "")
        
        if email[-10:] == "@gmail.com" and len(str(password)) == 8:
            func(**kwargs)
        else:
            print("not user")
            
    return wrapper_function

@my_decorator
def login(email, password):
    print(f' welcome {email}')


login(email="[email protected]", password="01234567")

You may also want to take a look at functools.wraps, which is a decorator itself and how it avoids replacing the name and docstring of the decorated function with the one of the wrapper.

  • Related