Home >Backend Development >Python Tutorial >How to Create and Chain Function Decorators in Python?
How to Create Function Decorators and Chain Them Together
Introduction
Decorators in Python allow you to modify the behavior of functions without modifying the functions themselves. You can use decorators to add functionality, check input/output, and perform other operations before and after the function is called.
Creating a Decorator
To create a decorator, define a function that takes another function as an argument. This function should return a new function that wraps the original function.
def make_bold(fn): # The new function the decorator returns def wrapper(): # Insertion of some code before and after return "<b>" + fn() + "</b>" return wrapper
Chaining Decorators
You can chain decorators to apply multiple modifications to a function. Simply apply each decorator in turn, as shown below:
@make_bold @make_italic def say(): return "hello"
This code applies the make_bold decorator to the make_italic decorator, which in turn is applied to the say function. The result is that the say function returns a string that is both bold and italicized.
Example: Chain Decorators to Format Text
Suppose you have a function that returns a string of text. You want to add bold and italic formatting to the text. You can use the decorators defined above to achieve this:
@make_bold @make_italic def formatted_text(text): return text print(formatted_text("Hello world"))
Output:
<b><i>Hello world</i></b>
Passing Arguments to Decorators
You can pass arguments to decorators by enclosing the arguments in parentheses:
def a_decorator_passing_arguments(function_to_decorate): def a_wrapper_accepting_arguments(arg1, arg2): print("I got args! Look: {0}, {1}".format(arg1, arg2)) function_to_decorate(arg1, arg2) return a_wrapper_accepting_arguments @a_decorator_passing_arguments def print_full_name(first_name, last_name): print("My name is {0} {1}".format(first_name, last_name)) print_full_name("Peter", "Venkman")
Output:
I got args! Look: Peter, Venkman My name is Peter Venkman
Conclusion
By understanding how to create and chain decorators, you can extend the functionality of your Python functions. This powerful technique allows you to modify behavior, perform checks, and enhance your code in a modular and reusable way.
The above is the detailed content of How to Create and Chain Function Decorators in Python?. For more information, please follow other related articles on the PHP Chinese website!