Python Exercise: Make a chain of function decorators in Python
17. Create a Chain of Function Decorators (Bold, Italic, Underline, etc.)
Write a Python program to create a chain of function decorators (bold, italic, underline etc.).
Sample Solution:
Python Code:
# Define a decorator 'make_bold' that adds bold HTML tags to the wrapped function's return value
def make_bold(fn):
def wrapped():
return "<b>" + fn() + "</b>"
return wrapped
# Define a decorator 'make_italic' that adds italic HTML tags to the wrapped function's return value
def make_italic(fn):
def wrapped():
return "<i>" + fn() + "</i>"
return wrapped
# Define a decorator 'make_underline' that adds underline HTML tags to the wrapped function's return value
def make_underline(fn):
def wrapped():
return "<u>" + fn() + "</u>"
return wrapped
# Apply multiple decorators (@make_bold, @make_italic, @make_underline) to the 'hello' function
@make_bold
@make_italic
@make_underline
def hello():
return "hello world"
# Print the result of the decorated 'hello' function, which adds HTML tags for bold, italic, and underline
print(hello()) ## returns "<b><i><u>hello world</u></i></b>"
Sample Output:
hello world
Explanation:
In the exercise above the code defines three decorators ('make_bold', 'make_italic', and 'make_underline') that wrap a function by adding HTML tags for bold, italic, and underline, respectively. Then, it decorates the "hello()" function by applying multiple decorators (@make_bold, @make_italic, @make_underline) in a chained manner. Finally, it prints the result of the decorated "hello()" function, which includes HTML tags for bold, italic, and underline applied to the original return value "hello world".
Pictorial presentation:
Flowchart:

For more Practice: Solve these Related Problems:
- Write a Python program to implement three decorators that wrap a function’s return string with tags for bold, italic, and underline, and apply them in a chain.
- Write a Python program to create a decorator that applies multiple formatting options in sequence based on a list of tag names.
- Write a Python program to design decorators that conditionally apply formatting based on runtime parameters and chain them together.
- Write a Python program to implement a decorator factory that generates decorators for any given tag and then chain several of these to format output.
Python Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a Python function to create and print a list where the values are square of numbers between 1 and 30 (both included).
Next: Write a Python program to execute a string containing Python code.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics