A decorator in Python is a function that wraps another function to extend or alter its behavior. You can use decorators to modify the input, output, or the way a function works, all while keeping the original function intact. This allows for cleaner and more maintainable code, as it separates the logic for the additional functionality from the core function logic.
The beauty of decorators lies in their ability to add extra functionality to an existing function without altering the function’s structure directly. This is done by passing the function as an argument to the decorator, which then returns a new function that wraps the original one.
5 and 10, but we want to ensure that the subtraction always yields a positive result. Normally, we would modify the sub function, but we can use a decorator to add this functionality without altering the original function.
Here’s how a decorator can be applied to swap the values if the first value is smaller than the second:
Output:
In this case, we added the swapping logic inside the decorator dec_sub, ensuring the subtraction logic is never modified, while still extending its functionality.
dec_num checks if the input is negative and converts it to a positive value before passing it to the num function.
*args and **kwargs in the decorator definition.