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())
  1. A. inA inB outA! outB! after
  2. B. inA inB outB! outA after
  3. C. inA inB outB! outA! after
  4. 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

Exams that ask this topic