Decorators in python.

What is a Decorator?

A decorator is a small function that takes another function as an argument and returns a new function that “wraps” the original function. The new function produced by the decorator is then called instead of the original function when it’s invoked.

Syntax:
@decorator_name
def function_to_decorate():
    pass

How Decorators Work

Here’s a step-by-step breakdown of how decorators work:

  1. Define a decorator function: You define a function that takes another function as an argument. This function is the decorator.
  2. Apply the decorator: You apply the decorator to a function or class using the @ syntax.
  3. Create a new function: The decorator function returns a new function that wraps the original function.
  4. Replace the original function: The new function returned by the decorator replaces the original function.
  5. Call the decorated function: When you call the decorated function, you call the new function returned by the decorator.
Example: A Simple Decorator.
def log_calls(func):
    def wrapper(*args, **kwargs):
        print(f"Calling {func.__name__} with arguments {args} and {kwargs}")
        result = func(*args, **kwargs)
        print(f"{func.__name__} returned {result}")
        return result
    return wrapper

@log_calls
def add(a, b):
    return a + b

result = add(2, 3)
print(result)
Output:
Calling add with arguments (2, 3) and {}
5
add returned 5
5

 

Leave a Comment

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

Scroll to Top