Quick Introduction Function Decorators in Python

Decorators are a powerful and versatile concept in Python that allows you to modify the behavior of functions without permanently altering their original code. They act like wrappers, accepting a function as an argument and returning a new function with additional capabilities. This approach promotes cleaner, more modular code and reusability.

How Decorators Work:

Benefits of Using Decorators:

Common Use Cases for Decorators:


def logging_decorator(func):

  """Decorator to log function calls."""

  def wrapper(*args, **kwargs):

    print(f"Calling function: {func.__name__} with arguments: {args}, {kwargs}")

    result = func(*args, **kwargs)

    print(f"Function {func.__name__} returned: {result}")

    return result

  return wrapper


@logging_decorator

def my_function(a, b):

  """Example function to be decorated."""

  return a + b


For example, when you run the code, you will get the following results for the input:


$python3 example4.py

Calling function: my_function with arguments: (5, 3), {}

Function my_function returned: 8


Looking to expand your Python knowledge? I recommend checking out the book "Mastering Learning Python 3: In Five Minutes." This resource offers a beginner-friendly approach with short, focused lessons that can help you grasp the fundamentals of Python 3 programming. (*** Now available on Amazon ***)