Python Decorators
Learn all about Python Decorators in this comprehensive tutorial.
- •Decorators let you add extra behavior to a function, without changing the function's code.
- •Define the decorator first, then apply it with @decorator_name above the function.
- •A decorator can be called multiple times.
- •Functions that require arguments can also be decorated, just make sure you pass the arguments to the wrapper function:
- •Decorators can accept their own arguments by adding another wrapper level.
- •You can use multiple decorators on one function.
- •Functions in Python has metadata that can be accessed using the __name__ and __doc__ attributes.
Introduction
Decorators let you add extra behavior to a function, without changing the function's code.
A decorator is a function that takes another function as input and returns a new function.
Basic Decorator
Define the decorator first, then apply it with @decorator_name above the function.
By placing @changecase directly above the function definition, the function myfunction is being "decorated" with the changecase function.
The function changecase is the decorator.
The function myfunction is the function that gets decorated.
Multiple Decorator Calls
A decorator can be called multiple times. Just place the decorator above the function you want to decorate.
Arguments in the Decorated Function
Functions that require arguments can also be decorated, just make sure you pass the arguments to the wrapper function:
*args and **kwargs
Decorator With Arguments
Decorators can accept their own arguments by adding another wrapper level.
Multiple Decorators
You can use multiple decorators on one function.
This is done by placing the decorator calls on top of each other.
Decorators are called in the reverse order, starting with the one closest to the function.
Preserving Function Metadata
Functions in Python has metadata that can be accessed using the __name__ and __doc__ attributes.
But, when a function is decorated, the metadata of the original function is lost.
To fix this, Python has a built-in function called functools.wraps that can be used to preserve the original function's name and docstring.
Module quiz
2 questionsWhich of the following is true about Python Decorators?
What is the most common pitfall when working with Python Decorators?
Answer all questions to submit.