ProgrammingVery hardTCS NQT · Python · Advanced

What is printed?

What is printed?
class T:
    def __init__(self, n): self.n = n
    def __enter__(self):
        print('in', self.n, end=' ')
        return self
    def __exit__(self, *a):
        print('out', self.n, end=' ')
        return True
with T(1) as a, T(2) as b:
    raise KeyError
print('done')
  1. A. in 1 in 2 out 1 out 2 done
  2. B. in 1 in 2 out 2 out 1 done
  3. C. in 1 in 2 out 2 out 1 followed by a KeyError traceback
  4. D. in 1 in 2 done

Correct answer: B. in 1 in 2 out 2 out 1 done

Context managers exit in reverse order (2 then 1); __exit__ returning True swallows the KeyError, so execution continues to print 'done'.

More Python Programming questions

Exams that ask this topic