ProgrammingHardPython · GATE DA · Advanced
What is printed?
What is printed?
class M:
def __enter__(self): print('in', end=' '); return self
def __exit__(self, t, v, tb):
print('exit', t.__name__ if t else None, end=' ')
return t is KeyError
for exc in (KeyError, ValueError, None):
try:
with M():
if exc: raise exc()
print('ok', end=' | ')
except Exception as e:
print('caught', type(e).__name__, end=' | ')- A. in exit KeyError ok | in exit ValueError ok | in exit None ok |
- B. in exit KeyError caught KeyError | in exit ValueError ok | in exit None ok |
- C. in exit KeyError caught KeyError | in exit ValueError caught ValueError | in exit None ok |
- D. in exit KeyError ok | in exit ValueError caught ValueError | in exit None ok |
Correct answer: D. in exit KeyError ok | in exit ValueError caught ValueError | in exit None ok |
A true return value from __exit__ swallows the exception, so the KeyError case continues after the with and prints 'ok'; ValueError propagates; with no exception __exit__ gets None.
More Python Programming questions
- What is printed? python a = [0] 3 m = [a] 2 m[0][1] = 5 n = [[0] 3 for in range(2)] n[0][1] = 5 print(m, n, a)
- What is printed? python try: try: 1 / 0 except ZeroDivisionError as e: raise ValueError('bad') from None except ValueError as v…
- What is printed? python def deco(tag): def w(f): def g(a): return f'<{tag}>' + f(a) + f'</{tag}>' return g return w @deco('b') @deco('i')…
- What is printed? python g = (x 2 for x in range(3)) lst = [1, 2, 3] h = (y for y in lst if y > n) n = 1 lst = [5] print(list(g), list(h))
- What is printed? python class A: def new(cls, v): print('new', v) return super().new(B) if v else super().new(cls) def init(self, v)…
- What is printed? python d = {'a': 1, 'b': 2, 'c': 3} del d['a'] d['a'] = 0 d |= {'b': 9, 'z': 4} print(list(d.items()), min(d, key=d.get))