Menu
Coddy logo textTech

Chaining Decorators

Lesson 7 of 12 in Coddy's Python Decorators course.

It's possible to chain multiple decorators together to modify the behavior of a function. To chain decorators, you simply apply them one after the other, with the innermost decorator closest to the function being decorated.

Here's an example:

def make_bold(func):
    def wrapper():
        return "<b>" + func() + "</b>"
    return wrapper

def make_italic(func):
    def wrapper():
        return "<i>" + func() + "</i>"
    return wrapper

@make_bold
@make_italic
def hello():
    return "Hello, world!"

print(hello())

The final output is:

<b><i>Hello, world!</i></b>

Notice that in the above example the decorator returns the value from the function, until now we only seen decorators which execute the function without returning it result!

challenge icon

Challenge

Medium

Write a function called my_decorator that takes an integer argument n and returns a decorator function that wraps a given function func in n layers of HTML tags. The outermost tag should be <div>, the next layer should be <p>, and so on, with each subsequent layer alternating between <div> and <p> tags. The innermost layer should wrap the output of the function in <b> tags.

You are given the code that will be executed with my_decorator, do not change it!

 

Example:

@my_decorator(3)
def my_function(s):
	return s.upper()

result = my_function("hello world")
print(result)

Output:

<div>
<p>
<div>
<b>
HELLO WORLD
</b>
</div>
</p>
</div>

Use new lines (\n) to format the output correctly!

Try it yourself

# Write code here


# Don't change below this line
n = int(input())

@my_decorator(n)
def my_function(s):
    return s.upper()

result = my_function(input())
print(result)

All lessons in Python Decorators