28. Python Decorators
Python Decorators
A decorator is a design pattern in Python that allows a user to add new functionality to an existing object without modifying its structure. Decorators are usually called before the definition of a function you want to decorate.
Functions in Python are first-class citizens. This means they can be passed as arguments to other functions, returned from other functions, and assigned to variables. Decorators leverage this deeply.
Functions as Arguments
Before understanding decorators, you must understand that you can pass a function into another function as a variable.
Creating a Basic Decorator
A decorator is simply a function that takes another function as an argument, adds some kind of wrapper logic around it, and returns the newly wrapped function.
Syntactic Sugar: The @ Symbol
Python provides a much cleaner way to apply decorators using the @ symbol. You just place it directly above the function you want to decorate. It does exactly the same thing as the manual wrapping shown above.
Decorating Functions with Arguments
If the function you are decorating takes arguments, the inner wrapper function must also accept those arguments. The best way to handle this is by using *args and **kwargs to accept any number of arguments.
Knowledge Check
Ready to test your understanding of 28. Python Decorators?