ProgrammingVery hardProduct company OA
What is printed?
What is printed?
class CM:
def __init__(self, name, swallow): self.name, self.swallow = name, swallow
def __enter__(self): print("in" + self.name, end=" "); return self
def __exit__(self, et, ev, tb):
print("out" + self.name + ("!" if et else ""), end=" ")
return self.swallow
def run():
with CM("A", True), CM("B", False):
raise ValueError
return "body"
return "after"
print(run())- A. inA inB outA! outB! after
- B. inA inB outB! outA after
- C. inA inB outB! outA! after
- D. inA inB outB! outA! body
Correct answer: C. inA inB outB! outA! after
Managers are entered left to right and exited in reverse, like nested with blocks. B's __exit__ sees the ValueError and returns False, so the exception keeps propagating; A's __exit__ therefore also receives it (hence 'outA!') and returns True, which swallows it. Execution continues after the with statement and run returns 'after'. Had B swallowed it instead, A would have been called with no exception and printed plain 'outA'.
More Python Programming questions
- What is printed? python import bisect a = [1, 3, 3, 3, 7] i, j = bisect.bisectleft(a, 3), bisect.bisectright(a, 3) bisect.insortleft(a…
- What is printed? python from itertools import groupby s = "aabbbaac" g1 = [(k, len(list(v))) for k, v in groupby(s)] g2 = {k: len(list(v))…
- What is printed? python print("abc" 2 + "d", len("abc" 0))
- What is printed? python x = [10, 20, 30, 40, 50] print(x[-1], x[len(x) // 2], x[-2:])
- What is printed? python s = "Python" print(s.find("th"), s.find("z"), s.upper()[1:3])
- What is printed? python s = "a-b-c-d" print(s.split("-", 2), s.rsplit("-", 1))