Wednesday, February 28, 2024

Python Decorator

 In Python, a decorator is a design pattern that allows you to extend or modify the behavior of functions or methods without modifying their actual code. Decorators are applied using the @decorator syntax and are a concise way to wrap a function or method with additional functionality.

It helps you to off/on some functionality.


def log_function_call(func):
def wrapper(*args):
print(f"Calling {func.__name__} with arguments {args}")
result = func(*args)
print(f"{func.__name__} execution completed.")
return result
return wrapper

@log_function_call
def add_numbers(a, b):
return a + b

@log_function_call
def multiply_numbers(x, y):
return x * y

# Calling decorated functions
result_add = add_numbers(3, 5)
print(result_add)
result_multiply = multiply_numbers(
4, 6)
print(result_multiply)

Output:
Calling add_numbers with arguments (3, 5)
add_numbers execution completed.
8
Calling multiply_numbers with arguments (4, 6)
multiply_numbers execution completed.
24

Now if we comment out the decorator,
def log_function_call(func):
def wrapper(*args):
print(f"Calling {func.__name__} with arguments {args}")
result = func(*args)
print(f"{func.__name__} execution completed.")
return result
return wrapper

# @log_function_call
def add_numbers(a, b):
return a + b

# @log_function_call
def multiply_numbers(x, y):
return x * y

# Calling decorated functions
result_add = add_numbers(3, 5)
print(result_add)
result_multiply = multiply_numbers(
4, 6)
print(result_multiply)

Output:
8
24

No comments:

Post a Comment