how i can change my function into decorator python?

Question:

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

Asked By: Adulik

||

Answers:

>>>
>>>
>>> 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')
Answered By: islam abdelmoumen

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:

from functools import wraps


def my_login_decorator(func):
    
    @wraps(func)
    def wrapper_function(*args, **kwargs):
        email = kwargs.get("email", "")
        password = kwargs.get("password", "")
        password_required_length = 8

        if email.endswith("@gmail.com") and
        len(password) == password_required_length:
            func(**kwargs)
        else:
            print("not user")
            
    return wrapper_function

@my_login_decorator
def login(email: str, password: str) -> None:
    print(f' welcome {email}')


login(email="[email protected]", password="01234567")
Answered By: Jonathan Ciapetti
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.