How To Infer Python Decorator Of A Method
Python Decorators in 10 minutes
Decorator crash class with pop existent-life usage examples
Update : This commodity is office of a series. Check out others "in x Minutes" topics here !
You may have noticed codes with @<something>
added right to a higher place a function, such as @staticmethod
, @classmethod
right in a higher place form methods, those are actually Python decorators. Decorators allow the extension of an existing function, without modifying the source code.
In this article, we will write our own Python decorators by understanding the structure of a decorator, exploring advanced behaviours such as overcoming the cons of decorators, multi-nested decorators, stacking decorators and finally some real-life usages.
Table of Contents
- Structure of a Decorator
- Advanced behaviours of Decorators
- Usage: Measure out execution time
- Usage: Debug with logging
- Usage: Create a singleton class
Structure of a Decorator
Decorators can be thought of every bit a function wrapper, meaning that it takes in a role as an argument and return a modified version of the role — adding extensions or capabilities to it.
From the structure shown above, we can run across that the function execution happens on line four, just we can alter what happens earlier, during and fifty-fifty after a function execution. Decorators can potentially change a function input, output or behaviour, but it is best to implement it in a style that does non reduce the understandability of the function it is wrapping.
Decorators are best used to add common behaviour to multiple functions without modifying every function manually
Advanced behaviours of Decorators
Retain metadata of wrapped function
One caveat of using decorators is that the function's metadata will be obscured by the decorator. In the code snippet from the previous section, nosotros are returning a wrapper
function instead of the original role, this ways that any decorated part will take their __name__
metadata overwritten to wrapper
.
In a technical sense, this would not affect the intended execution of the office or the decorator, only it is however a best practice to avert whatsoever unintended consequences of using a decorator. This can be done hands by adding a @wraps
decorator for the wrapper
part as shown below (line 5). The decorator tin be used in the same way, but the metadata of the wrapped function will not be overwritten now.
Decorators that accept arguments
Decorators are essentially a function (that wraps another part) and should be able to accept arguments. I notice it useful to pass in a Boolean variable then I can toggle the behaviour of the decorator, such as turning the press on and off if I want to enter or exit debugging manner. This can exist washed by wrapping the decorator in another function wrapper.
In the example below, I take a decorator debug_decorator
that can take arguments and returns a decorator
decorator which wraps the original part in wrapper
. This tin await quite complicated at first due to multiple nested functions. Information technology is recommended to write the original decorator kickoff and finally wrap information technology to have arguments.
Stacking decorators
As mentioned, decorators allow the extension of existing functions. Information technology is possible to stack multiple decorators above a role to add more extensions. The order of execution volition follow the order in which the decorators are stacked.
One thing to note is that fourth dimension-sensitive decorators should be added final if they are stacked. For example, decorators that measure execution time of function should be the last to be executed, then that they can reflect the execution time accurately without being influenced by other decorators.
Now, we take understood the structure of a decorator and their advanced behaviours, we can dive into their practical usage!
Usage: Measure execution fourth dimension
The timer
decorator tin measure the execution time of the wrapped function by recording the start time and end time of the function execution and printing the results to the console.
In the code snippet below, we measure the start_time
and end_time
before and after office execution which happens at line ten.
Usage: Debug with logging
The logging
decorator can exist used to log information to a console or log file and is useful for debugging. In the code snippet beneath, we'll use the logging
python package to perform logging.
Usage: Create a singleton class
The singleton
decorator can be used to create a singleton class. Singleton is a type of creational pattern design that restricts a class to have just ane instance. This is useful in cases where there is a limit on concurrent access to a shared resource, or a global point of access for a resource, such as imposing a limit on concurrent access to a database or a single point of access for a database.
Singleton classes can be coded specially to ensure single instantiation. Still, if there are multiple singleton classes, using decorators is a swell mode to reuse the code for multiple classes.
Promise you have learnt the basics of decorators, useful tips and practical examples of decorators. There are other usages such as using decorators for timeout operations, memoization and caching. Those decorators are more advanced, and it is amend to use built-in Python decorators or decorators from Python packages instead of implementing them yourself.
Finally, the codes shared in this article are summarized below,
Thank you for reading! If y'all liked this article, feel free to share it.
Source: https://towardsdatascience.com/python-decorators-in-10-minutes-c8bca1020235
Posted by: katzmanmainst93.blogspot.com
0 Response to "How To Infer Python Decorator Of A Method"
Post a Comment