All quizzesHard
ExitStack & Exception Groups
Preview — 3 of 10 questions
What is the output of the following code?
javascript
from contextlib import ExitStack
class Resource:
def __init__(self, name):
self.name = name
def __enter__(self):
print(f"open {self.name}")
return self
def __exit__(self, *args):
print(f"close {self.name}")
names = ["a", "b", "c"]
with ExitStack() as stack:
resources = [stack.enter_context(Resource(n)) for n in names]
print("using all")ATypeError: ExitStack() takes no arguments
Bopen a, open b, open c, using all, close c, close b, close a
Copen a, open b, open c, using all, close a, close b, close c
Dopen a, close a, open b, close b, open c, close c, using all
What is the output of the following code?
javascript
try:
raise ExceptionGroup("multiple failures", [ValueError("bad value"), TypeError("bad type")])
except* ValueError as eg:
print(f"caught ValueError group: {eg.exceptions}")
except* TypeError as eg:
print(f"caught TypeError group: {eg.exceptions}")AOnly the first matching except* clause runs, exactly like a regular except, catching everything.
BNeither except* clause runs; the ExceptionGroup propagates uncaught.
Ccaught ValueError group: (ValueError('bad value'),) then caught TypeError group: (TypeError('bad type'),)
DTypeError: except* cannot be used with ExceptionGroup
What is the output of the following code?
javascript
class Faulty:
def __enter__(self):
print("entering")
raise RuntimeError("setup failed")
def __exit__(self, *args):
print("exiting")
return False
try:
with Faulty():
print("using")
except RuntimeError as e:
print(f"caught: {e}")Aentering, using, exiting, caught: setup failed
Bentering, exiting, caught: setup failed — "using" is never printed.
CTypeError: __enter__() cannot raise exceptions
Dentering then caught: setup failed — "exiting" and "using" are never printed.
Sign up free to play
Answer all 10 questions (7 more), see explanations for every answer, and track your score.