Implementing Before and After Logging in a Function Using a Decorator

Here’s an example of how you can write a decorator to execute logic before and after the original method:

import time

def login_execution(function):
    
    def my_custom_wrapper(*args, **kwargs):
          
            print("before the request is executed")
            #do some modifications if needed
            if args and args[0] == "news_paper":
                kwargs['published_year'] = 2024
            #call the original function
            result = function(*args, **kwargs)
            
            print("after the original code")
            
            return result
    return my_custom_wrapper
    
      
@login_execution
def hello_decorator(*args, **kwargs):
     # *args is a tuple of positional arguments
    print("Positional arguments (args):", args)
    

login_execution(function):

  • This is a decorator function. It takes the function it decorates (in this case, hello_decorator) as its parameter (function).

my_custom_wrapper(*args, **kwargs):

  • This inner function wraps the original function (hello_decorator). It takes in all positional (*args) and keyword arguments (**kwargs), passes them to the original function, and adds extra behavior before and after the original function call.

Pre-execution logic:

  • It prints "before the request is executed".

Argument modification:

  • If the first positional argument is "news_paper", it modifies the keyword argument published_year to 2024. So, it changes any input year (in this case, 2023 becomes 2024).

Calling the original function:

  • The decorator calls the original function with the possibly modified arguments.

Post-execution logic:

  • After the original function runs, it prints "after the original code".

In this example, you’re creating a decorator named login_execution that wraps around the hello_decorator function, modifying its behavior by adding some actions before and after the original function executes.

Let’s break it down step by step:

1. The Decorator Function (login_execution):

pythonCopy codedef login_execution(function):
    def my_custom_wrapper(*args, **kwargs):
        # Pre-execution behavior
        print("before the request is executed")
        
        # Modify arguments if needed
        if args and args[0] == "news_paper":
            kwargs['published_year'] = 2024  # Modify the keyword argument

        # Call the original function with the modified arguments
        result = function(*args, **kwargs)
        
        # Post-execution behavior
        print("after the original code")
        
        return result
    return my_custom_wrapper
  • login_execution(function):
    • This is a decorator function. It takes the function it decorates (in this case, hello_decorator) as its parameter (function).
  • my_custom_wrapper(*args, **kwargs):
    • This inner function wraps the original function (hello_decorator). It takes in all positional (*args) and keyword arguments (**kwargs), passes them to the original function, and adds extra behavior before and after the original function call.
  • Pre-execution logic:
    • It prints "before the request is executed".
  • Argument modification:
    • If the first positional argument is "news_paper", it modifies the keyword argument published_year to 2024. So, it changes any input year (in this case, 2023 becomes 2024).
  • Calling the original function:
    • The decorator calls the original function with the possibly modified arguments.
  • Post-execution logic:
    • After the original function runs, it prints "after the original code".

2. Decorating the Function (hello_decorator):

pythonCopy code@login_execution
def hello_decorator(*args, **kwargs):
    # *args is a tuple of positional arguments
    print("Positional arguments (args):", args)
    
    # **kwargs is a dictionary of keyword arguments
    print("Keyword arguments (kwargs):", kwargs)
  • @login_execution:
    • This decorator modifies the behavior of hello_decorator. When hello_decorator is called, it will first go through login_execution and the my_custom_wrapper function instead of directly running its original code.
  • hello_decorator(*args, **kwargs):
    • This function simply prints out the positional arguments (*args) and keyword arguments (**kwargs) it receives.

3. Executing the Decorated Function:

pythonCopy codehello_decorator("news_paper", published_year=2023)

When you call hello_decorator("news_paper", published_year=2023), the following sequence happens:

  1. Pre-execution (inside the decorator):
    • It prints: "before the request is executed".
    • Since the first positional argument ("news_paper") matches the condition, the published_year is modified from 2023 to 2024.
  2. Original Function (hello_decorator):
    • The original function now runs with the modified arguments:
      • Positional argument: ("news_paper",)
      • Keyword argument: {'published_year': 2024}
    • It prints:
      • "Positional arguments (args): ('news_paper',)"
      • "Keyword arguments (kwargs): {'published_year': 2024}"
  3. Post-execution (inside the decorator):
    • It prints: "after the original code".

Final Output:

arduinoCopy codebefore the request is executed
Positional arguments (args): ('news_paper',)
Keyword arguments (kwargs): {'published_year': 2024}
after the original code

Key Points:

  • Before and after execution: The decorator adds logic before and after the original function executes.
  • Argument modification: The decorator checks and modifies the arguments passed to the function if needed.
  • Wrapper function: The my_custom_wrapper function wraps the original function and controls when and how it runs.

This example showcases how decorators can be used to extend or modify the behavior of a function without changing its core implementation.

Leave a Reply

Your email address will not be published. Required fields are marked *

Deprecated: htmlspecialchars(): Passing null to parameter #1 ($string) of type string is deprecated in /var/www/html/wp-includes/formatting.php on line 4720