What are decorators in Python. Provide an example

Decorators are a powerful feature in Python that allow you to modify or enhance the behavior of functions or methods without changing their actual code. They are essentially higher-order functions that take a function as input and return a modified function.

Decorators are widely used for:

  • Logging

  • Timing function execution

  • Access control (e.g., authentication)

  • Caching (memoization)

  • Input validation

How Decorators Work

A decorator function "wraps" another function and adds functionality before and/or after it runs.

Example 1: Basic Decorator

def my_decorator(func):
    def wrapper():
        print("Something is happening before the function is called.")
        func()  # Call the original function
        print("Something is happening after the function is called.")
    return wrapper

@my_decorator
def say_hello():
    print("Hello!")

say_hello()

Output:

text
Something is happening before the function is called.
Hello!
Something is happening after the function is called.

Example 2: Decorator with Arguments

If the decorated function takes arguments, use *args and **kwargs:

python
def repeat(n_times):
    def decorator(func):
        def wrapper(*args, **kwargs):
            for _ in range(n_times):
                result = func(*args, **kwargs)
            return result
        return wrapper
    return decorator

@repeat(n_times=3)
def greet(name):
    print(f"Hello, {name}!")

greet("Alice")

Output:

text
Hello, Alice!
Hello, Alice!
Hello, Alice!

Example 3: Built-in Decorators

Python includes useful built-in decorators like:

  • @staticmethod (for static methods)

  • @classmethod (for class methods)

  • @property (for getter/setter methods)

python
class MyClass:
    @staticmethod
    def static_method():
        print("This is a static method.")

MyClass.static_method()  # Output: "This is a static method."


Key Takeaways

  • Decorators modify or extend functions without altering their original code.

  • They use the @decorator_name syntax.

  • They can accept arguments (@decorator(args)).

  • Useful for logging, timing, caching, authentication, etc.

To Top