Decorators are a powerful feature in Python that allow you to modify the behavior of a function without changing its source code. They are a fundamental concept in functional programming, which encourages the use of pure functions, higher-order functions, and other functional programming techniques.
In this article, we’ll explore the basics of decorators and how they can help you write more expressive, modular, and maintainable Python code.
Understanding Decorators
In Python, a decorator is a function that takes another function as input, adds some functionality to it, and returns a new function. This new function can then be used in place of the original function. Decorators are defined using the @
symbol followed by the decorator function name, placed just before the function definition.
Here’s a simple example of a decorator that logs the arguments passed to a function:
def log_args(func):
def wrapper(*args, **kwargs):
print(f"Calling {func.__name__} with args={args} and kwargs={kwargs}")
return func(*args, **kwargs)
return wrapper
@log_args
def add_numbers(a, b):
return a + b
result = add_numbers(2, 3)
print(result)