ProgrammingHardIBM · Deloitte pattern
What is printed?
What is printed?
from contextlib import contextmanager
@contextmanager
def cm():
print("setup")
yield 1
print("teardown")
with cm() as v:
print("body", v)- A. setup body 1 teardown
- B. setup teardown body 1
- C. body 1 setup teardown
- D. setup body 1
Correct answer: A. setup body 1 teardown
@contextmanager splits the generator at yield: code before yield runs as __enter__ (printing 'setup' and giving v=1), the with-body runs next ('body 1'), and code after yield runs as __exit__ ('teardown').
More Python Programming questions
- What is printed? python class A: def enter(self): print("A enter"); return self def exit(self, a): print("A exit") class B: def…
- What is printed? python class A: def who(self): return "A" class B(A): def who(self): return "B" class C(A): def who(self): return "C"…
- What is printed? python class A: def f(self): return 1 class B(A): def f(self): return 2 + super().f() class C(B): def f(self): return 3 +…
- What is printed? python class F: @staticmethod def add(a, b): return a + b @classmethod def create(cls): return cls() print(F.add(2, 3)) f…
- What is printed? python class H: slots = ["a", "b"] h = H() h.a = 1 try: h.c = 2 except AttributeError: print("AttributeError") print(h.a)
- What is printed? python class K: x = 10 def method(self): x = 20 return x print(K().method(), K.x)