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')- A. in 1 in 2 out 1 out 2 done
- B. in 1 in 2 out 2 out 1 done
- C. in 1 in 2 out 2 out 1 followed by a KeyError traceback
- 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
- What is printed? python a = [1, 2, 3] a[1:2] = a a.insert(-1, 'x') a.insert(99, 'y') print(a, a.pop(-2), a.index(3))
- What is printed? python print(True + True, sum([True, False, True]), isinstance(True, int), [10, 20, 30][True], 'ab' False == '')
- What is printed? python class Meta(type): def new(m, name, bases, d): d['tag'] = name.lower() return super().new(m, name, bases, d) class…
- What is printed? python print(type(10 / 5))
- Which of these built-in Python types is immutable?
- What is printed? python s = "placement" print(s[2:5])