Unlocking Python’s Decorator Magic!
Python Decorators: A Deep Dive into Function Wrappers
Introduction to decorators in Python
--
Decorators in Python allow us to add new attributes to a method, function, or class without affecting the existing ones.
This makes the code you create cleaner and more readable, as well as more maintainable.
Function Inside Other Function
It is possible to define a function inside another function in Python. In this example, the outer function has access to the inner function, and the inner function has access to the outer function’s variables and scope.
Returning A Function
Python allows you to return functions as parameters. Returning a function enables the creation of higher-level functions.
Understanding the syntax and usage of decorators
Syntax of Simple Decorators
In this example, we define greater_decorator
as a decorator. It accepts the parameter func and returns a new function named wrapper.
We do the activities we wish to conduct before and after the func within the Wrapper.
To utilize a decorator, we place the decorator’s name behind the @ sign.
In this code example, calling say_name()
performs the decorator version of this function.
You have now fixed the properties of the say_name()
function without modifying it directly.
Syntax of Decorators With One Argument
To accept a parameter in a decorator, a parameter must be added to the wrapper and the function used with the decorator (say_name()
in this example).
As seen above, “John” is first utilized as a parameter of the wrapper, and then it is passed to the func via the wrapper.
Syntax of Decorator With Multiple Arguments
As previously, you can utilize more than one parameter. But that would be a poor use of your time (unless you wish to limit the number of parameters that should be used).
This is due to the fact that you have limited the number of parameters that must be utilized in this manner, and the decorator you construct will not work with all functions.
You can circumvent this issue by using *args and **kwargs instead of a fixed number of parameters.