ProgrammingHardTCS NQT pattern

What is printed?

What is printed?
counter = 0
def count_calls(f):
    def wrapper(*a, **kw):
        global counter
        counter += 1
        return f(*a, **kw)
    return wrapper

@count_calls
def a1(): pass
@count_calls
def a2(): pass

a1(); a1(); a2()
print(counter)
  1. A. 2
  2. B. 3
  3. C. 1
  4. D. 0

Correct answer: B. 3

Each decorated function shares the same module-level counter through the global statement. a1() runs twice and a2() runs once, so counter is incremented three times in total.

More Python Programming questions

Exams that ask this topic