CS FundamentalsVery hardProduct-company placement · Python interview
What does this code print (lines joined by ' / ')?
What does this code print (lines joined by ' / ')?
class Guard:
def __enter__(self):
print("enter")
return self
def __exit__(self, exc_type, exc, tb):
print("exit", exc_type.__name__ if exc_type else None)
return exc_type is ValueError
for err in (ValueError, KeyError):
try:
with Guard():
raise err("x")
print("after")
except Exception as e:
print("caught", type(e).__name__)- A. enter / exit ValueError / caught ValueError / enter / exit KeyError / caught KeyError
- B. enter / exit ValueError / after / enter / exit KeyError / after
- C. enter / exit ValueError / after / enter / exit KeyError / caught KeyError
- D. enter / caught ValueError / enter / caught KeyError
Correct answer: C. enter / exit ValueError / after / enter / exit KeyError / caught KeyError
__exit__ always runs; returning True suppresses the exception. For ValueError it returns True, so execution continues at 'after'. For KeyError it returns False, so the exception propagates to the except block.
Practise more Software Engineering, Git and Cloud Basics questionsSoftware Engineering, Git and Cloud Basics: notes and key points
More Software Engineering, Git and Cloud Basics questions
- Mixins rely on Python's method resolution order. What does this print? python class Base: def save(self): return ["Base"] class Log(Base)…
- This code illustrates the 'fragile base class' problem. What does it print? python class Bag: def init(self): self.items = [] def…
- What does this code print? python from abc import ABC, abstractmethod class Shape(ABC): @abstractmethod def area(self): ... def…
- Under design by contract, a method sqrt(x) has the precondition x ≥ 0. A caller passes -4 and the method fails. Whose bug is it, and which…
- A service catches every exception in a broad try/except, logs nothing and returns an empty list, so a database outage looks like 'no…
- How many of these defend against SQL injection in a login query: (1) parameterised queries / prepared statements, (2) escaping quotes by…