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=' | ')
  1. A. in exit KeyError ok | in exit ValueError ok | in exit None ok |
  2. B. in exit KeyError caught KeyError | in exit ValueError ok | in exit None ok |
  3. C. in exit KeyError caught KeyError | in exit ValueError caught ValueError | in exit None ok |
  4. 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

Exams that ask this topic