Skip to content
CodeKruPro

Two context managers and an error in the body

Predict the outputMedium-HardPython only
main.py
class Res:
    def __init__(self, name):
        self.name = name

    def __enter__(self):
        print("enter", self.name)
        return self

    def __exit__(self, exc_type, exc, tb):
        print("exit", self.name, exc_type.__name__)
        return False

try:
    with Res("A"), Res("B"):
        print("body")
        raise ValueError("fail")
except ValueError as e:
    print("caught", e)
finally:
    print("finally")

This question is part of Pro+

Pro+ opens every question in Interview Prep and the mock interview. Every article and the first 2 questions of each topic stay free. Hands-on Selenium and API tasks follow their course lesson's own lock.

See Pro+

Already have Pro+? Sign in