ProgrammingVery hardProduct company OA

What is printed?

What is printed?
def tag(t):
    print("make", t, end=" ")
    def deco(fn):
        print("wrap", t, end=" ")
        def inner(*a):
            return f"<{t}>" + fn(*a) + f"</{t}>"
        return inner
    return deco
@tag("b")
@tag("i")
def hi(n): return "x" * n
print(hi(2), hi.__name__)
  1. A. make i wrap i make b wrap b <b><i>xx</i></b> inner
  2. B. make b make i wrap i wrap b <b><i>xx</i></b> inner
  3. C. make b make i wrap b wrap i <i><b>xx</b></i> inner
  4. D. make b make i wrap i wrap b <b><i>xx</i></b> hi

Correct answer: B. make b make i wrap i wrap b <b><i>xx</i></b> inner

The decorator EXPRESSIONS are evaluated top to bottom (make b, make i), but the resulting decorators are APPLIED bottom to top: hi = tag('b')(tag('i')(hi)), so 'wrap i' prints before 'wrap b' and the outermost tag is <b>. Without functools.wraps the name of the replacement function is 'inner'. Output: make b make i wrap i wrap b <b><i>xx</i></b> inner.

More Python Programming questions

Exams that ask this topic