ProgrammingVery hardGATE CS · Product-company placement

What is printed?

What is printed?
class Ctx:
    def __init__(self, n): self.n = n
    def __enter__(self):
        print("in", self.n, end=" ")
        return self.n * 10
    def __exit__(self, et, ev, tb):
        print("out", self.n, end=" ")
        return self.n == 2
with Ctx(1) as a, Ctx(2) as b:
    print(a + b, end=" ")
    raise KeyError
print("after")
  1. A. in 1 in 2 30 out 1 out 2 after
  2. B. in 1 in 2 30 out 2 KeyError
  3. C. in 1 in 2 30 out 2 out 1 after
  4. D. in 1 in 2 3 out 2 out 1 after

Correct answer: C. in 1 in 2 30 out 2 out 1 after

Multiple context managers nest, so they exit in reverse order. __exit__ of Ctx(2) returns True, which suppresses the KeyError; Ctx(1)'s __exit__ then sees a normal exit, so execution continues to 'after'.

More Python Programming questions

Exams that ask this topic