Search code examples
pythonfunctiondecorator

how i can change my function into decorator python?


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


Solution

  • 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")