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")- A. in 1 in 2 30 out 1 out 2 after
- B. in 1 in 2 30 out 2 KeyError
- C. in 1 in 2 30 out 2 out 1 after
- 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
- What is printed? python from contextlib import contextmanager @contextmanager def cm(): print("A", end=" ") try: yield "B" except…
- What is printed? python from itertools import accumulate, chain, islice, count print(list(accumulate([1, 2, 3, 4])), list(chain("ab"…
- What is printed? python from itertools import ziplongest, product, combinations, permutations print(list(ziplongest("ab", [1, 2, 3]…
- What is printed? (Output lines are shown separated by " / ".) python from itertools import groupby data = [1, 1, 2, 1, 3, 3] print([(k…
- What is printed? python from functools import reduce print(reduce(lambda a, b: a 10 + b, [1, 2, 3]), reduce(lambda a, b: a + b, [], 7)…
- What is printed? python from functools import lrucache calls = 0 @lrucache(maxsize=2) def f(x): global calls calls += 1 return x for v in…