Table of contents
Welcome to Day 23 of our Python journey! Today, we're learning a powerful feature of Python: decorators. This enhances the functionality and readability of our code by providing elegant ways to modify behavior or manage resources.
Decorators
In Python, decorators are functions that wrap other functions or methods, allowing you to add functionality to existing code without modifying its structure. Decorators are commonly used for tasks like logging, authentication, caching, and more.
The basic syntax of a decorator involves defining a decorator function and applying it to another function using the @
symbol
Simplified Decorator Concept
At its core, a decorator performs three key tasks:
Accepts a Function: Decorators take a function as their input parameter.
Enhances Functionality: They augment the behavior of the input function by adding extra features or functionality.
Returns a Modified Function: Finally, decorators return a new function, incorporating the additional functionality.
Basic Syntax of Decorator
def my_decorator(func):
#decorator logic
return func
@my_decorator
def my_function():
pass
In this , @my_decorator
is applied to the my_function
function. You can define the my_decorator
function to perform any custom logic you need, such as logging, authentication, or modifying the behavior of my_function
.
Here's how we create a decorator to handle subtraction:
def smart_subtract(func):
def inner(a, b):
print("subtracting", b, "from", a)
return func(a, b)
return inner
@smart_subtract
def subtract(a, b):
return a - b
result = subtract(10, 2)
print("Result after subtraction:", result)
The
smart_subtract
decorator takes a functionfunc
as its argument and defines aninner
function inside it.Inside the
inner
function, a message is printed indicating the operation about to be performed.The
func
is called with the provided arguments (a
andb
), and the result is returned.The
subtract
function is decorated with@smart_subtract
, which means it will be wrapped by theinner
function defined in the decorator.
Decorators can also be implemented using classes. This is useful for more complex scenarios where you need to maintain state or perform additional operations.