Decorators in Python
Learn what decorators are in Python, how they work, and how to create your own decorators. Understand functions as first-class objects and how decorators modify behavior without changing original code.
Functions are First-Class Objects
In Python: - Functions can be assigned to variables - Functions can be passed as arguments - Functions can be returned from other functions This is the foundation of decorators.
Assign Function to a Variable
A function can be stored inside a variable and called using that variable.
Passing Functions as Arguments
Since functions are objects, they can be passed to other functions as arguments.
Passing a Function to Another Function
Here we pass a function as a parameter.
Returning Functions from Functions
A function can also return another function. This is called a higher-order function.
Returning a Function
Here a function returns another function.
What is a Decorator?
A decorator: - Takes a function as input - Adds some functionality - Returns a new function Decorators allow you to reuse logic like logging, authentication, timing, etc.
Creating a Simple Decorator
Let’s create a decorator that prints a message before and after a function runs.
Using @ Decorator Syntax
Instead of manually assigning the decorated function, Python allows us to use @decorator_name above the function definition.
Using @ Syntax
Rewrite the previous example using @ syntax.
Decorators with Function Arguments
When decorating functions that accept arguments, the wrapper must also accept arguments.
Handling Function Parameters
Modify the decorator to support arguments.
Best Practices for Decorators
1. Use decorators for reusable functionality. 2. Keep decorator logic simple and focused. 3. Use meaningful names (e.g., @log_execution, @authenticate). 4. Understand that decorators replace the original function. 5. Decorators are heavily used in frameworks like Flask and Django. Decorators are powerful and widely used in professional Python development.