Python Decorators

 Python Decorators

Python decorators are a powerful feature that allows you to modify or extend the behavior of functions or classes without permanently modifying their code. They essentially wrap another function and allow you to execute code before and after the wrapped function runs. Decorators are widely used for adding functionalities like logging, authentication, caching, etc., to functions or methods.

Here's a basic example of a decorator:

Python Code

 def my_decorator(func):

    def wrapper():

        print("Something is happening before the function is called.")

        func()

        print("Something is happening after the function is called.")

    return wrapper


@my_decorator

def say_hello():

    print("Hello!")


say_hello()

In this example, my_decorator is a function that takes another function (func) as an argument and returns a new function (wrapper) that adds extra functionality around func. The @my_decorator syntax is a shorthand way of applying the decorator to the say_hello function.

When you call say_hello(), it will actually execute wrapper, which prints some messages, calls the original say_hello function, and then prints some more messages.

Decorators can also take arguments, which can add flexibility to their behavior. For instance:

Python Code

 def repeat(num_times):

    def decorator_repeat(func):

        def wrapper(*args, **kwargs):

            for _ in range(num_times):

                result = func(*args, **kwargs)

            return result

        return wrapper

    return decorator_repeat


@repeat(num_times=3)

def greet(name):

    print(f"Hello {name}")


greet("Alice")

In this example, the repeat decorator takes an argument num_times which determines how many times the decorated function should be called. The wrapper function then calls the original function (func) the specified number of times.

Decorators are a powerful tool  for keeping your code modular, DRY (Don't Repeat rself), and easy to read. They're heavily used in frameworks like Flask and Django for request handling, authentication, and more.

 


Post a Comment

Previous Post Next Post