Decorators are a powerful feature in Python that allow us to modify or enhance the behavior of functions or classes without directly modifying their source code. Decorators are implemented using the concept of functions as first-class objects and function closures.
Let's explore decorators in Python:
# Creating a decorator function
def uppercase_decorator(func):
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
return result.upper()
return wrapper
# Applying the decorator to a function
@uppercase_decorator
def greet(name):
return f"Hello, {name}!"
# Calling the decorated function
print(greet("John")) # "HELLO, JOHN!"
# Applying the decorator manually
decorated_greet = uppercase_decorator(greet)
print(decorated_greet("Alice")) # "HELLO, ALICE!"
# Creating a decorator with arguments
def repeat_decorator(num_times):
def decorator(func):
def wrapper(*args, **kwargs):
for _ in range(num_times):
result = func(*args, **kwargs)
return result
return wrapper
return decorator
# Applying the decorator with arguments to a function
@repeat_decorator(3)
def say_hello(name):
print(f"Hello, {name}!")
# Calling the decorated function
say_hello("Alice")
# Output:
# "Hello, Alice!"
# "Hello, Alice!"
# "Hello, Alice!"
- Decorators are created using functions that take a function as input and return a modified or enhanced version of that function.
- The decorator function wraps the original function with additional functionality by defining an inner function (wrapper) that is called instead of the original function.
- The
*args
and**kwargs
allow the decorators to handle functions with different numbers of arguments and keyword arguments. - Decorators can be applied to functions using the
@decorator_name
syntax, or manually by assigning the result of the decorator function to the original function. - Decorators can also take arguments by creating nested functions. The outer function takes the arguments for the decorator, and the inner function serves as the actual decorator.
Now it's time for a practical task:
Write a decorator function called timing_decorator
that measures the execution time of a function and prints the time taken in seconds. Apply the timing_decorator
to a function of your choice and observe the execution time.
Once you've completed the task, you can proceed to the next lesson.