PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, October 18, 2022

[FIXED] how i can change my function into decorator python?

 October 18, 2022     decorator, function, python     No comments   

Issue

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

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_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="johnsmith@gmail.com", 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.



Answered By - Jonathan Ciapetti
Answer Checked By - Marilyn (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing