All quizzesHard
ExitStack & Exception Groups — Series 2
Preview — 3 of 10 questions
What is the output of the following code?
javascript
class Wrapper:
def __enter__(self):
return "not self"
def __exit__(self, *args):
pass
with Wrapper() as w:
print(w)
print(type(w))Anot self, <class 'str'>
B<__main__.Wrapper object at 0x...>, <class '__main__.Wrapper'> — as w always binds to the context manager instance itself, regardless of what __enter__ returns.
CNone, <class 'NoneType'>
DTypeError: __enter__() must return self
What is the output of the following code?
javascript
import io
from contextlib import redirect_stdout
buffer = io.StringIO()
with redirect_stdout(buffer):
print("captured!")
print("normal output")
print(repr(buffer.getvalue()))Acaptured!, then 'normal output\n' — redirect_stdout swaps which stream is captured vs. printed normally.
Bnormal output, 'captured!\n'
Cnormal output, '' — redirect_stdout discards output entirely instead of capturing it.
DTypeError: redirect_stdout() missing required argument
What is the output of the following code?
javascript
try:
raise ExceptionGroup("multi", [ValueError("v"), TypeError("t"), KeyError("k")])
except* (ValueError, TypeError) as eg:
print("caught:", sorted(str(e) for e in eg.exceptions))
except* KeyError as eg:
print("key error:", eg.exceptions)Acaught: ['v'], then caught: ['t'], then key error: (KeyError('k'),) — except* can only ever match one exception type per clause, even when a tuple is given.
BTypeError: except* does not accept a tuple of exception types
Ccaught: ['t', 'v'], key error: (KeyError('k'),)
Dkey error: (KeyError('k'),) only — the first except* clause silently absorbs everything and never prints, since a tuple type always matches greedily.
Sign up free to play
Answer all 10 questions (7 more), see explanations for every answer, and track your score.