ExitStack & Exception Groups — Series 3

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}")
        return False

with ExitStack() as stack:
    resources = [stack.enter_context(Resource(n)) for n in ["a", "b", "c"]]
    print("using resources")
Aopen a, open b, open c, using resources, close c, close b, close a
Bopen a, open b, open c, using resources, close a, close b, close c
Copen a, close a, open b, close b, open c, close c, using resources
Dusing resources, open a, open b, open c, close c, close b, close a

What is the output of the following code?

javascript
eg = ExceptionGroup("multiple failures", [ValueError("bad value"), TypeError("bad type")])
print(eg.message)
print(len(eg.exceptions))
print(type(eg.exceptions[0]).__name__)
print(type(eg.exceptions[1]).__name__)
ATypeError: ExceptionGroup() requires all exceptions to be the same type
Bmultiple failures, 2, ValueError, TypeError
C['bad value', 'bad type'], 2, ValueError, TypeError
Dmultiple failures, 1, ExceptionGroup, ExceptionGroup

What is the output of the following code?

javascript
import warnings

def risky_op():
    warnings.warn("something might be wrong", UserWarning)
    return 42

with warnings.catch_warnings(record=True) as caught:
    warnings.simplefilter("always")
    result = risky_op()
    print(result)
    print(len(caught))
    print(str(caught[0].message))
AUserWarning: something might be wrong (printed to stderr), 42
B42, 1, UserWarning
C42, 1, something might be wrong
D42, 0, IndexError: list index out of range

Sign up free to play

Answer all 10 questions (7 more), see explanations for every answer, and track your score.